commit 20d09e4ebb28c581990b9e0a17ba9dc23e0cd459 Author: changyunjia <905640960@qq.com> Date: Mon Jul 13 18:14:23 2026 +0800 首次提交 diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..703b673 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c7c3fbe --- /dev/null +++ b/.gitignore @@ -0,0 +1,63 @@ +# ---> AL +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ +*.app +.snapshots/* + +/Library +/Logs +/.vs/Crazy screws/FileContentIndex/*.vsidx +/.vs/Crazy screws/v17/*.suo +/*.csproj +/*.vsconfig +/obj/Debug/*.cache +/.vs/ScrewsMaster/FileContentIndex/*.vsidx +UserSettings/Search.settings +UserSettings/EditorUserSettings.asset +Temp/workerlic +Temp/UnityLockfile +Temp/FSTimeGet-158b49c4c882f4b7da2e46f692b474e2 +ScrewsMaster.sln +ProjectSettings/ProjectVersion.txt +ProjectSettings/PackageManagerSettings.asset +Packages/packages-lock.json +Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.137.0.txt.meta +Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.137.0.txt +Assets/PlayServicesResolver/Editor.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.VersionHandlerImpl.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.PackageManagerResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.PackageManagerResolver.dll.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.JarResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.JarResolver.dll.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.dll.meta +.vscode/settings.json +.vscode/launch.json +.vscode/extensions.json +ProjectSettings/ProjectVersion.txt +ProjectSettings/PackageManagerSettings.asset +Packages/packages-lock.json +Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.137.0.txt.meta +Assets/PlayServicesResolver/Editor/play-services-resolver_v1.2.137.0.txt +Assets/PlayServicesResolver/Editor.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.VersionHandlerImpl.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.PackageManagerResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.PackageManagerResolver.dll.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.JarResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.JarResolver.dll.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.dll.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.dll.meta +Packages/packages-lock.json +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.pdb.meta +Assets/ExternalDependencyManager/Editor/1.2.182/Google.IOSResolver.dll.meta +/Temp +/Assets/ExternalDependencyManager +/UserSettings/Layouts diff --git a/Assets/.DS_Store b/Assets/.DS_Store new file mode 100644 index 0000000..5d95178 Binary files /dev/null and b/Assets/.DS_Store differ diff --git a/Assets/Adaptive Performance.meta b/Assets/Adaptive Performance.meta new file mode 100644 index 0000000..b955b18 --- /dev/null +++ b/Assets/Adaptive Performance.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6f8175bbb5b26b14f982da1bcd23229f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset b/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset new file mode 100644 index 0000000..07889e9 --- /dev/null +++ b/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset @@ -0,0 +1,48 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &-2511651892639483336 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 536372c49e1ca914d822849d36de938c, type: 3} + m_Name: Android Providers + m_EditorClassIdentifier: + m_AutomaticLoading: 0 + m_AutomaticRunning: 0 + m_Loaders: + - {fileID: 11400000, guid: e53772c2b37b72d46ba5a580ba9e02c2, type: 2} + - {fileID: 11400000, guid: fafcd1dd02e5dee428bddffa0706eff3, type: 2} +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: cb0ece14d1f711a4fb9325ca819dee95, type: 3} + m_Name: AdaptivePerformanceGeneralSettings + m_EditorClassIdentifier: + Keys: 07000000 + Values: + - {fileID: 676180384865288505} +--- !u!114 &676180384865288505 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 179fc3111e144bc4688dca4038b3265d, type: 3} + m_Name: Android Settings + m_EditorClassIdentifier: + m_LoaderManagerInstance: {fileID: -2511651892639483336} + m_InitManagerOnStart: 1 diff --git a/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset.meta b/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset.meta new file mode 100644 index 0000000..720a9e8 --- /dev/null +++ b/Assets/Adaptive Performance/AdaptivePerformanceGeneralSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 503becd897ac82e4c85e42405210e889 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Provider.meta b/Assets/Adaptive Performance/Provider.meta new file mode 100644 index 0000000..a1d956a --- /dev/null +++ b/Assets/Adaptive Performance/Provider.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 268961098cbaab14385cdbbc5bec8e8f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset b/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset new file mode 100644 index 0000000..8dbf1b4 --- /dev/null +++ b/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset @@ -0,0 +1,14 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 7f64f689317e344bd94dad777079b3bb, type: 3} + m_Name: Google Android Provider Loader + m_EditorClassIdentifier: diff --git a/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset.meta b/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset.meta new file mode 100644 index 0000000..2b20bc3 --- /dev/null +++ b/Assets/Adaptive Performance/Provider/Google Android Provider Loader.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e53772c2b37b72d46ba5a580ba9e02c2 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset b/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset new file mode 100644 index 0000000..8d8e1bd --- /dev/null +++ b/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset @@ -0,0 +1,14 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 12368ffd90e3c4ac4889486ab7b2aa78, type: 3} + m_Name: Samsung Android Provider Loader + m_EditorClassIdentifier: diff --git a/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset.meta b/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset.meta new file mode 100644 index 0000000..638b86f --- /dev/null +++ b/Assets/Adaptive Performance/Provider/Samsung Android Provider Loader.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fafcd1dd02e5dee428bddffa0706eff3 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Settings.meta b/Assets/Adaptive Performance/Settings.meta new file mode 100644 index 0000000..7f34ca6 --- /dev/null +++ b/Assets/Adaptive Performance/Settings.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7e0834b3dfd4f094ab19b12c819cd999 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset b/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset new file mode 100644 index 0000000..6356d85 --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset @@ -0,0 +1,316 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 19bedd638b17440c6934f09de14d81c5, type: 3} + m_Name: Google Android Provider Settings + m_EditorClassIdentifier: + m_Logging: 1 + m_AutomaticPerformanceModeEnabled: 1 + m_EnableBoostOnStartup: 1 + m_StatsLoggingFrequencyInFrames: 50 + m_IndexerSettings: + m_Active: 1 + m_ThermalActionDelay: 10 + m_PerformanceActionDelay: 4 + m_ScalerSettings: + m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_scalerProfileList: + - m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_Name: Default Scaler Profile + m_DefaultScalerProfilerIndex: 0 + k_AssetVersion: 2 + m_GoogleProviderLogging: 0 diff --git a/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset.meta b/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset.meta new file mode 100644 index 0000000..e561c45 --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Google Android Provider Settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2f9255049e834c642a34ed9890be0bd6 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset b/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset new file mode 100644 index 0000000..1eddc1c --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset @@ -0,0 +1,318 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: 02a364304553d4fe797810bd5c88f9d8, type: 3} + m_Name: Samsung Android Provider Settings + m_EditorClassIdentifier: + m_Logging: 1 + m_AutomaticPerformanceModeEnabled: 1 + m_EnableBoostOnStartup: 1 + m_StatsLoggingFrequencyInFrames: 50 + m_IndexerSettings: + m_Active: 1 + m_ThermalActionDelay: 10 + m_PerformanceActionDelay: 4 + m_ScalerSettings: + m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_scalerProfileList: + - m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_Name: Default Scaler Profile + m_DefaultScalerProfilerIndex: 0 + k_AssetVersion: 2 + m_SamsungProviderLogging: 0 + m_HighSpeedVRR: 0 + m_AutomaticVRR: 1 diff --git a/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset.meta b/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset.meta new file mode 100644 index 0000000..1c009d2 --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Samsung Android Provider Settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f1dd90fcaad7acd4390f9a9092045f51 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset b/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset new file mode 100644 index 0000000..0f7e9f8 --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset @@ -0,0 +1,315 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 2 + 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: b592865877cb54284a5d1d88aec9cfbb, type: 3} + m_Name: Simulator Provider Settings + m_EditorClassIdentifier: + m_Logging: 1 + m_AutomaticPerformanceModeEnabled: 1 + m_EnableBoostOnStartup: 1 + m_StatsLoggingFrequencyInFrames: 50 + m_IndexerSettings: + m_Active: 1 + m_ThermalActionDelay: 10 + m_PerformanceActionDelay: 4 + m_ScalerSettings: + m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_scalerProfileList: + - m_AdaptiveFramerate: + m_Name: Adaptive Framerate + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 7 + m_MaxLevel: 45 + m_MinBound: 15 + m_MaxBound: 60 + m_AdaptiveResolution: + m_Name: Adaptive Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 6 + m_MaxLevel: 9 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveBatching: + m_Name: Adaptive Batching + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveLOD: + m_Name: Adaptive LOD + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.4 + m_MaxBound: 1 + m_AdaptiveLut: + m_Name: Adaptive Lut + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveMSAA: + m_Name: Adaptive MSAA + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 6 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowCascade: + m_Name: Adaptive Shadow Cascade + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 3 + m_MaxLevel: 2 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveShadowDistance: + m_Name: Adaptive Shadow Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowmapResolution: + m_Name: Adaptive Shadowmap Resolution + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 2 + m_MaxLevel: 3 + m_MinBound: 0.15 + m_MaxBound: 1 + m_AdaptiveShadowQuality: + m_Name: Adaptive Shadow Quality + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 3 + m_MaxLevel: 3 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveSorting: + m_Name: Adaptive Sorting + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveTransparency: + m_Name: Adaptive Transparency + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 1 + m_MinBound: 0 + m_MaxBound: 1 + m_AdaptiveViewDistance: + m_Name: Adaptive View Distance + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 2 + m_Target: 2 + m_MaxLevel: 40 + m_MinBound: 50 + m_MaxBound: 1000 + m_AdaptivePhysics: + m_Name: Adaptive Physics + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 0 + m_Target: 1 + m_MaxLevel: 5 + m_MinBound: 0.5 + m_MaxBound: 1 + m_AdaptiveDecals: + m_Name: Adaptive Decals + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 2 + m_MaxLevel: 20 + m_MinBound: 0.01 + m_MaxBound: 1 + m_AdaptiveLayerCulling: + m_Name: Adaptive Layer Culling + m_Enabled: 0 + m_Scale: 1 + m_VisualImpact: 1 + m_Target: 1 + m_MaxLevel: 40 + m_MinBound: 0.01 + m_MaxBound: 1 + m_Name: Default Scaler Profile + m_DefaultScalerProfilerIndex: 0 + k_AssetVersion: 2 diff --git a/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset.meta b/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset.meta new file mode 100644 index 0000000..153fb34 --- /dev/null +++ b/Assets/Adaptive Performance/Settings/Simulator Provider Settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9da72ca4bc391c459de173bc9bb740f +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData.meta b/Assets/AddressableAssetsData.meta new file mode 100644 index 0000000..86de620 --- /dev/null +++ b/Assets/AddressableAssetsData.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a43074c61e7cd2744a4d7cdebde0aa32 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AddressableAssetSettings.asset b/Assets/AddressableAssetsData/AddressableAssetSettings.asset new file mode 100644 index 0000000..7a82e1b --- /dev/null +++ b/Assets/AddressableAssetsData/AddressableAssetSettings.asset @@ -0,0 +1,109 @@ +%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: 468a46d0ae32c3544b7d98094e6448a9, type: 3} + m_Name: AddressableAssetSettings + m_EditorClassIdentifier: + m_DefaultGroup: 5d047487addee0649ac8829632be0676 + m_currentHash: + serializedVersion: 2 + Hash: 25b892d65a1d75f2c14eb8678a5875bb + m_OptimizeCatalogSize: 0 + m_BuildRemoteCatalog: 0 + m_BundleLocalCatalog: 0 + m_CatalogRequestsTimeout: 0 + m_DisableCatalogUpdateOnStart: 0 + m_IgnoreUnsupportedFilesInBuild: 0 + m_UniqueBundleIds: 0 + m_NonRecursiveBuilding: 1 + m_CCDEnabled: 0 + m_maxConcurrentWebRequests: 3 + m_ContiguousBundles: 1 + m_StripUnityVersionFromBundleBuild: 0 + m_DisableVisibleSubAssetRepresentations: 0 + m_ShaderBundleNaming: 0 + m_ShaderBundleCustomNaming: + m_MonoScriptBundleNaming: 0 + m_CheckForContentUpdateRestrictionsOption: 0 + m_MonoScriptBundleCustomNaming: + m_RemoteCatalogBuildPath: + m_Id: + m_RemoteCatalogLoadPath: + m_Id: + m_ContentStateBuildPathProfileVariableName: + m_CustomContentStateBuildPath: + m_ContentStateBuildPath: + m_BuildAddressablesWithPlayerBuild: 0 + m_overridePlayerVersion: '[UnityEditor.PlayerSettings.bundleVersion]' + m_GroupAssets: + - {fileID: 11400000, guid: 927975840aac92b40984ab99b521bfe2, type: 2} + - {fileID: 11400000, guid: eb308392fceb2d6468508538f61ec7af, type: 2} + m_BuildSettings: + m_CompileScriptsInVirtualMode: 0 + m_CleanupStreamingAssetsAfterBuilds: 1 + m_LogResourceManagerExceptions: 1 + m_BundleBuildPath: Temp/com.unity.addressables/AssetBundles + m_ProfileSettings: + m_Profiles: + - m_InheritedParent: + m_Id: e903a453b05f8104fa5aef1d8e879695 + m_ProfileName: Default + m_Values: + - m_Id: 62e79c1e07d89d0428f937528f1c4801 + m_Value: '[UnityEditor.EditorUserBuildSettings.activeBuildTarget]' + - m_Id: ed2d85858da9a754bbea005ed7914454 + m_Value: '[UnityEngine.AddressableAssets.Addressables.BuildPath]/[BuildTarget]' + - m_Id: ec93ed4c7f7766144ac93f6ff35b650c + m_Value: '{UnityEngine.AddressableAssets.Addressables.RuntimePath}/[BuildTarget]' + - m_Id: c21aeabe8e5097d46893180692def07a + m_Value: ServerData/[BuildTarget] + - m_Id: 87eddab52a67612499717764668b2c9c + m_Value: http://[PrivateIpAddress]:[HostingServicePort] + m_ProfileEntryNames: + - m_Id: 62e79c1e07d89d0428f937528f1c4801 + m_Name: BuildTarget + m_InlineUsage: 0 + - m_Id: ed2d85858da9a754bbea005ed7914454 + m_Name: Local.BuildPath + m_InlineUsage: 0 + - m_Id: ec93ed4c7f7766144ac93f6ff35b650c + m_Name: Local.LoadPath + m_InlineUsage: 0 + - m_Id: c21aeabe8e5097d46893180692def07a + m_Name: Remote.BuildPath + m_InlineUsage: 0 + - m_Id: 87eddab52a67612499717764668b2c9c + m_Name: Remote.LoadPath + m_InlineUsage: 0 + m_ProfileVersion: 1 + m_LabelTable: + m_LabelNames: + - config + m_SchemaTemplates: [] + m_GroupTemplateObjects: + - {fileID: 11400000, guid: fb02c9e8227032348bab7686d089e83c, type: 2} + m_InitializationObjects: [] + m_CertificateHandlerType: + m_AssemblyName: + m_ClassName: + m_ActivePlayerDataBuilderIndex: 3 + m_DataBuilders: + - {fileID: 11400000, guid: 914464090befcec4bb7a3b974ae8af6f, type: 2} + - {fileID: 11400000, guid: 60115c373d5134847a58b415a0ad0cb8, type: 2} + - {fileID: 11400000, guid: fb6601cebde001e47a401edd0ce7e086, type: 2} + - {fileID: 11400000, guid: c5b680bf794610d49b8497cccf38f502, type: 2} + m_ActiveProfileId: e903a453b05f8104fa5aef1d8e879695 + m_HostingServicesManager: + m_HostingServiceInfos: [] + m_Settings: {fileID: 11400000} + m_NextInstanceId: 0 + m_RegisteredServiceTypeRefs: [] + m_PingTimeoutInMilliseconds: 5000 diff --git a/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta b/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta new file mode 100644 index 0000000..bdc5cae --- /dev/null +++ b/Assets/AddressableAssetsData/AddressableAssetSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e4635826e7c48e841b2c1bfaf67911b4 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/Android.meta b/Assets/AddressableAssetsData/Android.meta new file mode 100644 index 0000000..d232af8 --- /dev/null +++ b/Assets/AddressableAssetsData/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 55be96c8ba4e01041a0ed7f2aaff9b7c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/Android/addressables_content_state.bin b/Assets/AddressableAssetsData/Android/addressables_content_state.bin new file mode 100644 index 0000000..05181bd Binary files /dev/null and b/Assets/AddressableAssetsData/Android/addressables_content_state.bin differ diff --git a/Assets/AddressableAssetsData/Android/addressables_content_state.bin.meta b/Assets/AddressableAssetsData/Android/addressables_content_state.bin.meta new file mode 100644 index 0000000..31b184c --- /dev/null +++ b/Assets/AddressableAssetsData/Android/addressables_content_state.bin.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a603977311abc6349a1cfa7c4357042b +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroupTemplates.meta b/Assets/AddressableAssetsData/AssetGroupTemplates.meta new file mode 100644 index 0000000..6f3672b --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroupTemplates.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 69e63d84f990c6d489257027617abcf7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset b/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset new file mode 100644 index 0000000..ec8d05a --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset @@ -0,0 +1,76 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &-8268349710405424442 +MonoBehaviour: + m_ObjectHideFlags: 1 + 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: 5834b5087d578d24c926ce20cd31e6d6, type: 3} + m_Name: ContentUpdateGroupSchema + m_EditorClassIdentifier: + m_Group: {fileID: 0} + m_StaticContent: 0 +--- !u!114 &-1758526770184641408 +MonoBehaviour: + m_ObjectHideFlags: 1 + 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: e5d17a21594effb4e9591490b009e7aa, type: 3} + m_Name: BundledAssetGroupSchema + m_EditorClassIdentifier: + m_Group: {fileID: 0} + m_InternalBundleIdMode: 1 + m_Compression: 1 + m_IncludeAddressInCatalog: 1 + m_IncludeGUIDInCatalog: 1 + m_IncludeLabelsInCatalog: 1 + m_InternalIdNamingMode: 0 + m_CacheClearBehavior: 0 + m_IncludeInBuild: 1 + m_BundledAssetProviderType: + m_AssemblyName: + m_ClassName: + m_ForceUniqueProvider: 0 + m_UseAssetBundleCache: 1 + m_UseAssetBundleCrc: 1 + m_UseAssetBundleCrcForCachedBundles: 1 + m_UseUWRForLocalBundles: 0 + m_Timeout: 0 + m_ChunkedTransfer: 0 + m_RedirectLimit: -1 + m_RetryCount: 0 + m_BuildPath: + m_Id: + m_LoadPath: + m_Id: + m_BundleMode: 0 + m_AssetBundleProviderType: + m_AssemblyName: + m_ClassName: + m_BundleNaming: 0 + m_AssetLoadMode: 0 +--- !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: 1a3c5d64ac83548c09dd1678b9f6f1cd, type: 3} + m_Name: Packed Assets + m_EditorClassIdentifier: + m_SchemaObjects: + - {fileID: -1758526770184641408} + - {fileID: -8268349710405424442} + m_Description: Pack assets into asset bundles. + m_Settings: {fileID: 11400000, guid: e4635826e7c48e841b2c1bfaf67911b4, type: 2} diff --git a/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset.meta b/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset.meta new file mode 100644 index 0000000..ca7cf5b --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroupTemplates/Packed Assets.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fb02c9e8227032348bab7686d089e83c +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups.meta b/Assets/AddressableAssetsData/AssetGroups.meta new file mode 100644 index 0000000..73c7608 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 78bcadb097a47a14fa6adbdc3775051b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset b/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset new file mode 100644 index 0000000..1c0b69c --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset @@ -0,0 +1,34 @@ +%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: bbb281ee3bf0b054c82ac2347e9e782c, type: 3} + m_Name: Built In Data + m_EditorClassIdentifier: + m_GroupName: Built In Data + m_Data: + m_SerializedData: [] + m_GUID: f136500d745b6754b86d4acd9dabbaaa + m_SerializeEntries: + - m_GUID: Resources + m_Address: Resources + m_ReadOnly: 1 + m_SerializedLabels: [] + FlaggedDuringContentUpdateRestriction: 0 + - m_GUID: EditorSceneList + m_Address: EditorSceneList + m_ReadOnly: 1 + m_SerializedLabels: [] + FlaggedDuringContentUpdateRestriction: 0 + m_ReadOnly: 1 + m_Settings: {fileID: 11400000, guid: e4635826e7c48e841b2c1bfaf67911b4, type: 2} + m_SchemaSet: + m_Schemas: + - {fileID: 11400000, guid: dc54a5c33f441e0438b553eb631f1ad3, type: 2} diff --git a/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset.meta b/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset.meta new file mode 100644 index 0000000..60cf771 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Built In Data.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 927975840aac92b40984ab99b521bfe2 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset b/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset new file mode 100644 index 0000000..0b10134 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset @@ -0,0 +1,31 @@ +%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: bbb281ee3bf0b054c82ac2347e9e782c, type: 3} + m_Name: Default Local Group + m_EditorClassIdentifier: + m_GroupName: Default Local Group + m_Data: + m_SerializedData: [] + m_GUID: 5d047487addee0649ac8829632be0676 + m_SerializeEntries: + - m_GUID: c1a09420c1d944149b93170add8b91e4 + m_Address: Assets/Configs + m_ReadOnly: 0 + m_SerializedLabels: + - config + FlaggedDuringContentUpdateRestriction: 0 + m_ReadOnly: 0 + m_Settings: {fileID: 11400000, guid: e4635826e7c48e841b2c1bfaf67911b4, type: 2} + m_SchemaSet: + m_Schemas: + - {fileID: 11400000, guid: a24ab3f109405a14c8a84679c99f458c, type: 2} + - {fileID: 11400000, guid: 7f5fc64834f066f45bfbeefa59100720, type: 2} diff --git a/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta b/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta new file mode 100644 index 0000000..17ffc1a --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Default Local Group.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eb308392fceb2d6468508538f61ec7af +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas.meta b/Assets/AddressableAssetsData/AssetGroups/Schemas.meta new file mode 100644 index 0000000..79a11ba --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8349bcbcf3830544cba29ead7d3d4308 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset b/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset new file mode 100644 index 0000000..2b23345 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset @@ -0,0 +1,17 @@ +%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: b1487f5d688e4f94f828f879d599dbdc, type: 3} + m_Name: Built In Data_PlayerDataGroupSchema + m_EditorClassIdentifier: + m_Group: {fileID: 11400000, guid: 927975840aac92b40984ab99b521bfe2, type: 2} + m_IncludeResourcesFolders: 1 + m_IncludeBuildSettingsScenes: 1 diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset.meta b/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset.meta new file mode 100644 index 0000000..b2ac841 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Built In Data_PlayerDataGroupSchema.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dc54a5c33f441e0438b553eb631f1ad3 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset new file mode 100644 index 0000000..1ff210e --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset @@ -0,0 +1,45 @@ +%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: e5d17a21594effb4e9591490b009e7aa, type: 3} + m_Name: Default Local Group_BundledAssetGroupSchema + m_EditorClassIdentifier: + m_Group: {fileID: 11400000, guid: eb308392fceb2d6468508538f61ec7af, type: 2} + m_InternalBundleIdMode: 1 + m_Compression: 1 + m_IncludeAddressInCatalog: 1 + m_IncludeGUIDInCatalog: 1 + m_IncludeLabelsInCatalog: 1 + m_InternalIdNamingMode: 0 + m_CacheClearBehavior: 0 + m_IncludeInBuild: 1 + m_BundledAssetProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.BundledAssetProvider + m_ForceUniqueProvider: 0 + m_UseAssetBundleCache: 1 + m_UseAssetBundleCrc: 1 + m_UseAssetBundleCrcForCachedBundles: 1 + m_UseUWRForLocalBundles: 0 + m_Timeout: 0 + m_ChunkedTransfer: 0 + m_RedirectLimit: -1 + m_RetryCount: 0 + m_BuildPath: + m_Id: ed2d85858da9a754bbea005ed7914454 + m_LoadPath: + m_Id: ec93ed4c7f7766144ac93f6ff35b650c + m_BundleMode: 0 + m_AssetBundleProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.AssetBundleProvider + m_BundleNaming: 0 + m_AssetLoadMode: 0 diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset.meta b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset.meta new file mode 100644 index 0000000..8c37e4e --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_BundledAssetGroupSchema.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7f5fc64834f066f45bfbeefa59100720 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset new file mode 100644 index 0000000..b0b8fa9 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset @@ -0,0 +1,16 @@ +%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: 5834b5087d578d24c926ce20cd31e6d6, type: 3} + m_Name: Default Local Group_ContentUpdateGroupSchema + m_EditorClassIdentifier: + m_Group: {fileID: 11400000, guid: eb308392fceb2d6468508538f61ec7af, type: 2} + m_StaticContent: 0 diff --git a/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset.meta b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset.meta new file mode 100644 index 0000000..478b739 --- /dev/null +++ b/Assets/AddressableAssetsData/AssetGroups/Schemas/Default Local Group_ContentUpdateGroupSchema.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a24ab3f109405a14c8a84679c99f458c +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DataBuilders.meta b/Assets/AddressableAssetsData/DataBuilders.meta new file mode 100644 index 0000000..dd65ee7 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d578dfc5d32d2814489c28572fbc70f4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset b/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset new file mode 100644 index 0000000..50d30dc --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset @@ -0,0 +1,20 @@ +%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: 88d21199f5d473f4db36845f2318f180, type: 3} + m_Name: BuildScriptFastMode + m_EditorClassIdentifier: + instanceProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.InstanceProvider + sceneProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.SceneProvider diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset.meta b/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset.meta new file mode 100644 index 0000000..3d80d92 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptFastMode.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 914464090befcec4bb7a3b974ae8af6f +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset new file mode 100644 index 0000000..ec875f9 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset @@ -0,0 +1,20 @@ +%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: 3e2e0ffa088c91d41a086d0b8cb16bdc, type: 3} + m_Name: BuildScriptPackedMode + m_EditorClassIdentifier: + instanceProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.InstanceProvider + sceneProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.SceneProvider diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset.meta b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset.meta new file mode 100644 index 0000000..bd2d923 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedMode.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c5b680bf794610d49b8497cccf38f502 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset new file mode 100644 index 0000000..7628845 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset @@ -0,0 +1,20 @@ +%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: ad8c280d42ee0ed41a27db23b43dd2bf, type: 3} + m_Name: BuildScriptPackedPlayMode + m_EditorClassIdentifier: + instanceProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.InstanceProvider + sceneProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.SceneProvider diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset.meta b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset.meta new file mode 100644 index 0000000..bb2df7d --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptPackedPlayMode.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fb6601cebde001e47a401edd0ce7e086 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset b/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset new file mode 100644 index 0000000..dfb2d58 --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset @@ -0,0 +1,20 @@ +%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: bb0e4994b34add1409fd8ccaf4a82de5, type: 3} + m_Name: BuildScriptVirtualMode + m_EditorClassIdentifier: + instanceProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.InstanceProvider + sceneProviderType: + m_AssemblyName: Unity.ResourceManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + m_ClassName: UnityEngine.ResourceManagement.ResourceProviders.SceneProvider diff --git a/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset.meta b/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset.meta new file mode 100644 index 0000000..6f7e23d --- /dev/null +++ b/Assets/AddressableAssetsData/DataBuilders/BuildScriptVirtualMode.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 60115c373d5134847a58b415a0ad0cb8 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/DefaultObject.asset b/Assets/AddressableAssetsData/DefaultObject.asset new file mode 100644 index 0000000..24980f7 --- /dev/null +++ b/Assets/AddressableAssetsData/DefaultObject.asset @@ -0,0 +1,15 @@ +%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: 3a189bb168d8d90478a09ea08c2f3d72, type: 3} + m_Name: DefaultObject + m_EditorClassIdentifier: + m_AddressableAssetSettingsGuid: e4635826e7c48e841b2c1bfaf67911b4 diff --git a/Assets/AddressableAssetsData/DefaultObject.asset.meta b/Assets/AddressableAssetsData/DefaultObject.asset.meta new file mode 100644 index 0000000..ad7dfaa --- /dev/null +++ b/Assets/AddressableAssetsData/DefaultObject.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 748083ea9e7d93645834ca69c3e18624 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset b/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset new file mode 100644 index 0000000..588fc4c --- /dev/null +++ b/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset @@ -0,0 +1,34 @@ +%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: 7e3976da977cb49238499ea3b4c237ae, type: 3} + m_Name: ProfileDataSourceSettings + m_EditorClassIdentifier: + profileGroupTypes: + - m_GroupTypePrefix: Built-In + m_Variables: + - m_Suffix: BuildPath + m_Value: '[UnityEngine.AddressableAssets.Addressables.BuildPath]/[BuildTarget]' + - m_Suffix: LoadPath + m_Value: '{UnityEngine.AddressableAssets.Addressables.RuntimePath}/[BuildTarget]' + - m_GroupTypePrefix: Editor Hosted + m_Variables: + - m_Suffix: BuildPath + m_Value: ServerData/[BuildTarget] + - m_Suffix: LoadPath + m_Value: http://[PrivateIpAddress]:[HostingServicePort] + environments: [] + currentEnvironment: + id: + projectId: + projectGenesisId: + name: + isDefault: 0 diff --git a/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset.meta b/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset.meta new file mode 100644 index 0000000..e73d629 --- /dev/null +++ b/Assets/AddressableAssetsData/ProfileDataSourceSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 87b43b98bb305f8428c324abbfb6b549 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/iOS.meta b/Assets/AddressableAssetsData/iOS.meta new file mode 100644 index 0000000..4d4b824 --- /dev/null +++ b/Assets/AddressableAssetsData/iOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 70e01f7be97d86d429f4c81b3c85e800 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AddressableAssetsData/iOS/addressables_content_state.bin b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin new file mode 100644 index 0000000..4900bf8 Binary files /dev/null and b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin differ diff --git a/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta new file mode 100644 index 0000000..82798d2 --- /dev/null +++ b/Assets/AddressableAssetsData/iOS/addressables_content_state.bin.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: fa827dd8bf035af47b74ff5c54f4bda1 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer.meta b/Assets/AppsFlyer.meta new file mode 100644 index 0000000..6f8a6ba --- /dev/null +++ b/Assets/AppsFlyer.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b9fa183d82b44f6795290513d09d9522 +timeCreated: 1730188675 \ No newline at end of file diff --git a/Assets/AppsFlyer/AFInAppEvents.cs b/Assets/AppsFlyer/AFInAppEvents.cs new file mode 100644 index 0000000..1f6d1fe --- /dev/null +++ b/Assets/AppsFlyer/AFInAppEvents.cs @@ -0,0 +1,72 @@ +using UnityEngine; +using System.Collections; + +public class AFInAppEvents { + /** + * Event Type + * */ + public const string LEVEL_ACHIEVED = "af_level_achieved"; + public const string ADD_PAYMENT_INFO = "af_add_payment_info"; + public const string ADD_TO_CART = "af_add_to_cart"; + public const string ADD_TO_WISH_LIST = "af_add_to_wishlist"; + public const string COMPLETE_REGISTRATION = "af_complete_registration"; + public const string TUTORIAL_COMPLETION = "af_tutorial_completion"; + public const string INITIATED_CHECKOUT = "af_initiated_checkout"; + public const string PURCHASE = "af_purchase"; + public const string RATE = "af_rate"; + public const string SEARCH = "af_search"; + public const string SPENT_CREDIT = "af_spent_credits"; + public const string ACHIEVEMENT_UNLOCKED = "af_achievement_unlocked"; + public const string CONTENT_VIEW = "af_content_view"; + public const string TRAVEL_BOOKING = "af_travel_booking"; + public const string SHARE = "af_share"; + public const string INVITE = "af_invite"; + public const string LOGIN = "af_login"; + public const string RE_ENGAGE = "af_re_engage"; + public const string UPDATE = "af_update"; + public const string OPENED_FROM_PUSH_NOTIFICATION = "af_opened_from_push_notification"; + public const string LOCATION_CHANGED = "af_location_changed"; + public const string LOCATION_COORDINATES = "af_location_coordinates"; + public const string ORDER_ID = "af_order_id"; + /** + * Event Parameter Name + * **/ + public const string LEVEL = "af_level"; + public const string SCORE = "af_score"; + public const string SUCCESS = "af_success"; + public const string PRICE = "af_price"; + public const string CONTENT_TYPE = "af_content_type"; + public const string CONTENT_ID = "af_content_id"; + public const string CONTENT_LIST = "af_content_list"; + public const string CURRENCY = "af_currency"; + public const string QUANTITY = "af_quantity"; + public const string REGSITRATION_METHOD = "af_registration_method"; + public const string PAYMENT_INFO_AVAILIBLE = "af_payment_info_available"; + public const string MAX_RATING_VALUE = "af_max_rating_value"; + public const string RATING_VALUE = "af_rating_value"; + public const string SEARCH_STRING = "af_search_string"; + public const string DATE_A = "af_date_a"; + public const string DATE_B = "af_date_b"; + public const string DESTINATION_A = "af_destination_a"; + public const string DESTINATION_B = "af_destination_b"; + public const string DESCRIPTION = "af_description"; + public const string CLASS = "af_class"; + public const string EVENT_START = "af_event_start"; + public const string EVENT_END = "af_event_end"; + public const string LATITUDE = "af_lat"; + public const string LONGTITUDE = "af_long"; + public const string CUSTOMER_USER_ID = "af_customer_user_id"; + public const string VALIDATED = "af_validated"; + public const string REVENUE = "af_revenue"; + public const string RECEIPT_ID = "af_receipt_id"; + public const string PARAM_1 = "af_param_1"; + public const string PARAM_2 = "af_param_2"; + public const string PARAM_3 = "af_param_3"; + public const string PARAM_4 = "af_param_4"; + public const string PARAM_5 = "af_param_5"; + public const string PARAM_6 = "af_param_6"; + public const string PARAM_7 = "af_param_7"; + public const string PARAM_8 = "af_param_8"; + public const string PARAM_9 = "af_param_9"; + public const string PARAM_10 = "af_param_10"; +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AFInAppEvents.cs.meta b/Assets/AppsFlyer/AFInAppEvents.cs.meta new file mode 100644 index 0000000..b31364e --- /dev/null +++ b/Assets/AppsFlyer/AFInAppEvents.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4075c6cf6f3d94b9a9f37f826e6a0e6f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AFMiniJSON.cs b/Assets/AppsFlyer/AFMiniJSON.cs new file mode 100644 index 0000000..d02bf2f --- /dev/null +++ b/Assets/AppsFlyer/AFMiniJSON.cs @@ -0,0 +1,547 @@ +/* + * Copyright (c) 2013 Calvin Rien + * + * Based on the JSON parser by Patrick van Bergen + * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html + * + * Simplified it so that it doesn't throw exceptions + * and can be used in Unity iPhone with maximum code stripping. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace AFMiniJSON { + // Example usage: + // + // using UnityEngine; + // using System.Collections; + // using System.Collections.Generic; + // using MiniJSON; + // + // public class MiniJSONTest : MonoBehaviour { + // void Start () { + // var jsonString = "{ \"array\": [1.44,2,3], " + + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + + // "\"int\": 65536, " + + // "\"float\": 3.1415926, " + + // "\"bool\": true, " + + // "\"null\": null }"; + // + // var dict = Json.Deserialize(jsonString) as Dictionary; + // + // Debug.Log("deserialized: " + dict.GetType()); + // Debug.Log("dict['array'][0]: " + ((List) dict["array"])[0]); + // Debug.Log("dict['string']: " + (string) dict["string"]); + // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles + // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs + // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); + // + // var str = Json.Serialize(dict); + // + // Debug.Log("serialized: " + str); + // } + // } + + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. + /// All numbers are parsed to doubles. + /// + public static class Json { + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false + public static object Deserialize(string json) { + // save the string for debug information + if (json == null) { + return null; + } + + return Parser.Parse(json); + } + + sealed class Parser : IDisposable { + const string WORD_BREAK = "{}[],:\""; + + public static bool IsWordBreak(char c) { + return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; + } + + enum TOKEN { + NONE, + CURLY_OPEN, + CURLY_CLOSE, + SQUARED_OPEN, + SQUARED_CLOSE, + COLON, + COMMA, + STRING, + NUMBER, + TRUE, + FALSE, + NULL + }; + + StringReader json; + + Parser(string jsonString) { + json = new StringReader(jsonString); + } + + public static object Parse(string jsonString) { + using (var instance = new Parser(jsonString)) { + return instance.ParseValue(); + } + } + + public void Dispose() { + json.Dispose(); + json = null; + } + + Dictionary ParseObject() { + Dictionary table = new Dictionary(); + + // ditch opening brace + json.Read(); + + // { + while (true) { + switch (NextToken) { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.CURLY_CLOSE: + return table; + default: + // name + string name = ParseString(); + if (name == null) { + return null; + } + + // : + if (NextToken != TOKEN.COLON) { + return null; + } + // ditch the colon + json.Read(); + + // value + table[name] = ParseValue(); + break; + } + } + } + + List ParseArray() { + List array = new List(); + + // ditch opening bracket + json.Read(); + + // [ + var parsing = true; + while (parsing) { + TOKEN nextToken = NextToken; + + switch (nextToken) { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.SQUARED_CLOSE: + parsing = false; + break; + default: + object value = ParseByToken(nextToken); + + array.Add(value); + break; + } + } + + return array; + } + + object ParseValue() { + TOKEN nextToken = NextToken; + return ParseByToken(nextToken); + } + + object ParseByToken(TOKEN token) { + switch (token) { + case TOKEN.STRING: + return ParseString(); + case TOKEN.NUMBER: + return ParseNumber(); + case TOKEN.CURLY_OPEN: + return ParseObject(); + case TOKEN.SQUARED_OPEN: + return ParseArray(); + case TOKEN.TRUE: + return true; + case TOKEN.FALSE: + return false; + case TOKEN.NULL: + return null; + default: + return null; + } + } + + string ParseString() { + StringBuilder s = new StringBuilder(); + char c; + + // ditch opening quote + json.Read(); + + bool parsing = true; + while (parsing) { + + if (json.Peek() == -1) { + parsing = false; + break; + } + + c = NextChar; + switch (c) { + case '"': + parsing = false; + break; + case '\\': + if (json.Peek() == -1) { + parsing = false; + break; + } + + c = NextChar; + switch (c) { + case '"': + case '\\': + case '/': + s.Append(c); + break; + case 'b': + s.Append('\b'); + break; + case 'f': + s.Append('\f'); + break; + case 'n': + s.Append('\n'); + break; + case 'r': + s.Append('\r'); + break; + case 't': + s.Append('\t'); + break; + case 'u': + var hex = new char[4]; + + for (int i=0; i< 4; i++) { + hex[i] = NextChar; + } + + s.Append((char) Convert.ToInt32(new string(hex), 16)); + break; + } + break; + default: + s.Append(c); + break; + } + } + + return s.ToString(); + } + + object ParseNumber() { + string number = NextWord; + + if (number.IndexOf('.') == -1) { + long parsedInt; + Int64.TryParse(number, out parsedInt); + return parsedInt; + } + + double parsedDouble; + Double.TryParse(number, out parsedDouble); + return parsedDouble; + } + + void EatWhitespace() { + while (Char.IsWhiteSpace(PeekChar)) { + json.Read(); + + if (json.Peek() == -1) { + break; + } + } + } + + char PeekChar { + get { + return Convert.ToChar(json.Peek()); + } + } + + char NextChar { + get { + return Convert.ToChar(json.Read()); + } + } + + string NextWord { + get { + StringBuilder word = new StringBuilder(); + + while (!IsWordBreak(PeekChar)) { + word.Append(NextChar); + + if (json.Peek() == -1) { + break; + } + } + + return word.ToString(); + } + } + + TOKEN NextToken { + get { + EatWhitespace(); + + if (json.Peek() == -1) { + return TOKEN.NONE; + } + + switch (PeekChar) { + case '{': + return TOKEN.CURLY_OPEN; + case '}': + json.Read(); + return TOKEN.CURLY_CLOSE; + case '[': + return TOKEN.SQUARED_OPEN; + case ']': + json.Read(); + return TOKEN.SQUARED_CLOSE; + case ',': + json.Read(); + return TOKEN.COMMA; + case '"': + return TOKEN.STRING; + case ':': + return TOKEN.COLON; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN.NUMBER; + } + + switch (NextWord) { + case "false": + return TOKEN.FALSE; + case "true": + return TOKEN.TRUE; + case "null": + return TOKEN.NULL; + } + + return TOKEN.NONE; + } + } + } + + /// + /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string + /// + /// A Dictionary<string, object> / List<object> + /// A JSON encoded string, or null if object 'json' is not serializable + public static string Serialize(object obj) { + return Serializer.Serialize(obj); + } + + sealed class Serializer { + StringBuilder builder; + + Serializer() { + builder = new StringBuilder(); + } + + public static string Serialize(object obj) { + var instance = new Serializer(); + + instance.SerializeValue(obj); + + return instance.builder.ToString(); + } + + void SerializeValue(object value) { + IList asList; + IDictionary asDict; + string asStr; + + if (value == null) { + builder.Append("null"); + } else if ((asStr = value as string) != null) { + SerializeString(asStr); + } else if (value is bool) { + builder.Append((bool) value ? "true" : "false"); + } else if ((asList = value as IList) != null) { + SerializeArray(asList); + } else if ((asDict = value as IDictionary) != null) { + SerializeObject(asDict); + } else if (value is char) { + SerializeString(new string((char) value, 1)); + } else { + SerializeOther(value); + } + } + + void SerializeObject(IDictionary obj) { + bool first = true; + + builder.Append('{'); + + foreach (object e in obj.Keys) { + if (!first) { + builder.Append(','); + } + + SerializeString(e.ToString()); + builder.Append(':'); + + SerializeValue(obj[e]); + + first = false; + } + + builder.Append('}'); + } + + void SerializeArray(IList anArray) { + builder.Append('['); + + bool first = true; + + foreach (object obj in anArray) { + if (!first) { + builder.Append(','); + } + + SerializeValue(obj); + + first = false; + } + + builder.Append(']'); + } + + void SerializeString(string str) { + builder.Append('\"'); + + char[] charArray = str.ToCharArray(); + foreach (var c in charArray) { + switch (c) { + case '"': + builder.Append("\\\""); + break; + case '\\': + builder.Append("\\\\"); + break; + case '\b': + builder.Append("\\b"); + break; + case '\f': + builder.Append("\\f"); + break; + case '\n': + builder.Append("\\n"); + break; + case '\r': + builder.Append("\\r"); + break; + case '\t': + builder.Append("\\t"); + break; + default: + int codepoint = Convert.ToInt32(c); + if ((codepoint >= 32) && (codepoint <= 126)) { + builder.Append(c); + } else { + builder.Append("\\u"); + builder.Append(codepoint.ToString("x4")); + } + break; + } + } + + builder.Append('\"'); + } + + void SerializeOther(object value) { + // NOTE: decimals lose precision during serialization. + // They always have, I'm just letting you know. + // Previously floats and doubles lost precision too. + if (value is float) { + builder.Append(((float) value).ToString("R")); + } else if (value is int + || value is uint + || value is long + || value is sbyte + || value is byte + || value is short + || value is ushort + || value is ulong) { + builder.Append(value); + } else if (value is double + || value is decimal) { + builder.Append(Convert.ToDouble(value).ToString("R")); + } else { + SerializeString(value.ToString()); + } + } + } + } +} diff --git a/Assets/AppsFlyer/AFMiniJSON.cs.meta b/Assets/AppsFlyer/AFMiniJSON.cs.meta new file mode 100644 index 0000000..11ec5c9 --- /dev/null +++ b/Assets/AppsFlyer/AFMiniJSON.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc3d1c806d507463e9b560eb09d8eb0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs b/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs new file mode 100644 index 0000000..6762c97 --- /dev/null +++ b/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; + +namespace AppsFlyerSDK +{ + public enum AFPurchaseType + { + Subscription = 0, + OneTimePurchase = 1 + } + + /// + // + /// + public class AFPurchaseDetailsAndroid + + { + public AFPurchaseType purchaseType { get; private set; } + public string purchaseToken { get; private set; } + public string productId { get; private set; } + public string price { get; private set; } + public string currency { get; private set; } + + public AFPurchaseDetailsAndroid(AFPurchaseType type, String purchaseToken, String productId, String price, String currency) + { + this.purchaseType = type; + this.purchaseToken = purchaseToken; + this.productId = productId; + this.price = price; + this.currency = currency; + } + + } + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs.meta b/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs.meta new file mode 100644 index 0000000..6d0024d --- /dev/null +++ b/Assets/AppsFlyer/AFPurchaseDetailsAndroid.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d71b3864006f94ac08938b2ebdc940bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs b/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs new file mode 100644 index 0000000..f159eea --- /dev/null +++ b/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace AppsFlyerSDK +{ + /// + // + /// + public class AFSDKPurchaseDetailsIOS + { + public string productId { get; private set; } + public string price { get; private set; } + public string currency { get; private set; } + public string transactionId { get; private set; } + + private AFSDKPurchaseDetailsIOS(string productId, string price, string currency, string transactionId) + { + this.productId = productId; + this.price = price; + this.currency = currency; + this.transactionId = transactionId; + } + + public static AFSDKPurchaseDetailsIOS Init(string productId, string price, string currency, string transactionId) + { + return new AFSDKPurchaseDetailsIOS(productId, price, currency, transactionId); + } + } + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs.meta b/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs.meta new file mode 100644 index 0000000..f33ebcc --- /dev/null +++ b/Assets/AppsFlyer/AFSDKPurchaseDetailsIOS.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 44bb6c4472701416080eb050732075ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs b/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs new file mode 100644 index 0000000..e877fbd --- /dev/null +++ b/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; + +namespace AppsFlyerSDK +{ + public enum AFSDKValidateAndLogStatus + { + AFSDKValidateAndLogStatusSuccess, + AFSDKValidateAndLogStatusFailure, + AFSDKValidateAndLogStatusError + } + + + /// + // + /// + public class AFSDKValidateAndLogResult + { + public AFSDKValidateAndLogStatus status { get; private set; } + public Dictionary result { get; private set; } + public Dictionary errorData { get; private set; } + public string error { get; private set; } + + private AFSDKValidateAndLogResult(AFSDKValidateAndLogStatus status, Dictionary result, Dictionary errorData, string error) + { + this.status = status; + this.result = result; + this.errorData = errorData; + this.error = error; + } + + public static AFSDKValidateAndLogResult Init(AFSDKValidateAndLogStatus status, Dictionary result, Dictionary errorData, string error) + { + return new AFSDKValidateAndLogResult(status, result, errorData, error); + } + } + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs.meta b/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs.meta new file mode 100644 index 0000000..63d4835 --- /dev/null +++ b/Assets/AppsFlyer/AFSDKValidateAndLogResult.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2df1c6f1eab2e4849bf2762a8d78933f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyer.asmdef b/Assets/AppsFlyer/AppsFlyer.asmdef new file mode 100644 index 0000000..381ee00 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyer.asmdef @@ -0,0 +1,13 @@ +{ + "name": "AppsFlyer", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AppsFlyer.asmdef.meta b/Assets/AppsFlyer/AppsFlyer.asmdef.meta new file mode 100644 index 0000000..380f36a --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyer.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2a37df438292d4903b4e5159c5de3bf9 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyer.cs b/Assets/AppsFlyer/AppsFlyer.cs new file mode 100644 index 0000000..e942a7a --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyer.cs @@ -0,0 +1,1086 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace AppsFlyerSDK +{ + public class AppsFlyer : MonoBehaviour + { + public static readonly string kAppsFlyerPluginVersion = "6.14.4"; + public static string CallBackObjectName = null; + private static EventHandler onRequestResponse; + private static EventHandler onInAppResponse; + private static EventHandler onDeepLinkReceived; + public static IAppsFlyerNativeBridge instance = null; + public delegate void unityCallBack(string message); + + + /// + /// Initialize the AppsFlyer SDK with your devKey and appID. + /// The dev key is required on all platforms, and the appID is required for iOS. + /// If you app is for Android only pass null for the appID. + /// + /// AppsFlyer's Dev-Key, which is accessible from your AppsFlyer account under 'App Settings' in the dashboard. + /// Your app's Apple ID. + /// + /// + /// AppsFlyer.initSDK("K2***********99", "41*****44""); + /// + /// + public static void initSDK(string devKey, string appID) + { + initSDK(devKey, appID, null); + } + + /// + /// Initialize the AppsFlyer SDK with your devKey and appID. + /// The dev key is required on all platforms, and the appID is required for iOS. + /// If you app is for Android only pass null for the appID. + /// + /// AppsFlyer's Dev-Key, which is accessible from your AppsFlyer account under 'App Settings' in the dashboard. + /// Your app's Apple ID. + /// pass the script of the game object being used. + /// + /// + /// AppsFlyer.initSDK("K2***********99", 41*****44, this); + /// + /// + public static void initSDK(string devKey, string appID, MonoBehaviour gameObject) + { + + if (gameObject != null) + { +#if UNITY_STANDALONE_OSX + CallBackObjectName = gameObject.GetType().ToString(); +#else + CallBackObjectName = gameObject.name; +#endif + } + +#if UNITY_IOS || UNITY_STANDALONE_OSX + if (instance == null || !instance.isInit) + { + instance = new AppsFlyeriOS(devKey, appID, gameObject); + instance.isInit = true; + } +#elif UNITY_ANDROID + if (instance == null || !instance.isInit) + { + AppsFlyerAndroid appsFlyerAndroid = new AppsFlyerAndroid(); + appsFlyerAndroid.initSDK(devKey, gameObject); + instance = appsFlyerAndroid; + instance.isInit = true; + + } +#elif UNITY_WSA_10_0 + AppsFlyerWindows.InitSDK(devKey, appID, gameObject); + if (gameObject != null) + { + AppsFlyerWindows.GetConversionData(gameObject.name); + } +#else + +#endif + } + + + /// + /// Once this API is invoked, our SDK will start. + /// Once the API is called a sessions will be immediately sent, and all background forground transitions will send a session. + /// + public static void startSDK() + { +#if UNITY_WSA_10_0 + AppsFlyerWindows.Start(); + +#else + if (instance != null) + { + instance.startSDK(onRequestResponse != null, CallBackObjectName); + } +#endif + } + + + + + + + /// + /// Send an In-App Event. + /// In-App Events provide insight on what is happening in your app. + /// + /// Event Name as String. + /// Event Values as Dictionary. + public static void sendEvent(string eventName, Dictionary eventValues) + { +#if UNITY_WSA_10_0 && !UNITY_EDITOR + AppsFlyerWindows.LogEvent(eventName, eventValues); +#else + if (instance != null) + { + instance.sendEvent(eventName, eventValues, onInAppResponse != null, CallBackObjectName); + } +#endif + } + /// + /// Once this API is invoked, our SDK no longer communicates with our servers and stops functioning. + /// In some extreme cases you might want to shut down all SDK activity due to legal and privacy compliance. + /// This can be achieved with the stopSDK API. + /// + /// should sdk be stopped. + public static void stopSDK(bool isSDKStopped) + { + if (instance != null) + { + instance.stopSDK(isSDKStopped); + } + } + + // + /// Was the stopSDK(boolean) API set to true. + /// + /// boolean isSDKStopped. + public static bool isSDKStopped() + { + if (instance != null) + { + return instance.isSDKStopped(); + } + + return false; + } + + /// + /// Get the AppsFlyer SDK version used in app. + /// + /// The current SDK version. + public static string getSdkVersion() + { + if (instance != null) + { + return instance.getSdkVersion(); + } + + return ""; + + } + + /// + /// Enables Debug logs for the AppsFlyer SDK. + /// Should only be set to true in development / debug. + /// + /// shouldEnable boolean. + public static void setIsDebug(bool shouldEnable) + { + if (instance != null) + { + instance.setIsDebug(shouldEnable); + } else { +#if UNITY_IOS || UNITY_STANDALONE_OSX + instance = new AppsFlyeriOS(); + instance.setIsDebug(shouldEnable); +#elif UNITY_ANDROID + instance = new AppsFlyerAndroid(); + instance.setIsDebug(shouldEnable); +#else + +#endif + } + + } + + /// + /// Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs. + /// This ID is available in AppsFlyer CSV reports along with Postback APIs for cross-referencing with your internal IDs. + /// + /// Customer ID for client. + public static void setCustomerUserId(string id) + { +#if UNITY_WSA_10_0 && !UNITY_EDITOR + AppsFlyerWindows.SetCustomerUserId(id); +#else + if (instance != null) + { + instance.setCustomerUserId(id); + } +#endif + } + + /// + /// Set the OneLink ID that should be used for User-Invite-API. + /// The link that is generated for the user invite will use this OneLink as the base link. + /// + /// OneLink ID obtained from the AppsFlyer Dashboard. + public static void setAppInviteOneLinkID(string oneLinkId) + { + + if (instance != null) + { + instance.setAppInviteOneLinkID(oneLinkId); + } + + + } + + /// + /// Set the deepLink timeout value that should be used for DDL. + /// + /// deepLink timeout in milliseconds. + public static void setDeepLinkTimeout(long deepLinkTimeout) + { + + if (instance != null) + { + instance.setDeepLinkTimeout(deepLinkTimeout); + } + + + } + + /// + /// Set additional data to be sent to AppsFlyer. + /// + /// additional data Dictionary. + public static void setAdditionalData(Dictionary customData) + { + + if (instance != null) + { + instance.setAdditionalData(customData); + } + + + } + + /// + /// Advertisers can wrap AppsFlyer OneLink within another Universal Link. + /// This Universal Link will invoke the app but any deep linking data will not propagate to AppsFlyer. + /// + /// Array of urls. + public static void setResolveDeepLinkURLs(params string[] urls) + { + + if (instance != null) + { + instance.setResolveDeepLinkURLs(urls); + } + + + } + + + /// + /// Advertisers can use this method to set vanity onelink domains. + /// + /// Array of domains. + public static void setOneLinkCustomDomain(params string[] domains) + { + + if (instance != null) + { + instance.setOneLinkCustomDomain(domains); + } + else + { +#if UNITY_IOS || UNITY_STANDALONE_OSX + instance = new AppsFlyeriOS(); +#elif UNITY_ANDROID + instance = new AppsFlyerAndroid(); +#else + +#endif + + + + } + } + + /// + /// Setting user local currency code for in-app purchases. + /// The currency code should be a 3 character ISO 4217 code. (default is USD). + /// You can set the currency code for all events by calling the following method. + /// + /// 3 character ISO 4217 code. + public static void setCurrencyCode(string currencyCode) + { + + if (instance != null) + { + instance.setCurrencyCode(currencyCode); + } else { +#if UNITY_IOS || UNITY_STANDALONE_OSX + instance = new AppsFlyeriOS(); + instance.setCurrencyCode(currencyCode); +#elif UNITY_ANDROID + instance = new AppsFlyerAndroid(); + instance.setCurrencyCode(currencyCode); +#else +#endif + } + } + + /// + /// Sets or updates the user consent data related to GDPR and DMA regulations for advertising and data usage purposes within the application. + /// + /// instance of AppsFlyerConsent. + public static void setConsentData(AppsFlyerConsent appsFlyerConsent) + { + if (instance != null) + { + instance.setConsentData(appsFlyerConsent); + } + } + + /// + /// Manually record the location of the user. + /// + /// latitude as double. + /// longitude as double. + public static void recordLocation(double latitude, double longitude) + { + + if (instance != null) + { + instance.recordLocation(latitude, longitude); + } + + + } + + /// + /// Anonymize user Data. + /// Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions. + /// Default is false. + /// + /// shouldAnonymizeUser boolean. + public static void anonymizeUser(bool shouldAnonymizeUser) + { + + if (instance != null) + { + instance.anonymizeUser(shouldAnonymizeUser); + } + + + } + + /// + /// Calling enableTCFDataCollection(true) will enable collecting and sending any TCF related data. + /// Calling enableTCFDataCollection(false) will disable the collection of TCF related data and from sending it. + /// + /// should start TCF Data collection boolean. + public static void enableTCFDataCollection(bool shouldCollectTcfData) + { + if (instance != null) + { + instance.enableTCFDataCollection(shouldCollectTcfData); + } + } + + /// + /// Get AppsFlyer's unique device ID which is created for every new install of an app. + /// + /// AppsFlyer's unique device ID. + public static string getAppsFlyerId() + { +#if UNITY_WSA_10_0 && !UNITY_EDITOR + return AppsFlyerWindows.GetAppsFlyerId(); +#else + if (instance != null) + { + return instance.getAppsFlyerId(); + } +#endif + return string.Empty; + + } + + /// + /// Set a custom value for the minimum required time between sessions. + /// By default, at least 5 seconds must lapse between 2 app launches to count as separate 2 sessions. + /// + /// minimum time between 2 separate sessions in seconds. + public static void setMinTimeBetweenSessions(int seconds) + { + + if (instance != null) + { + instance.setMinTimeBetweenSessions(seconds); + } + + + } + + /// + /// Set a custom host. + /// + /// Host prefix. + /// Host name. + public static void setHost(string hostPrefixName, string hostName) + { + + if (instance != null) + { + instance.setHost(hostPrefixName, hostName); + } else { +#if UNITY_IOS || UNITY_STANDALONE_OSX + instance = new AppsFlyeriOS(); + instance.setHost(hostPrefixName, hostName); +#elif UNITY_ANDROID + instance = new AppsFlyerAndroid(); + instance.setHost(hostPrefixName, hostName); +#else +#endif + } + } + + /// + /// Set the user emails and encrypt them. + /// cryptMethod Encryption method: + /// EmailCryptType.EmailCryptTypeMD5 + /// EmailCryptType.EmailCryptTypeSHA1 + /// EmailCryptType.EmailCryptTypeSHA256 + /// EmailCryptType.EmailCryptTypeNone + /// + /// Encryption method. + /// User emails. + public static void setUserEmails(EmailCryptType cryptType, params string[] userEmails) + { + + if (instance != null) + { + instance.setUserEmails(cryptType, userEmails); + } + + } + + public static void updateServerUninstallToken(string token) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.updateServerUninstallToken(token); + } + } + + /// + /// Set the user phone number. + /// + /// phoneNumber string + public static void setPhoneNumber(string phoneNumber) + { + + if (instance != null) + { + instance.setPhoneNumber(phoneNumber); + } + + } + + public static void setImeiData(string aImei) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setImeiData(aImei); + } + } + + /// + /// Used by advertisers to exclude all networks/integrated partners from getting data. + /// + [Obsolete("Please use setSharingFilterForPartners api")] + public static void setSharingFilterForAllPartners() + { + + if (instance != null) + { + instance.setSharingFilterForAllPartners(); + } + + + } + + public static void setAndroidIdData(string aAndroidId) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setAndroidIdData(aAndroidId); + } + } + + public static void waitForCustomerUserId(bool wait) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.waitForCustomerUserId(wait); + } + } + + /// + /// Used by advertisers to set some (one or more) networks/integrated partners to exclude from getting data. + /// + /// partners to exclude from getting data + [Obsolete("Please use setSharingFilterForPartners api")] + public static void setSharingFilter(params string[] partners) + { + + if (instance != null) + { + instance.setSharingFilter(partners); + } + + + } + + public static void setCustomerIdAndStartSDK(string id) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setCustomerIdAndStartSDK(id); + } + } + + /// + /// Lets you configure how which partners should the SDK exclude from data-sharing. + /// + /// partners to exclude from getting data + public static void setSharingFilterForPartners(params string[] partners) + { +#if UNITY_IOS || UNITY_STANDALONE_OSX + AppsFlyeriOS.setSharingFilterForPartners(partners); +#elif UNITY_ANDROID + AppsFlyerAndroid.setSharingFilterForPartners(partners); +#else + +#endif + } + + public static string getOutOfStore() + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + return appsFlyerAndroidInstance.getOutOfStore(); + } + return string.Empty; + } + + public static void setOutOfStore(string sourceName) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setOutOfStore(sourceName); + } + } + + /// + /// Register a Conversion Data Listener. + /// Allows the developer to access the user attribution data in real-time for every new install, directly from the SDK level. + /// By doing this you can serve users with personalized content or send them to specific activities within the app, + /// which can greatly enhance their engagement with your app. + /// + /// + /// + /// AppsFlyer.getConversionData(this.name); + /// + /// + public static void getConversionData(string objectName) + { +#if UNITY_WSA_10_0 && !UNITY_EDITOR + AppsFlyerWindows.GetConversionData(""); +#else + if (instance != null) + { + instance.getConversionData(objectName); + } +#endif + + } + + public static void setCollectAndroidID(bool isCollect) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setCollectAndroidID(isCollect); + } + } + + public static void setIsUpdate(bool isUpdate) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setIsUpdate(isUpdate); + } + } + + public static void setCollectIMEI(bool isCollect) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setCollectIMEI(isCollect); + } + } + + public static void setDisableCollectAppleAdSupport(bool disable) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setDisableCollectAppleAdSupport(disable); + } + } + + public static void setShouldCollectDeviceName(bool shouldCollectDeviceName) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setShouldCollectDeviceName(shouldCollectDeviceName); + } + } + + + /// + /// Use the following API to attribute the click and launch the app store's app page. + /// + /// promoted App ID + /// cross promotion campaign + /// additional user params + /// + /// + /// Dictionary parameters = new Dictionary(); + /// parameters.Add("af_sub1", "val"); + /// parameters.Add("custom_param", "val2"); + /// AppsFlyer.attributeAndOpenStore("123456789", "test campaign", parameters, this); + /// + /// + public static void attributeAndOpenStore(string appID, string campaign, Dictionary userParams, MonoBehaviour gameObject) + { + + if (instance != null) + { + instance.attributeAndOpenStore(appID, campaign, userParams, gameObject); + } + + } + + public static void setPreinstallAttribution(string mediaSource, string campaign, string siteId) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setPreinstallAttribution(mediaSource, campaign, siteId); + } + } + + public static void setDisableCollectIAd(bool disableCollectIAd) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setDisableCollectIAd(disableCollectIAd); + } + } + + public static bool isPreInstalledApp() + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + return appsFlyerAndroidInstance.isPreInstalledApp(); + } + return false; + } + + public static void setUseReceiptValidationSandbox(bool useReceiptValidationSandbox) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setUseReceiptValidationSandbox(useReceiptValidationSandbox); + } + } + + /// + /// To attribute an impression use the following API call. + /// Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard. + /// + /// promoted App ID. + /// cross promotion campaign. + /// parameters Dictionary. + public static void recordCrossPromoteImpression(string appID, string campaign, Dictionary parameters) + { + + if (instance != null) + { + instance.recordCrossPromoteImpression(appID, campaign, parameters); + } + + } + + public static void setUseUninstallSandbox(bool useUninstallSandbox) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setUseUninstallSandbox(useUninstallSandbox); + } + } + + public static string getAttributionId() + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + return appsFlyerAndroidInstance.getAttributionId(); + } + return string.Empty; + } + + public static void handlePushNotifications() + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.handlePushNotifications(); + } + } + + public static void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary additionalParameters, MonoBehaviour gameObject) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.validateAndSendInAppPurchase(productIdentifier, price, currency, transactionId, additionalParameters, gameObject); + } + } + + // V2 + public static void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary extraEventValues, MonoBehaviour gameObject) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.validateAndSendInAppPurchase(details, extraEventValues, gameObject); + } + } + + public static void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary additionalParameters, MonoBehaviour gameObject) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.validateAndSendInAppPurchase(publicKey, signature,purchaseData, price, currency, additionalParameters, gameObject); + } + } + + // V2 + public static void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary additionalParameters, MonoBehaviour gameObject) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.validateAndSendInAppPurchase(details, additionalParameters, gameObject); + } + } + + public static void handleOpenUrl(string url, string sourceApplication, string annotation) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.handleOpenUrl(url, sourceApplication, annotation); + } + } + + public static void registerUninstall(byte[] deviceToken) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.registerUninstall(deviceToken); + } + } + + public static void waitForATTUserAuthorizationWithTimeoutInterval(int timeoutInterval) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.waitForATTUserAuthorizationWithTimeoutInterval(timeoutInterval); + } + } + + public static void setCurrentDeviceLanguage(string language) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.setCurrentDeviceLanguage(language); + } + } + + /// + /// The LinkGenerator class builds the invite URL according to various setter methods which allow passing on additional information on the click. + /// See - https://support.appsflyer.com/hc/en-us/articles/115004480866-User-invite-attribution- + /// + /// parameters Dictionary. + public static void generateUserInviteLink(Dictionary parameters, MonoBehaviour gameObject) + { + + if (instance != null) + { + instance.generateUserInviteLink(parameters, gameObject); + } + + } + + public static void disableSKAdNetwork(bool isDisabled) + { + if (instance != null && instance is IAppsFlyerIOSBridge) + { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.disableSKAdNetwork(isDisabled); + } else { +#if UNITY_IOS || UNITY_STANDALONE_OSX + instance = new AppsFlyeriOS(); + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.disableSKAdNetwork(isDisabled); +#else +#endif + } + } + + public static void setCollectOaid(bool isCollect) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setCollectOaid(isCollect); + } + } + + + /// + /// Use this method if you’re integrating your app with push providers + /// that don’t use the default push notification JSON schema the SDK expects. + /// See docs for more info. + /// + /// array of nested json path + public static void addPushNotificationDeepLinkPath(params string[] paths) + { + + if (instance != null) + { + instance.addPushNotificationDeepLinkPath(paths); + } + + } + + public static void setDisableAdvertisingIdentifiers(bool disable) + { + if (instance != null && instance is IAppsFlyerAndroidBridge) + { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setDisableAdvertisingIdentifiers(disable); + } + } + + /// + /// Subscribe for unified deeplink API. + /// This is called automatically from OnDeepLinkReceived. + /// CallBackObjectName is set in the init method. + /// + public static void subscribeForDeepLink() + { + + if (instance != null) + { + instance.subscribeForDeepLink(CallBackObjectName); + } + + } + + /// + /// Allows sending custom data for partner integration purposes. + /// partnerId : id of the partner + /// partnerInfo: customer data + /// + public static void setPartnerData(string partnerId, Dictionary partnerInfo) + { + if (instance != null) + { + instance.setPartnerData(partnerId, partnerInfo); + } + + } + + /// + /// Use to opt-out of collecting the network operator name (carrier) and sim operator name from the device. + /// + public static void setDisableNetworkData(bool disable) { + if (instance != null && instance is IAppsFlyerAndroidBridge) { + IAppsFlyerAndroidBridge appsFlyerAndroidInstance = (IAppsFlyerAndroidBridge)instance; + appsFlyerAndroidInstance.setDisableNetworkData(disable); + } + } + + + /// + /// Use to disable app vendor identifier (IDFV) collection, 'true' to disable. + /// + public static void disableIDFVCollection(bool isDisabled) + { +#if UNITY_IOS || UNITY_STANDALONE_OSX + if (instance == null) { + instance = new AppsFlyeriOS(); + } + if (instance != null && instance is IAppsFlyerIOSBridge) { + IAppsFlyerIOSBridge appsFlyeriOSInstance = (IAppsFlyerIOSBridge)instance; + appsFlyeriOSInstance.disableIDFVCollection(isDisabled); + } +#else +#endif + } + + /// + /// Start callback event. + /// + public static event EventHandler OnRequestResponse + { + add + { + onRequestResponse += value; + } + remove + { + onRequestResponse -= value; + } + } + + /// + /// In-App callback event. + /// + public static event EventHandler OnInAppResponse + { + add + { + onInAppResponse += value; + } + remove + { + onInAppResponse -= value; + } + } + + /// + /// Unified DeepLink Event + /// + public static event EventHandler OnDeepLinkReceived + { + add + { + onDeepLinkReceived += value; + subscribeForDeepLink(); + } + remove + { + onDeepLinkReceived -= value; + } + } + + /// + /// Used to accept start callback from UnitySendMessage on native side. + /// + public void inAppResponseReceived(string response) + { + if (onInAppResponse != null) + { + onInAppResponse.Invoke(null, parseRequestCallback(response)); + } + } + + /// + /// Used to accept in-app callback from UnitySendMessage on native side. + /// + public void requestResponseReceived(string response) + { + if (onRequestResponse != null) + { + onRequestResponse.Invoke(null, parseRequestCallback(response)); + } + } + + /// + /// Used to accept deeplink callback from UnitySendMessage on native side. + /// + public void onDeepLinking(string response) + { + + DeepLinkEventsArgs args = new DeepLinkEventsArgs(response); + + if (onDeepLinkReceived != null) + { + onDeepLinkReceived.Invoke(null, args); + } + } + + private static AppsFlyerRequestEventArgs parseRequestCallback(string response) + { + int responseCode = 0; + string errorDescription = ""; + + try + { + Dictionary dictionary = CallbackStringToDictionary(response); + var errorResponse = dictionary.ContainsKey("errorDescription") ? dictionary["errorDescription"] : ""; + errorDescription = (string)errorResponse; + responseCode = (int)(long) dictionary["statusCode"]; + } + catch (Exception e) + { + AFLog("parseRequestCallback", String.Format("{0} Exception caught.", e)); + } + + return new AppsFlyerRequestEventArgs(responseCode, errorDescription); + } + + /// + /// Helper method to convert json strings to dictionary. + /// + /// json string + /// dictionary representing the input json string. + public static Dictionary CallbackStringToDictionary(string str) + { + return AFMiniJSON.Json.Deserialize(str) as Dictionary; + } + + /// + /// Helper method to log AppsFlyer events and callbacks. + /// + /// method name + /// message to log + public static void AFLog(string methodName, string str) + { + Debug.Log(string.Format("AppsFlyer_Unity_v{0} {1} called with {2}", kAppsFlyerPluginVersion, methodName, str)); + } + } + + public enum EmailCryptType + { + // None + EmailCryptTypeNone = 0, + // SHA256 + EmailCryptTypeSHA256 = 1, + } + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AppsFlyer.cs.meta b/Assets/AppsFlyer/AppsFlyer.cs.meta new file mode 100644 index 0000000..48d98d5 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45161025a517d427381d3d06153a5ad3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyerAndroid.cs b/Assets/AppsFlyer/AppsFlyerAndroid.cs new file mode 100644 index 0000000..0e085f6 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerAndroid.cs @@ -0,0 +1,779 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace AppsFlyerSDK +{ + +#if UNITY_ANDROID + public class AppsFlyerAndroid : IAppsFlyerAndroidBridge + { + public bool isInit { get; set; } + + private static AndroidJavaClass appsFlyerAndroid = new AndroidJavaClass("com.appsflyer.unity.AppsFlyerAndroidWrapper"); + + public AppsFlyerAndroid() { } + + /// + /// Use this method to init the sdk for the application. + /// Call this method before startSDK. + /// + /// AppsFlyer's Dev-Key, which is accessible from your AppsFlyer account under 'App Settings' in the dashboard. + /// The current game object. This is used to get the conversion data callbacks. Pass null if you do not need the callbacks. + public void initSDK(string devkey, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("initSDK", devkey, gameObject ? gameObject.name : null); +#endif + } + + /// + /// Use this method to start the sdk for the application. + /// The AppsFlyer's Dev-Key must be provided. + /// + /// AppsFlyer's Dev-Key, which is accessible from your AppsFlyer account under 'App Settings' in the dashboard. + public void startSDK(bool onRequestResponse, string CallBackObjectName) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("startTracking", onRequestResponse, CallBackObjectName); +#endif + } + + /// + /// Once this API is invoked, our SDK no longer communicates with our servers and stops functioning. + /// In some extreme cases you might want to shut down all SDK activity due to legal and privacy compliance. + /// This can be achieved with the stopSDK API. + /// + /// boolean should SDK be stopped. + public void stopSDK(bool isSDKStopped) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("stopTracking", isSDKStopped); +#endif + } + + /// + /// Get the AppsFlyer SDK version used in app. + /// + /// AppsFlyer SDK version. + public string getSdkVersion() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getSdkVersion"); +#else + return ""; +#endif + } + + /// + /// Manually pass the Firebase / GCM Device Token for Uninstall measurement. + /// + /// Firebase Device Token. + public void updateServerUninstallToken(string token) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("updateServerUninstallToken", token); +#endif + } + + /// + /// Enables Debug logs for the AppsFlyer SDK. + /// Should only be set to true in development / debug. + /// + /// shouldEnable boolean. + public void setIsDebug(bool shouldEnable) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setIsDebug", shouldEnable); +#endif + } + + /// + /// By default, IMEI and Android ID are not collected by the SDK if the OS version is higher than KitKat (4.4) + /// and the device contains Google Play Services(on SDK versions 4.8.8 and below the specific app needed GPS). + /// Use this API to explicitly send IMEI to AppsFlyer. + /// + /// device's IMEI. + public void setImeiData(string aImei) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setImeiData", aImei); +#endif + } + + /// + /// By default, IMEI and Android ID are not collected by the SDK if the OS version is higher than KitKat(4.4) + /// and the device contains Google Play Services(on SDK versions 4.8.8 and below the specific app needed GPS). + /// Use this API to explicitly send Android ID to AppsFlyer. + /// + /// device's Android ID. + public void setAndroidIdData(string aAndroidId) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setAndroidIdData", aAndroidId); +#endif + } + + /// + /// Setting your own customer ID enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs. + /// This ID is available in AppsFlyer CSV reports along with Postback APIs for cross-referencing with your internal IDs. + /// + /// Customer ID for client. + public void setCustomerUserId(string id) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCustomerUserId", id); +#endif + } + + /// + /// It is possible to delay the SDK Initialization until the customerUserID is set. + /// This feature makes sure that the SDK doesn't begin functioning until the customerUserID is provided. + /// If this API is used, all in-app events and any other SDK API calls are discarded, until the customerUserID is provided. + /// + /// wait boolean. + public void waitForCustomerUserId(bool wait) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("waitForCustomerUserId", wait); +#endif + } + + /// + /// Use this API to provide the SDK with the relevant customer user id and trigger the SDK to begin its normal activity. + /// + /// Customer ID for client. + public void setCustomerIdAndStartSDK(string id) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCustomerIdAndTrack", id); +#endif + } + + /// + /// Get the current AF_STORE value. + /// + /// AF_Store value. + public string getOutOfStore() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getOutOfStore"); +#else + return ""; +#endif + } + + /// + /// Manually set the AF_STORE value. + /// + /// value to be set. + public void setOutOfStore(string sourceName) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setOutOfStore", sourceName); +#endif + } + + /// + /// Set the OneLink ID that should be used for User-Invites. + /// The link that is generated for the user invite will use this OneLink as the base link. + /// + /// OneLink ID obtained from the AppsFlyer Dashboard. + public void setAppInviteOneLinkID(string oneLinkId) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setAppInviteOneLinkID", oneLinkId); +#endif + } + + /// + /// Set additional data to be sent to AppsFlyer. + /// + /// additional data Dictionary. + public void setAdditionalData(Dictionary customData) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setAdditionalData", convertDictionaryToJavaMap(customData)); +#endif + } + + //// + /// Set the deepLink timeout value that should be used for DDL. + /// + /// deepLink timeout in milliseconds. + public void setDeepLinkTimeout(long deepLinkTimeout) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setDeepLinkTimeout", deepLinkTimeout); +#endif + } + + /// + /// Set the user emails. + /// + /// User emails. + public void setUserEmails(params string[] userEmails) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setUserEmails", (object)userEmails); +#endif + } + + + /// + /// Set the user phone number. + /// + /// User phoneNumber. + public void setPhoneNumber(string phoneNumber){ +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setPhoneNumber", phoneNumber); +#endif + } + + /// + /// Set the user emails and encrypt them. + /// cryptMethod Encryption method: + /// EmailCryptType.EmailCryptTypeMD5 + /// EmailCryptType.EmailCryptTypeSHA1 + /// EmailCryptType.EmailCryptTypeSHA256 + /// EmailCryptType.EmailCryptTypeNone + /// + /// Encryption method. + /// User emails. + public void setUserEmails(EmailCryptType cryptMethod, params string[] emails) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setUserEmails", getEmailType(cryptMethod), (object)emails); +#endif + } + + /// + /// Opt-out of collection of Android ID. + /// If the app does NOT contain Google Play Services, Android ID is collected by the SDK. + /// However, apps with Google play services should avoid Android ID collection as this is in violation of the Google Play policy. + /// + /// boolean, false to opt-out. + public void setCollectAndroidID(bool isCollect) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCollectAndroidID", isCollect); +#endif + } + + /// + /// Opt-out of collection of IMEI. + /// If the app does NOT contain Google Play Services, device IMEI is collected by the SDK. + /// However, apps with Google play services should avoid IMEI collection as this is in violation of the Google Play policy. + /// + /// boolean, false to opt-out. + public void setCollectIMEI(bool isCollect) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCollectIMEI", isCollect); +#endif + } + + /// + /// Advertisers can wrap AppsFlyer OneLink within another Universal Link. + /// This Universal Link will invoke the app but any deep linking data will not propagate to AppsFlyer. + /// + /// Array of urls. + public void setResolveDeepLinkURLs(params string[] urls) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setResolveDeepLinkURLs", (object)urls); +#endif + } + + + /// + /// Advertisers can use this method to set vanity onelink domains. + /// + /// Array of domains. + public void setOneLinkCustomDomain(params string[] domains) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setOneLinkCustomDomain", (object)domains); +#endif + } + + /// + /// Manually set that the application was updated. + /// + /// isUpdate boolean value. + public void setIsUpdate(bool isUpdate) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setIsUpdate", isUpdate); +#endif + } + + /// + /// Setting user local currency code for in-app purchases. + /// The currency code should be a 3 character ISO 4217 code. (default is USD). + /// You can set the currency code for all events by calling the following method. + /// + /// 3 character ISO 4217 code. + public void setCurrencyCode(string currencyCode) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCurrencyCode", currencyCode); +#endif + } + + /// + /// Manually record the location of the user. + /// + /// latitude as double. + /// longitude as double. + public void recordLocation(double latitude, double longitude) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("trackLocation", latitude, longitude); +#endif + } + + /// + /// Send an In-App Event. + /// In-App Events provide insight on what is happening in your app. + /// + /// Event Name as String. + /// Event Values as Dictionary. + public void sendEvent(string eventName, Dictionary eventValues) + { + sendEvent(eventName, eventValues, false, AppsFlyer.CallBackObjectName); + } + + public void sendEvent(string eventName, Dictionary eventValues, bool shouldCallback, string callBackObjectName) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("trackEvent", eventName, convertDictionaryToJavaMap(eventValues), shouldCallback, callBackObjectName); +#endif + } + + /// + /// Anonymize user Data. + /// Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions. + /// Default is false. + /// + /// isDisabled boolean. + public void anonymizeUser(bool isDisabled) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setDeviceTrackingDisabled", isDisabled); +#endif + } + + /// + /// Calling enableTCFDataCollection(true) will enable collecting and sending any TCF related data. + /// Calling enableTCFDataCollection(false) will disable the collection of TCF related data and from sending it. + /// + /// should start TCF Data collection boolean. + public void enableTCFDataCollection(bool shouldCollectTcfData) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("enableTCFDataCollection", shouldCollectTcfData); +#endif + } + + /// + /// Enable the collection of Facebook Deferred AppLinks. + /// Requires Facebook SDK and Facebook app on target/client device. + /// This API must be invoked prior to initializing the AppsFlyer SDK in order to function properly. + /// + /// should Facebook's deferred app links be processed by the AppsFlyer SDK. + public void enableFacebookDeferredApplinks(bool isEnabled) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("enableFacebookDeferredApplinks", isEnabled); +#endif + } + + /// + /// Sets or updates the user consent data related to GDPR and DMA regulations for advertising and data usage purposes within the application. + /// call this method when GDPR user is true + /// + /// hasConsentForDataUsage boolean. + /// hasConsentForAdsPersonalization boolean. + public void setConsentData(AppsFlyerConsent appsFlyerConsent) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setConsentData", appsFlyerConsent.isUserSubjectToGDPR, appsFlyerConsent.hasConsentForDataUsage, appsFlyerConsent.hasConsentForAdsPersonalization); +#endif + } + + /// + /// Restrict reengagement via deep-link to once per each unique deep-link. + /// Otherwise deep re-occurring deep-links will be permitted for non-singleTask Activities and deep-linking via AppsFlyer deep-links. + /// The default value is false. + /// + /// doConsume boolean. + public void setConsumeAFDeepLinks(bool doConsume) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setConsumeAFDeepLinks", doConsume); +#endif + } + + /// + /// Specify the manufacturer or media source name to which the preinstall is attributed. + /// + /// Manufacturer or media source name for preinstall attribution. + /// Campaign name for preinstall attribution. + /// Site ID for preinstall attribution. + public void setPreinstallAttribution(string mediaSource, string campaign, string siteId) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setPreinstallAttribution", mediaSource, campaign, siteId); +#endif + } + + /// + /// Boolean indicator for preinstall by Manufacturer. + /// + /// boolean isPreInstalledApp. + public bool isPreInstalledApp() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("isPreInstalledApp"); +#else + return false; +#endif + } + + /// + /// Get the Facebook attribution ID, if one exists. + /// + /// string Facebook attribution ID. + public string getAttributionId() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getAttributionId"); +#else + return ""; +#endif + } + + /// + /// Get AppsFlyer's unique device ID is created for every new install of an app. + /// + /// AppsFlyer's unique device ID. + public string getAppsFlyerId() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getAppsFlyerId"); +#else + return ""; +#endif + } + + /// + /// API for server verification of in-app purchases. + /// An af_purchase event with the relevant values will be automatically sent if the validation is successful. + /// + /// License Key obtained from the Google Play Console. + /// data.INAPP_DATA_SIGNATURE from onActivityResult(int requestCode, int resultCode, Intent data) + /// data.INAPP_PURCHASE_DATA from onActivityResult(int requestCode, int resultCode, Intent data) + /// Purchase price, should be derived from skuDetails.getStringArrayList("DETAILS_LIST") + /// Purchase currency, should be derived from skuDetails.getStringArrayList("DETAILS_LIST") + /// additionalParameters Freehand parameters to be sent with the purchase (if validated). + public void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary additionalParameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("validateAndTrackInAppPurchase", publicKey, signature, purchaseData, price, currency, convertDictionaryToJavaMap(additionalParameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// API for server verification of in-app purchases. + /// An af_purchase event with the relevant values will be automatically sent if the validation is successful. + /// + /// AFPurchaseDetailsAndroid instance. + /// additionalParameters Freehand parameters to be sent with the purchase (if validated). + public void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary additionalParameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("validateAndTrackInAppPurchaseV2", (int)details.purchaseType, details.purchaseToken, details.productId, details.price, details.currency, convertDictionaryToJavaMap(additionalParameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// Was the stopSDK(boolean) API set to true. + /// + /// boolean isSDKStopped. + public bool isSDKStopped() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("isTrackingStopped"); +#else + return false; +#endif + } + + /// + /// Set a custom value for the minimum required time between sessions. + /// By default, at least 5 seconds must lapse between 2 app launches to count as separate 2 sessions. + /// + /// minimum time between 2 separate sessions in seconds. + public void setMinTimeBetweenSessions(int seconds) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setMinTimeBetweenSessions", seconds); +#endif + } + + /// + /// Set a custom host. + /// + /// Host prefix. + /// Host name. + public void setHost(string hostPrefixName, string hostName) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setHost", hostPrefixName, hostName); +#endif + } + + /// + /// Get the host name. + /// Default value is "appsflyer.com". + /// + /// Host name. + public string getHostName() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getHostName"); +#else + return ""; +#endif + } + + /// + /// Get the custom host prefix. + /// + /// Host prefix. + public string getHostPrefix() + { +#if !UNITY_EDITOR + return appsFlyerAndroid.CallStatic("getHostPrefix"); +#else + return ""; +#endif + } + + /// + /// Used by advertisers to exclude all networks/integrated partners from getting data. + /// + public void setSharingFilterForAllPartners() + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setSharingFilterForAllPartners"); +#endif + } + + /// + /// Used by advertisers to set some (one or more) networks/integrated partners to exclude from getting data. + /// + /// partners to exclude from getting data + public void setSharingFilter(params string[] partners) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setSharingFilter", (object)partners); +#endif + } + + /// + /// Lets you configure how which partners should the SDK exclude from data-sharing. + /// + /// partners to exclude from getting data + public static void setSharingFilterForPartners(params string[] partners) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setSharingFilterForPartners", (object)partners); +#endif + } + + /// + /// Register a Conversion Data Listener. + /// Allows the developer to access the user attribution data in real-time for every new install, directly from the SDK level. + /// By doing this you can serve users with personalized content or send them to specific activities within the app, + /// which can greatly enhance their engagement with your app. + /// + public void getConversionData(string objectName) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("getConversionData", objectName); +#endif + } + + /// + /// Register a validation listener for the validateAndSendInAppPurchase API. + /// + public void initInAppPurchaseValidatorListener(MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("initInAppPurchaseValidatorListener", gameObject ? gameObject.name : null); +#endif + } + + /// + /// setCollectOaid + /// You must include the appsflyer oaid library for this api to work. + /// + /// isCollect oaid - set fasle to opt out + public void setCollectOaid(bool isCollect) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setCollectOaid", isCollect); +#endif + } + + /// + /// Use the following API to attribute the click and launch the app store's app page. + /// + /// promoted App ID + /// cross promotion campaign + /// additional user params + public void attributeAndOpenStore(string promoted_app_id, string campaign, Dictionary userParams, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("attributeAndOpenStore", promoted_app_id, campaign, convertDictionaryToJavaMap(userParams)); +#endif + } + + /// + /// To attribute an impression use the following API call. + /// Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard. + /// + /// promoted App ID. + /// cross promotion campaign. + /// parameters Dictionary. + public void recordCrossPromoteImpression(string appID, string campaign, Dictionary parameters) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("recordCrossPromoteImpression", appID, campaign, convertDictionaryToJavaMap(parameters)); +#endif + } + + /// + /// The LinkGenerator class builds the invite URL according to various setter methods which allow passing on additional information on the click. + /// See - https://support.appsflyer.com/hc/en-us/articles/115004480866-User-invite-attribution- + /// + /// parameters Dictionary. + public void generateUserInviteLink(Dictionary parameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("createOneLinkInviteListener", convertDictionaryToJavaMap(parameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// To measure push notifications as part of a retargeting campaign. + /// + public void handlePushNotifications(){ +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("handlePushNotifications"); +#endif + } + + /// + /// Use this method if you’re integrating your app with push providers + /// that don’t use the default push notification JSON schema the SDK expects. + /// See docs for more info. + /// + /// array of nested json path + public void addPushNotificationDeepLinkPath(params string[] paths) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("addPushNotificationDeepLinkPath", (object)paths); +#endif + } + + /// + /// subscribe to unified deep link callbacks + /// + public void subscribeForDeepLink(string objectName){ +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("subscribeForDeepLink", objectName); +#endif + } + + /// + /// Disables collection of various Advertising IDs by the SDK. This includes Google Advertising ID (GAID), OAID and Amazon Advertising ID (AAID) + /// + /// disable boolean. + public void setDisableAdvertisingIdentifiers(bool disable) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setDisableAdvertisingIdentifiers", disable); +#endif + } + + /// + /// Allows sending custom data for partner integration purposes. + /// + public void setPartnerData(string partnerId, Dictionary partnerInfo) + { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setPartnerData", partnerId, convertDictionaryToJavaMap(partnerInfo)); +#endif + } + + /// + /// Use to opt-out of collecting the network operator name (carrier) and sim operator name from the device. + /// + public void setDisableNetworkData(bool disable) { +#if !UNITY_EDITOR + appsFlyerAndroid.CallStatic("setDisableNetworkData", disable); +#endif + } + + /// + /// Internal Helper Method. + /// + private static AndroidJavaObject getEmailType(EmailCryptType cryptType) + { + AndroidJavaClass emailsCryptTypeEnum = new AndroidJavaClass("com.appsflyer.AppsFlyerProperties$EmailsCryptType"); + AndroidJavaObject emailsCryptType; + + switch (cryptType) + { + case EmailCryptType.EmailCryptTypeSHA256: + emailsCryptType = emailsCryptTypeEnum.GetStatic("SHA256"); + break; + default: + emailsCryptType = emailsCryptTypeEnum.GetStatic("NONE"); + break; + } + + return emailsCryptType; + } + + /// + /// Internal Helper Method. + /// + private static AndroidJavaObject convertDictionaryToJavaMap(Dictionary dictionary) + { + AndroidJavaObject map = new AndroidJavaObject("java.util.HashMap"); + IntPtr putMethod = AndroidJNIHelper.GetMethodID(map.GetRawClass(), "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + jvalue[] val; + if (dictionary != null) + { + foreach (var entry in dictionary) + { + val = AndroidJNIHelper.CreateJNIArgArray(new object[] { entry.Key, entry.Value }); + AndroidJNI.CallObjectMethod(map.GetRawObject(), putMethod,val); + AndroidJNI.DeleteLocalRef(val[0].l); + AndroidJNI.DeleteLocalRef(val[1].l); + } + } + + return map; + } + } + +#endif + + + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AppsFlyerAndroid.cs.meta b/Assets/AppsFlyer/AppsFlyerAndroid.cs.meta new file mode 100644 index 0000000..d7ce722 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerAndroid.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 172d18dd98e7e4ed3b30110568b0fae4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyerConsent.cs b/Assets/AppsFlyer/AppsFlyerConsent.cs new file mode 100644 index 0000000..341e530 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerConsent.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; + +namespace AppsFlyerSDK +{ + /// + // Data class representing a user's consent for data processing in accordance with GDPR and DMA + // (Digital Markets Act) compliance, specifically regarding advertising preferences. + + // This class should be used to notify and record the user's applicability + // under GDPR, their general consent to data usage, and their consent to personalized + // advertisements based on user data. + + // Note that the consent for data usage and ads personalization pair is only applicable when the user is + // subject to GDPR guidelines. Therefore, the following factory methods should be used accordingly: + // - Use [forGDPRUser] when the user is subject to GDPR. + // - Use [forNonGDPRUser] when the user is not subject to GDPR. + + // @property isUserSubjectToGDPR Indicates whether GDPR regulations apply to the user (true if the user is + // a subject of GDPR). It also serves as a flag for compliance with relevant aspects of DMA regulations. + // @property hasConsentForDataUsage Indicates whether the user has consented to the use of their data for advertising + // purposes under both GDPR and DMA guidelines (true if the user has consented, nullable if not subject to GDPR). + // @property hasConsentForAdsPersonalization Indicates whether the user has consented to the use of their data for + // personalized advertising within the boundaries of GDPR and DMA rules (true if the user has consented to + // personalized ads, nullable if not subject to GDPR). + /// + public class AppsFlyerConsent + { + public bool isUserSubjectToGDPR { get; private set; } + public bool hasConsentForDataUsage { get; private set; } + public bool hasConsentForAdsPersonalization { get; private set; } + + private AppsFlyerConsent(bool isGDPR, bool hasForDataUsage, bool hasForAdsPersonalization) + { + isUserSubjectToGDPR = isGDPR; + hasConsentForDataUsage = hasForDataUsage; + hasConsentForAdsPersonalization = hasForAdsPersonalization; + } + + public static AppsFlyerConsent ForGDPRUser(bool hasConsentForDataUsage, bool hasConsentForAdsPersonalization) + { + return new AppsFlyerConsent(true, hasConsentForDataUsage, hasConsentForAdsPersonalization); + } + + public static AppsFlyerConsent ForNonGDPRUser() + { + return new AppsFlyerConsent(false, false, false); + } + } + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AppsFlyerConsent.cs.meta b/Assets/AppsFlyer/AppsFlyerConsent.cs.meta new file mode 100644 index 0000000..5a881de --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerConsent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a97c986fe4ee0461badf7042e08db3f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyerEventArgs.cs b/Assets/AppsFlyer/AppsFlyerEventArgs.cs new file mode 100644 index 0000000..511db67 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerEventArgs.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; + +namespace AppsFlyerSDK +{ + + /// + /// Event args for AppsFlyer requests. + /// Used for sessions and in-app events. + /// Used to handle post request logic. + /// + /// Examples: + /// statusCode / errorDescription + /// + /// 200 - null + /// + /// 10 - "Event timeout. Check 'minTimeBetweenSessions' param" + /// 11 - "Skipping event because 'isStopTracking' enabled" + /// 40 - Network error: Error description comes from Android + /// 41 - "No dev key" + /// 50 - "Status code failure" + actual response code from the server + /// + /// + public class AppsFlyerRequestEventArgs : EventArgs + { + public AppsFlyerRequestEventArgs(int code, string description) + { + statusCode = code; + errorDescription = description; + } + + public int statusCode { get; } + public string errorDescription { get; } + } + + /// + /// Event args for OnDeepLinkReceived. + /// Used to handle deep linking results. + /// + public class DeepLinkEventsArgs : EventArgs + { + + /// + /// DeepLink dictionary to get additional parameters + /// + public Dictionary deepLink; + + /// + /// DeepLink status: FOUND, NOT_FOUND, ERROR + /// + public DeepLinkStatus status { get; } + + /// + /// DeepLink error: TIMEOUT, NETWORK, HTTP_STATUS_CODE, UNEXPECTED + /// + public DeepLinkError error { get; } + + public string getMatchType() + { + return getDeepLinkParameter("match_type"); + } + + public string getDeepLinkValue() + { + return getDeepLinkParameter("deep_link_value"); + } + + public string getClickHttpReferrer() + { + return getDeepLinkParameter("click_http_referrer"); + } + + public string getMediaSource() + { + return getDeepLinkParameter("media_source"); + } + + public string getCampaign() + { + return getDeepLinkParameter("campaign"); + } + + public string getCampaignId() + { + return getDeepLinkParameter("campaign_id"); + } + + public string getAfSub1() + { + return getDeepLinkParameter("af_sub1"); + } + + public string getAfSub2() + { + return getDeepLinkParameter("af_sub2"); + } + + public string getAfSub3() + { + return getDeepLinkParameter("af_sub3"); + } + + public string getAfSub4() + { + return getDeepLinkParameter("af_sub4"); + } + + public string getAfSub5() + { + return getDeepLinkParameter("af_sub5"); + } + + public bool isDeferred() + { + if (deepLink != null && deepLink.ContainsKey("is_deferred")) + { + try + { + return (bool)deepLink["is_deferred"]; + } + catch (Exception e) + { + AppsFlyer.AFLog("DeepLinkEventsArgs.isDeferred", String.Format("{0} Exception caught.", e)); + } + } + return false; + } + + public Dictionary getDeepLinkDictionary() + { + return deepLink; + } + + public DeepLinkEventsArgs(string str) + { + try + { + Dictionary dictionary = AppsFlyer.CallbackStringToDictionary(str); + + string status = ""; + string error = ""; + + + if (dictionary.ContainsKey("status") && dictionary["status"] != null) + { + status = dictionary["status"].ToString(); + } + + if (dictionary.ContainsKey("error") && dictionary["error"] != null) + { + error = dictionary["error"].ToString(); + } + + if (dictionary.ContainsKey("deepLink") && dictionary["deepLink"] != null) + { + this.deepLink = AppsFlyer.CallbackStringToDictionary(dictionary["deepLink"].ToString()); + } + if (dictionary.ContainsKey("is_deferred")) + { + this.deepLink["is_deferred"] = dictionary["is_deferred"]; + } + + switch (status) + { + case "FOUND": + this.status = DeepLinkStatus.FOUND; + break; + case "NOT_FOUND": + this.status = DeepLinkStatus.NOT_FOUND; + break; + default: + this.status = DeepLinkStatus.ERROR; + break; + } + + switch (error) + { + case "TIMEOUT": + this.error = DeepLinkError.TIMEOUT; + break; + case "NETWORK": + this.error = DeepLinkError.NETWORK; + break; + case "HTTP_STATUS_CODE": + this.error = DeepLinkError.HTTP_STATUS_CODE; + break; + default: + this.error = DeepLinkError.UNEXPECTED; + break; + } + + } + catch (Exception e) + { + AppsFlyer.AFLog("DeepLinkEventsArgs.parseDeepLink", String.Format("{0} Exception caught.", e)); + } + } + + private string getDeepLinkParameter(string name) + { + if (deepLink != null && deepLink.ContainsKey(name) && deepLink[name] != null) + { + return deepLink[name].ToString(); + } + + return null; + } + + } + + public enum DeepLinkStatus { + FOUND, NOT_FOUND, ERROR + } + + public enum DeepLinkError { + TIMEOUT, NETWORK, HTTP_STATUS_CODE, UNEXPECTED + } +} diff --git a/Assets/AppsFlyer/AppsFlyerEventArgs.cs.meta b/Assets/AppsFlyer/AppsFlyerEventArgs.cs.meta new file mode 100644 index 0000000..056bce2 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0fc241ad5a9b43a7b461a6147dbc74c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyerObject.prefab b/Assets/AppsFlyer/AppsFlyerObject.prefab new file mode 100644 index 0000000..f3bbb45 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerObject.prefab @@ -0,0 +1,49 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &7315102894599890749 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 6207133488976360133} + - component: {fileID: 4405976200006927252} + m_Layer: 0 + m_Name: AppsFlyerObject + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &6207133488976360133 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7315102894599890749} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &4405976200006927252 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7315102894599890749} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2a2ec6ba1ee8b48749524f015ed572a6, type: 3} + m_Name: + m_EditorClassIdentifier: + devKey: + appID: + isDebug: 0 + getConversionData: 0 diff --git a/Assets/AppsFlyer/AppsFlyerObject.prefab.meta b/Assets/AppsFlyer/AppsFlyerObject.prefab.meta new file mode 100644 index 0000000..1acd1cf --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerObject.prefab.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0bfe3b149145747cc92dc53bb4df4e9b +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyerObjectScript.cs b/Assets/AppsFlyer/AppsFlyerObjectScript.cs new file mode 100644 index 0000000..266a848 --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerObjectScript.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using AppsFlyerSDK; + +// This class is intended to be used the the AppsFlyerObject.prefab + +public class AppsFlyerObjectScript : MonoBehaviour , IAppsFlyerConversionData +{ + + // These fields are set from the editor so do not modify! + //******************************// + public string devKey; + public string appID; + public string UWPAppID; + public string macOSAppID; + public bool isDebug; + public bool getConversionData; + //******************************// + + + void Start() + { + // These fields are set from the editor so do not modify! + //******************************// + AppsFlyer.setIsDebug(isDebug); +#if UNITY_WSA_10_0 && !UNITY_EDITOR + AppsFlyer.initSDK(devKey, UWPAppID, getConversionData ? this : null); +#elif UNITY_STANDALONE_OSX && !UNITY_EDITOR + AppsFlyer.initSDK(devKey, macOSAppID, getConversionData ? this : null); +#else + AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); +#endif + //******************************/ + + AppsFlyer.startSDK(); + } + + + void Update() + { + + } + + // Mark AppsFlyer CallBacks + public void onConversionDataSuccess(string conversionData) + { + AppsFlyer.AFLog("didReceiveConversionData", conversionData); + Dictionary conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData); + // add deferred deeplink logic here + } + + public void onConversionDataFail(string error) + { + AppsFlyer.AFLog("didReceiveConversionDataWithError", error); + } + + public void onAppOpenAttribution(string attributionData) + { + AppsFlyer.AFLog("onAppOpenAttribution", attributionData); + Dictionary attributionDataDictionary = AppsFlyer.CallbackStringToDictionary(attributionData); + // add direct deeplink logic here + } + + public void onAppOpenAttributionFailure(string error) + { + AppsFlyer.AFLog("onAppOpenAttributionFailure", error); + } + +} diff --git a/Assets/AppsFlyer/AppsFlyerObjectScript.cs.meta b/Assets/AppsFlyer/AppsFlyerObjectScript.cs.meta new file mode 100644 index 0000000..65ccedc --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyerObjectScript.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a2ec6ba1ee8b48749524f015ed572a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/AppsFlyeriOS.cs b/Assets/AppsFlyer/AppsFlyeriOS.cs new file mode 100644 index 0000000..e117a8e --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyeriOS.cs @@ -0,0 +1,997 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using UnityEngine; +using System.Reflection; + + + +namespace AppsFlyerSDK +{ + +#if UNITY_IOS || UNITY_STANDALONE_OSX + + public class AppsFlyeriOS: IAppsFlyerIOSBridge + { + public bool isInit { get; set; } + + public AppsFlyeriOS() { } + + public AppsFlyeriOS(string devKey, string appID, MonoBehaviour gameObject) + { + setAppsFlyerDevKey(devKey); + setAppleAppID(appID); + if (gameObject != null) + { +#if UNITY_IOS + getConversionData(gameObject.name); +#elif UNITY_STANDALONE_OSX + getConversionData(gameObject.GetType().ToString()); +#endif + } + } + + + + /// + /// Start Session. + /// This will record a session and then record all background forground sessions during the lifecycle of the app. + /// +public void startSDK(bool shouldCallback, string CallBackObjectName) + { +#if UNITY_STANDALONE_OSX && !UNITY_EDITOR + _startSDK(shouldCallback, CallBackObjectName, getCallback); +#elif UNITY_IOS && !UNITY_EDITOR + _startSDK(shouldCallback, CallBackObjectName); +#endif + } + + /// + /// Send an In-App Event. + /// In-App Events provide insight on what is happening in your app. + /// + /// Name of event. + /// Contains dictionary of values for handling by backend. + public void sendEvent(string eventName, Dictionary eventValues) + { + sendEvent(eventName, eventValues, false, AppsFlyer.CallBackObjectName); + } + + public void sendEvent(string eventName, Dictionary eventValues, bool shouldCallback, string callBackObjectName) + { +#if !UNITY_EDITOR + _afSendEvent(eventName, AFMiniJSON.Json.Serialize(eventValues), shouldCallback, callBackObjectName); +#endif + } + + /// + /// Get the conversion data. + /// Allows the developer to access the user attribution data in real-time for every new install, directly from the SDK level. + /// By doing this you can serve users with personalized content or send them to specific activities within the app, + /// which can greatly enhance their engagement with your app. + /// + public void getConversionData(string objectName) + { +#if !UNITY_EDITOR + _getConversionData(objectName); +#endif + } + + /// + /// In case you use your own user ID in your app, you can set this property to that ID. + /// Enables you to cross-reference your own unique ID with AppsFlyer’s unique ID and the other devices’ IDs. + /// + /// Customer ID for client. + public void setCustomerUserId(string customerUserID) + { +#if !UNITY_EDITOR + _setCustomerUserID(customerUserID); +#endif + } + + /// + /// In case you use custom data and you want to receive it in the raw reports. + /// see [Setting additional custom data] (https://support.appsflyer.com/hc/en-us/articles/207032066-AppsFlyer-SDK-Integration-iOS#setting-additional-custom-data) for more information. + /// + /// additional data Dictionary. + public void setAdditionalData(Dictionary customData) + { +#if !UNITY_EDITOR + _setAdditionalData(AFMiniJSON.Json.Serialize(customData)); +#endif + } + + /// + /// Use this method to set your AppsFlyer's dev key. + /// + /// AppsFlyer's Dev-Key, which is accessible from your AppsFlyer account under 'App Settings' in the dashboard. + public void setAppsFlyerDevKey(string appsFlyerDevKey) + { +#if !UNITY_EDITOR + _setAppsFlyerDevKey(appsFlyerDevKey); +#endif + } + + /// + /// Use this method to set your app's Apple ID(taken from the app's page on iTunes Connect). + /// + /// your app's Apple ID. + public void setAppleAppID(string appleAppID) + { +#if !UNITY_EDITOR + _setAppleAppID(appleAppID); +#endif + } + + /// + /// Setting user local currency code for in-app purchases. + /// The currency code should be a 3 character ISO 4217 code. (default is USD). + /// You can set the currency code for all events by calling the following method. + /// + /// 3 character ISO 4217 code. + public void setCurrencyCode(string currencyCode) + { +#if !UNITY_EDITOR + _setCurrencyCode(currencyCode); +#endif + } + + /// + /// AppsFlyer SDK collect Apple's `advertisingIdentifier` if the `AdSupport.framework` included in the SDK. + /// You can disable this behavior by setting the following property to true. + /// + /// boolean to disableCollectAppleAdSupport + public void setDisableCollectAppleAdSupport(bool disableCollectAppleAdSupport) + { +#if !UNITY_EDITOR + _setDisableCollectAppleAdSupport(disableCollectAppleAdSupport); +#endif + } + + /// + /// Enables Debug logs for the AppsFlyer SDK. + /// Should only be set to true in development / debug. + /// The default value is false. + /// + /// shouldEnable boolean.. + public void setIsDebug(bool isDebug) + { +#if !UNITY_EDITOR + _setIsDebug(isDebug); +#endif + } + + /// + /// Set this flag to true, to collect the current device name(e.g. "My iPhone"). Default value is false. + /// + /// boolean shouldCollectDeviceName. + [System.Obsolete("This is deprecated")] + public void setShouldCollectDeviceName(bool shouldCollectDeviceName) + { +#if !UNITY_EDITOR + _setShouldCollectDeviceName(shouldCollectDeviceName); +#endif + } + + /// + /// Set the OneLink ID that should be used for User-Invites. + /// The link that is generated for the user invite will use this OneLink as the base link. + /// + /// OneLink ID obtained from the AppsFlyer Dashboard. + public void setAppInviteOneLinkID(string appInviteOneLinkID) + { +#if !UNITY_EDITOR + _setAppInviteOneLinkID(appInviteOneLinkID); +#endif + } + + /// + /// Set the deepLink timeout value that should be used for DDL. + /// + /// deepLink timeout in milliseconds. + public void setDeepLinkTimeout(long deepLinkTimeout) + { +#if !UNITY_EDITOR + _setDeepLinkTimeout(deepLinkTimeout); +#endif + } + + /// + /// Calling enableTCFDataCollection(true) will enable collecting and sending any TCF related data. + /// Calling enableTCFDataCollection(false) will disable the collection of TCF related data and from sending it. + /// + /// should start TCF Data collection boolean. + public void enableTCFDataCollection(bool shouldCollectTcfData) + { +#if !UNITY_EDITOR + _enableTCFDataCollection(shouldCollectTcfData); +#endif + } + + /// + /// Sets or updates the user consent data related to GDPR and DMA regulations for advertising and data usage purposes within the application. + /// + /// instance of AppsFlyerConsent. + public void setConsentData(AppsFlyerConsent appsFlyerConsent) + { +#if !UNITY_EDITOR + _setConsentData(appsFlyerConsent.isUserSubjectToGDPR, appsFlyerConsent.hasConsentForDataUsage, appsFlyerConsent.hasConsentForAdsPersonalization); +#endif + } + + /// + /// Anonymize user Data. + /// Use this API during the SDK Initialization to explicitly anonymize a user's installs, events and sessions. + /// Default is false + /// + /// boolean shouldAnonymizeUser. + public void anonymizeUser(bool shouldAnonymizeUser) + { +#if !UNITY_EDITOR + _anonymizeUser(shouldAnonymizeUser); +#endif + } + + /// + /// Opt-out for Apple Search Ads attributions. + /// + /// boolean disableCollectIAd. + public void setDisableCollectIAd(bool disableCollectIAd) + { +#if !UNITY_EDITOR + _setDisableCollectIAd(disableCollectIAd); +#endif + } + + /// + /// In app purchase receipt validation Apple environment(production or sandbox). The default value is false. + /// + /// boolean useReceiptValidationSandbox. + public void setUseReceiptValidationSandbox(bool useReceiptValidationSandbox) + { +#if !UNITY_EDITOR + _setUseReceiptValidationSandbox(useReceiptValidationSandbox); +#endif + } + + /// + /// Set this flag to test uninstall on Apple environment(production or sandbox). The default value is false. + /// + /// boolean useUninstallSandbox. + public void setUseUninstallSandbox(bool useUninstallSandbox) + { +#if !UNITY_EDITOR + _setUseUninstallSandbox(useUninstallSandbox); +#endif + } + + /// + /// For advertisers who wrap OneLink within another Universal Link. + /// An advertiser will be able to deeplink from a OneLink wrapped within another Universal Link and also record this retargeting conversion. + /// + /// Array of urls. + public void setResolveDeepLinkURLs(params string[] resolveDeepLinkURLs) + { +#if !UNITY_EDITOR + _setResolveDeepLinkURLs(resolveDeepLinkURLs.Length,resolveDeepLinkURLs); +#endif + } + + /// + /// For advertisers who use vanity OneLinks. + /// + /// Array of domains. + public void setOneLinkCustomDomain(params string[] oneLinkCustomDomains) + { +#if !UNITY_EDITOR + _setOneLinkCustomDomains(oneLinkCustomDomains.Length, oneLinkCustomDomains); +#endif + } + + /// + /// Set the user emails and encrypt them. + /// cryptMethod Encryption method: + /// EmailCryptType.EmailCryptTypeMD5 + /// EmailCryptType.EmailCryptTypeSHA1 + /// EmailCryptType.EmailCryptTypeSHA256 + /// EmailCryptType.EmailCryptTypeNone + /// + /// type Hash algoritm. + /// length of userEmails array. + /// userEmails The list of strings that hold mails.} + + public void setUserEmails(EmailCryptType cryptType, params string[] userEmails) + { +#if !UNITY_EDITOR + _setUserEmails(cryptType, userEmails.Length, userEmails); +#endif + } + + /// + /// Set the user phone number. + /// + /// User phoneNumber. + public void setPhoneNumber(string phoneNumber){ +#if !UNITY_EDITOR + _setPhoneNumber(phoneNumber); +#endif + } + + /// + /// To send and validate in app purchases you can call this method from the processPurchase method - please use v2. + /// + /// The product identifier. + /// The product price. + /// The product currency. + /// The purchase transaction Id. + /// The additional param, which you want to receive it in the raw reports. + public void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary additionalParameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + _validateAndSendInAppPurchase(productIdentifier, price, currency, transactionId, AFMiniJSON.Json.Serialize(additionalParameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// V2 + /// To send and validate in app purchases you can call this method from the processPurchase method. + /// + /// The AFSDKPurchaseDetailsIOS instance. + /// The extra params, which you want to receive it in the raw reports. + public void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary extraEventValues, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + _validateAndSendInAppPurchaseV2(details.productId, details.price, details.currency, details.transactionId, AFMiniJSON.Json.Serialize(extraEventValues), gameObject ? gameObject.name : null); +#endif + } + + /// + /// To record location for geo-fencing. Does the same as code below. + /// + /// The location longitude. + /// The location latitude. + public void recordLocation(double longitude, double latitude) + { +#if !UNITY_EDITOR + _recordLocation(longitude, latitude); +#endif + } + + /// + /// Get AppsFlyer's unique device ID, which is created for every new install of an app. + /// + public string getAppsFlyerId() + { +#if !UNITY_EDITOR + return _getAppsFlyerId(); +#else + return ""; +#endif + } + + /// + /// Register uninstall - you should register for remote notification and provide AppsFlyer the push device token. + /// + /// deviceToken The `deviceToken` from `-application:didRegisterForRemoteNotificationsWithDeviceToken:`. + public void registerUninstall(byte[] deviceToken) + { +#if !UNITY_EDITOR + _registerUninstall(deviceToken); +#endif + } + + /// + /// Enable AppsFlyer to handle a push notification. + /// + /// pushPayload The `userInfo` from received remote notification. One of root keys should be @"af".. + public void handlePushNotification(Dictionary pushPayload) + { +#if !UNITY_EDITOR + _handlePushNotification(AFMiniJSON.Json.Serialize(pushPayload)); +#endif + } + + /// + /// Get SDK version. + /// + public string getSdkVersion() + { +#if !UNITY_EDITOR + return _getSDKVersion(); +#else + return ""; +#endif + } + + /// + /// This property accepts a string value representing the host name for all endpoints. + /// Can be used to Zero rate your application’s data usage.Contact your CSM for more information. + /// + /// Host Name. + /// Host prefix. + public void setHost(string hostPrefix, string host) + { +#if !UNITY_EDITOR + _setHost(host, hostPrefix); +#endif + } + + /// + /// This property is responsible for timeout between sessions in seconds. + /// Default value is 5 seconds. + /// + /// minimum time between 2 separate sessions in seconds. + public void setMinTimeBetweenSessions(int minTimeBetweenSessions) + { +#if !UNITY_EDITOR + _setMinTimeBetweenSessions(minTimeBetweenSessions); +#endif + } + + /// + /// Once this API is invoked, our SDK no longer communicates with our servers and stops functioning. + /// In some extreme cases you might want to shut down all SDK activity due to legal and privacy compliance. + /// This can be achieved with the stopSDK API. + /// + /// boolean isSDKStopped. + public void stopSDK(bool isSDKStopped) + { +#if !UNITY_EDITOR + _stopSDK(isSDKStopped); +#endif + } + + // + /// Was the stopSDK(boolean) API set to true. + /// + /// boolean isSDKStopped. + public bool isSDKStopped() + { +#if !UNITY_EDITOR + return _isSDKStopped(); +#else + return false; +#endif + } + + /// + /// In case you want to track deep linking manually call handleOpenUrl. + /// The continueUserActivity and onOpenURL are implemented in the AppsFlyerAppController.mm class, so + /// only use this method if the other methods do not cover your apps deeplinking needs. + /// + /// The URL to be passed to your AppDelegate. + /// The sourceApplication to be passed to your AppDelegate. + /// The annotation to be passed to your app delegate. + public void handleOpenUrl(string url, string sourceApplication, string annotation) + { +#if !UNITY_EDITOR + _handleOpenUrl(url, sourceApplication, annotation); +#endif + } + + /// + /// Used by advertisers to exclude all networks/integrated partners from getting data. + /// + public void setSharingFilterForAllPartners() + { +#if !UNITY_EDITOR + _setSharingFilterForAllPartners(); +#endif + } + + /// + /// Used by advertisers to set some (one or more) networks/integrated partners to exclude from getting data. + /// + /// partners to exclude from getting data + public void setSharingFilter(params string[] partners) + { +#if !UNITY_EDITOR + _setSharingFilter(partners.Length, partners); +#endif + } + + + /// + /// Lets you configure how which partners should the SDK exclude from data-sharing. + /// partners to exclude from getting data + public static void setSharingFilterForPartners(params string[] partners) + { +#if !UNITY_EDITOR + _setSharingFilterForPartners(partners.Length, partners); +#endif + } + + /// + /// To record an impression use the following API call. + /// Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard. + /// + /// promoted App ID. + /// cross promotion campaign. + /// parameters Dictionary. + public void recordCrossPromoteImpression(string appID, string campaign, Dictionary parameters) + { +#if !UNITY_EDITOR + _recordCrossPromoteImpression(appID, campaign, AFMiniJSON.Json.Serialize(parameters)); +#endif + } + + /// + /// Use the following API to attribute the click and launch the app store's app page. + /// + /// promoted App ID + /// cross promotion campaign + /// additional user params + public void attributeAndOpenStore(string appID, string campaign, Dictionary parameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + _attributeAndOpenStore(appID, campaign, AFMiniJSON.Json.Serialize(parameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// The LinkGenerator class builds the invite URL according to various setter methods which allow passing on additional information on the click. + /// See - https://support.appsflyer.com/hc/en-us/articles/115004480866-User-invite-attribution- + /// + /// parameters Dictionary. + public void generateUserInviteLink(Dictionary parameters, MonoBehaviour gameObject) + { +#if !UNITY_EDITOR + _generateUserInviteLink(AFMiniJSON.Json.Serialize(parameters), gameObject ? gameObject.name : null); +#endif + } + + /// + /// It is recommended to generate an in-app event after the invite is sent to record the invites from the senders' perspective. + /// This enables you to find the users that tend most to invite friends, and the media sources that get you these users. + /// + /// channel string. + /// parameters Dictionary.. + public void recordInvite(string channel, Dictionary parameters) + { +#if !UNITY_EDITOR + _recordInvite(channel, AFMiniJSON.Json.Serialize(parameters)); +#endif + } + + /// + /// Waits for request user authorization to access app-related data + /// + /// time to wait until session starts + public void waitForATTUserAuthorizationWithTimeoutInterval(int timeoutInterval) + { +#if !UNITY_EDITOR + _waitForATTUserAuthorizationWithTimeoutInterval(timeoutInterval); +#endif + } + + /// + /// + /// bool should diable + public void disableSKAdNetwork(bool isDisabled) + { +#if !UNITY_EDITOR + _disableSKAdNetwork(isDisabled); +#endif + } + + /// + /// Use this method if you’re integrating your app with push providers + /// that don’t use the default push notification JSON schema the SDK expects. + /// See docs for more info. + /// + /// array of nested json path + public void addPushNotificationDeepLinkPath(params string[] paths) + { +#if !UNITY_EDITOR + _addPushNotificationDeepLinkPath(paths.Length, paths); +#endif + } + + /// + /// subscribe to unified deep link callbacks + /// + public void subscribeForDeepLink(string objectName){ +#if !UNITY_EDITOR + _subscribeForDeepLink(objectName); +#endif + } + + /// + /// Set the language of the device. + /// + public void setCurrentDeviceLanguage(string language){ +#if !UNITY_EDITOR + _setCurrentDeviceLanguage(language); +#endif + } + + /// + /// Allows sending custom data for partner integration purposes. + /// + public void setPartnerData(string partnerId, Dictionary partnerInfo){ +#if !UNITY_EDITOR + _setPartnerData(partnerId, AFMiniJSON.Json.Serialize(partnerInfo)); +#endif + } + + /// + /// Use to disable app vendor identifier (IDFV) collection, 'true' to disable. + /// + public void disableIDFVCollection(bool isDisabled){ +#if !UNITY_EDITOR + _disableIDFVCollection(isDisabled); +#endif + } + + delegate void unityCallBack(string message); + + [AOT.MonoPInvokeCallback(typeof(unityCallBack))] + public static void getCallback(string gameObjectName, string callbackName, string message) + { + GameObject go = GameObject.Find("AppsFlyerObject"); + var afscript = go.GetComponent("AppsFlyerObjectScript") as AppsFlyerObjectScript; + Type type = typeof(AppsFlyerObjectScript); + MethodInfo info = type.GetMethod(callbackName); + info.Invoke(afscript, new[] { message }); + + } + + + /* + * AppsFlyer ios method mapping + */ + + +#if UNITY_IOS + [DllImport("__Internal")] + private static extern void _startSDK(bool shouldCallback, string objectName); +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] + private static extern void _startSDK(bool shouldCallback, string objectName, Action getCallback); + +#endif + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _getConversionData(string objectName); + + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setCustomerUserID(string customerUserID); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setAdditionalData(string customData); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setAppsFlyerDevKey(string appsFlyerDevKey); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setAppleAppID(string appleAppID); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setCurrencyCode(string currencyCode); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setDisableCollectAppleAdSupport(bool disableCollectAppleAdSupport); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setIsDebug(bool isDebug); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setShouldCollectDeviceName(bool shouldCollectDeviceName); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setAppInviteOneLinkID(string appInviteOneLinkID); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setDeepLinkTimeout(long deepLinkTimeout); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _anonymizeUser(bool shouldAnonymizeUser); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _enableTCFDataCollection(bool shouldCollectTcfData); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setConsentData(bool isUserSubjectToGDPR, bool hasConsentForDataUsage, bool hasConsentForAdsPersonalization); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setDisableCollectIAd(bool disableCollectIAd); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setUseReceiptValidationSandbox(bool useReceiptValidationSandbox); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setUseUninstallSandbox(bool useUninstallSandbox); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setResolveDeepLinkURLs(int length, params string[] resolveDeepLinkURLs); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setOneLinkCustomDomains(int length, params string[] oneLinkCustomDomains); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setUserEmails(EmailCryptType cryptType, int length, params string[] userEmails); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setPhoneNumber(string phoneNumber); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _afSendEvent(string eventName, string eventValues, bool shouldCallback, string objectName); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, string additionalParameters, string objectName); + + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _validateAndSendInAppPurchaseV2(string product, string price, string currency, string transactionId, string extraEventValues, string objectName); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _recordLocation(double longitude, double latitude); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern string _getAppsFlyerId(); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _registerUninstall(byte[] deviceToken); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _handlePushNotification(string pushPayload); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern string _getSDKVersion(); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setHost(string host, string hostPrefix); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setMinTimeBetweenSessions(int minTimeBetweenSessions); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _stopSDK(bool isStopSDK); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern bool _isSDKStopped(); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _handleOpenUrl(string url, string sourceApplication, string annotation); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setSharingFilterForAllPartners(); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setSharingFilter(int length, params string[] partners); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setSharingFilterForPartners(int length, params string[] partners); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _recordCrossPromoteImpression(string appID, string campaign, string parameters); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _attributeAndOpenStore(string appID, string campaign, string parameters, string gameObject); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _generateUserInviteLink(string parameters, string gameObject); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _recordInvite(string channel, string parameters); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _waitForATTUserAuthorizationWithTimeoutInterval(int timeoutInterval); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _disableSKAdNetwork(bool isDisabled); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _addPushNotificationDeepLinkPath(int length, params string[] paths); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _subscribeForDeepLink(string objectName); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setCurrentDeviceLanguage(string language); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _setPartnerData(string partnerId, string partnerInfo); + +#if UNITY_IOS + [DllImport("__Internal")] +#elif UNITY_STANDALONE_OSX + [DllImport("AppsFlyerBundle")] +#endif + private static extern void _disableIDFVCollection(bool isDisabled); + + } + +#endif + + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/AppsFlyeriOS.cs.meta b/Assets/AppsFlyer/AppsFlyeriOS.cs.meta new file mode 100644 index 0000000..36b719f --- /dev/null +++ b/Assets/AppsFlyer/AppsFlyeriOS.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b34371b3cc09641ebb007ffc4e9500f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Editor.meta b/Assets/AppsFlyer/Editor.meta new file mode 100644 index 0000000..a768212 --- /dev/null +++ b/Assets/AppsFlyer/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9f84c02aa78da4ac9b444d98d97f7cc4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef b/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef new file mode 100644 index 0000000..a63b527 --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef @@ -0,0 +1,17 @@ +{ + "name": "AppsFlyer.Editor", + "references": [ + "AppsFlyer" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef.meta b/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef.meta new file mode 100644 index 0000000..f61dfd3 --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyer.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d008146f00dea44d38752b4289e5f65b +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml b/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml new file mode 100644 index 0000000..f7ebbb2 --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml.meta b/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml.meta new file mode 100644 index 0000000..1e4d57e --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyerDependencies.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a03558dbbfeac45db9afe9e9c2df5a85 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs b/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs new file mode 100644 index 0000000..f18e3fa --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs @@ -0,0 +1,84 @@ +using UnityEditor; +using UnityEngine; + + +[CustomEditor(typeof(AppsFlyerObjectScript))] +[CanEditMultipleObjects] +public class AppsFlyerObjectEditor : Editor +{ + + SerializedProperty devKey; + SerializedProperty appID; + SerializedProperty UWPAppID; + SerializedProperty macOSAppID; + SerializedProperty isDebug; + SerializedProperty getConversionData; + + + void OnEnable() + { + devKey = serializedObject.FindProperty("devKey"); + appID = serializedObject.FindProperty("appID"); + UWPAppID = serializedObject.FindProperty("UWPAppID"); + macOSAppID = serializedObject.FindProperty("macOSAppID"); + isDebug = serializedObject.FindProperty("isDebug"); + getConversionData = serializedObject.FindProperty("getConversionData"); + } + + + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + GUILayout.Box((Texture)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets("appsflyer_logo")[0]), typeof(Texture)), new GUILayoutOption[] { GUILayout.Width(600) }); + + EditorGUILayout.Separator(); + EditorGUILayout.HelpBox("Set your devKey and appID to init the AppsFlyer SDK and start tracking. You must modify these fields and provide:\ndevKey - Your application devKey provided by AppsFlyer.\nappId - For iOS only. Your iTunes Application ID.\nUWP app id - For UWP only. Your application app id \nMac OS app id - For MacOS app only.", MessageType.Info); + + EditorGUILayout.PropertyField(devKey); + EditorGUILayout.PropertyField(appID); + EditorGUILayout.PropertyField(UWPAppID); + EditorGUILayout.PropertyField(macOSAppID); + EditorGUILayout.Separator(); + EditorGUILayout.HelpBox("Enable get conversion data to allow your app to recive deeplinking callbacks", MessageType.None); + EditorGUILayout.PropertyField(getConversionData); + EditorGUILayout.Separator(); + EditorGUILayout.HelpBox("Debugging should be restricted to development phase only.\n Do not distribute the app to app stores with debugging enabled", MessageType.Warning); + EditorGUILayout.PropertyField(isDebug); + EditorGUILayout.Separator(); + + EditorGUILayout.HelpBox("For more information on setting up AppsFlyer check out our relevant docs.", MessageType.None); + + + if (GUILayout.Button("AppsFlyer Unity Docs", new GUILayoutOption[] { GUILayout.Width(200) })) + { + Application.OpenURL("https://support.appsflyer.com/hc/en-us/articles/213766183-Unity-SDK-integration-for-developers"); + } + + if (GUILayout.Button("AppsFlyer Android Docs", new GUILayoutOption[] { GUILayout.Width(200) })) + { + Application.OpenURL("https://support.appsflyer.com/hc/en-us/articles/207032126-Android-SDK-integration-for-developers"); + } + + if (GUILayout.Button("AppsFlyer iOS Docs", new GUILayoutOption[] { GUILayout.Width(200) })) + { + Application.OpenURL("https://support.appsflyer.com/hc/en-us/articles/207032066-AppsFlyer-SDK-Integration-iOS"); + } + + if (GUILayout.Button("AppsFlyer Deeplinking Docs", new GUILayoutOption[] { GUILayout.Width(200) })) + { + Application.OpenURL("https://support.appsflyer.com/hc/en-us/articles/208874366-OneLink-deep-linking-guide#Setups"); + } + + if (GUILayout.Button("AppsFlyer Windows Docs", new GUILayoutOption[] { GUILayout.Width(200) })) + { + Application.OpenURL("https://support.appsflyer.com/hc/en-us/articles/207032026-Windows-and-Xbox-SDK-integration-for-developers"); + } + + + serializedObject.ApplyModifiedProperties(); + } + + +} \ No newline at end of file diff --git a/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs.meta b/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs.meta new file mode 100644 index 0000000..53d8abb --- /dev/null +++ b/Assets/AppsFlyer/Editor/AppsFlyerObjectEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d248a134cf494486fb1d6a2e95a05d87 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Editor/appsflyer_logo.png b/Assets/AppsFlyer/Editor/appsflyer_logo.png new file mode 100644 index 0000000..01c2b8c Binary files /dev/null and b/Assets/AppsFlyer/Editor/appsflyer_logo.png differ diff --git a/Assets/AppsFlyer/Editor/appsflyer_logo.png.meta b/Assets/AppsFlyer/Editor/appsflyer_logo.png.meta new file mode 100644 index 0000000..90005e8 --- /dev/null +++ b/Assets/AppsFlyer/Editor/appsflyer_logo.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: bc7fa5a6b64b944a4b2900fd877acb8b +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 11 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + applyGammaDecoding: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs b/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs new file mode 100644 index 0000000..b4c8188 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs @@ -0,0 +1,31 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace AppsFlyerSDK +{ + + public interface IAppsFlyerAndroidBridge : IAppsFlyerNativeBridge + { + void updateServerUninstallToken(string token); + void setImeiData(string imei); + void setAndroidIdData(string androidId); + void waitForCustomerUserId(bool wait); + void setCustomerIdAndStartSDK(string id); + string getOutOfStore(); + void setOutOfStore(string sourceName); + void setCollectAndroidID(bool isCollect); + void setCollectIMEI(bool isCollect); + void setIsUpdate(bool isUpdate); + void setPreinstallAttribution(string mediaSource, string campaign, string siteId); + bool isPreInstalledApp(); + string getAttributionId(); + void handlePushNotifications(); + void validateAndSendInAppPurchase(string publicKey, string signature, string purchaseData, string price, string currency, Dictionary additionalParameters, MonoBehaviour gameObject); + void validateAndSendInAppPurchase(AFPurchaseDetailsAndroid details, Dictionary additionalParameters, MonoBehaviour gameObject); + void setCollectOaid(bool isCollect); + void setDisableAdvertisingIdentifiers(bool disable); + void setDisableNetworkData(bool disable); + + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs.meta b/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs.meta new file mode 100644 index 0000000..8157bc6 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerAndroidBridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cdf9d1bc41a8244b3bc2d249fb6cd7aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerConversionData.cs b/Assets/AppsFlyer/IAppsFlyerConversionData.cs new file mode 100644 index 0000000..454eaa6 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerConversionData.cs @@ -0,0 +1,31 @@ +namespace AppsFlyerSDK +{ + public interface IAppsFlyerConversionData + { + /// + /// `conversionData` contains information about install. Organic/non-organic, etc. + /// https://support.appsflyer.com/hc/en-us/articles/360000726098-Conversion-Data-Scenarios#Introduction + /// + /// JSON string of the returned conversion data. + void onConversionDataSuccess(string conversionData); + + /// + /// Any errors that occurred during the conversion request. + /// + /// A string describing the error. + void onConversionDataFail(string error); + + /// + /// `attributionData` contains information about OneLink, deeplink. + /// https://support.appsflyer.com/hc/en-us/articles/208874366-OneLink-Deep-Linking-Guide#Intro + /// + /// JSON string of the returned deeplink data. + void onAppOpenAttribution(string attributionData); + + /// + /// Any errors that occurred during the attribution request. + /// + /// A string describing the error. + void onAppOpenAttributionFailure(string error); + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerConversionData.cs.meta b/Assets/AppsFlyer/IAppsFlyerConversionData.cs.meta new file mode 100644 index 0000000..3133eaa --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerConversionData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d2f1d4dadb7cb44628f25f1ffd8fc104 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs b/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs new file mode 100644 index 0000000..86211fb --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + + +namespace AppsFlyerSDK +{ + + public interface IAppsFlyerIOSBridge : IAppsFlyerNativeBridge + { + void setDisableCollectAppleAdSupport(bool disable); + void setShouldCollectDeviceName(bool shouldCollectDeviceName); + void setDisableCollectIAd(bool disableCollectIAd); + void setUseReceiptValidationSandbox(bool useReceiptValidationSandbox); + void setUseUninstallSandbox(bool useUninstallSandbox); + void validateAndSendInAppPurchase(string productIdentifier, string price, string currency, string transactionId, Dictionary additionalParameters, MonoBehaviour gameObject); + void validateAndSendInAppPurchase(AFSDKPurchaseDetailsIOS details, Dictionary extraEventValues, MonoBehaviour gameObject); + void registerUninstall(byte[] deviceToken); + void handleOpenUrl(string url, string sourceApplication, string annotation); + void waitForATTUserAuthorizationWithTimeoutInterval(int timeoutInterval); + void setCurrentDeviceLanguage(string language); + void disableSKAdNetwork(bool isDisabled); + void disableIDFVCollection(bool isDisabled); + + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs.meta b/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs.meta new file mode 100644 index 0000000..8e200ea --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerIOSBridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6847fb337898040288c165e3667101a3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs b/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs new file mode 100644 index 0000000..fb1a9cf --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs @@ -0,0 +1,74 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace AppsFlyerSDK +{ + + public interface IAppsFlyerNativeBridge + { + bool isInit { get; set; } + + void startSDK(bool onRequestResponse, string CallBackObjectName); + + void sendEvent(string eventName, Dictionary eventValues, bool onInAppResponse, string CallBackObjectName); + + void stopSDK(bool isSDKStopped); + + bool isSDKStopped(); + + string getSdkVersion(); + + void setCustomerUserId(string id); + + void setAppInviteOneLinkID(string oneLinkId); + + void setAdditionalData(Dictionary customData); + + void setDeepLinkTimeout(long deepLinkTimeout); + + void setResolveDeepLinkURLs(params string[] urls); + + void setOneLinkCustomDomain(params string[] domains); + + void setCurrencyCode(string currencyCode); + + void recordLocation(double latitude, double longitude); + + void anonymizeUser(bool shouldAnonymizeUser); + + string getAppsFlyerId(); + + void enableTCFDataCollection(bool shouldCollectTcfData); + + void setConsentData(AppsFlyerConsent appsFlyerConsent); + + void setMinTimeBetweenSessions(int seconds); + + void setHost(string hostPrefixName, string hostName); + + void setPhoneNumber(string phoneNumber); + + void setSharingFilterForAllPartners(); + + void setSharingFilter(params string[] partners); + + void getConversionData(string objectName); + + void attributeAndOpenStore(string appID, string campaign, Dictionary userParams, MonoBehaviour gameObject); + + void recordCrossPromoteImpression(string appID, string campaign, Dictionary parameters); + + void generateUserInviteLink(Dictionary parameters, MonoBehaviour gameObject); + + void addPushNotificationDeepLinkPath(params string[] paths); + + void setUserEmails(EmailCryptType cryptType, params string[] userEmails); + + void subscribeForDeepLink(string objectName); + + void setIsDebug(bool shouldEnable); + + void setPartnerData(string partnerId, Dictionary partnerInfo); + } +} diff --git a/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs.meta b/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs.meta new file mode 100644 index 0000000..dd43257 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerNativeBridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 409b8302434664a3785ce55d075e7f58 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerUserInvite.cs b/Assets/AppsFlyer/IAppsFlyerUserInvite.cs new file mode 100644 index 0000000..aac109e --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerUserInvite.cs @@ -0,0 +1,26 @@ +namespace AppsFlyerSDK +{ + public interface IAppsFlyerUserInvite + { + /// + /// The success callback for generating OneLink URLs. + /// + /// A string of the newly created url. + void onInviteLinkGenerated(string link); + + /// + /// The error callback for generating OneLink URLs + /// + /// A string describing the error. + void onInviteLinkGeneratedFailure(string error); + + /// + /// (ios only) iOS allows you to utilize the StoreKit component to open + /// the App Store while remaining in the context of your app. + /// More details at https://support.appsflyer.com/hc/en-us/articles/115004481946-Cross-Promotion-Tracking#tracking-cross-promotion-impressions + /// + /// openStore callback Contains promoted `clickURL` + void onOpenStoreLinkGenerated(string link); + + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerUserInvite.cs.meta b/Assets/AppsFlyer/IAppsFlyerUserInvite.cs.meta new file mode 100644 index 0000000..8530528 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerUserInvite.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5a4cdfa023cb8497b94bb39720052fef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs b/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs new file mode 100644 index 0000000..a5c02cf --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs @@ -0,0 +1,19 @@ +namespace AppsFlyerSDK +{ + public interface IAppsFlyerValidateAndLog + { + /// + /// The success callback for validateAndSendInAppPurchase API. + /// For Android : the callback will return JSON string. + /// For iOS : the callback will return a JSON string from apples verifyReceipt API. + /// + /// + void onValidateAndLogComplete(string result); + + /// + /// The error callback for validateAndSendInAppPurchase API. + /// + /// A string describing the error. + void onValidateAndLogFailure(string error); + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs.meta b/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs.meta new file mode 100644 index 0000000..459cc85 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerValidateAndLog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a5adb7eab3284dd39a76ec56c06457c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs b/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs new file mode 100644 index 0000000..90490e2 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs @@ -0,0 +1,19 @@ +namespace AppsFlyerSDK +{ + public interface IAppsFlyerValidateReceipt + { + /// + /// The success callback for validateAndSendInAppPurchase API. + /// For Android : the callback will return "Validate success". + /// For iOS : the callback will return a JSON string from apples verifyReceipt API. + /// + /// + void didFinishValidateReceipt(string result); + + /// + /// The error callback for validateAndSendInAppPurchase API. + /// + /// A string describing the error. + void didFinishValidateReceiptWithError(string error); + } +} \ No newline at end of file diff --git a/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs.meta b/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs.meta new file mode 100644 index 0000000..38efa67 --- /dev/null +++ b/Assets/AppsFlyer/IAppsFlyerValidateReceipt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6385b1d184efa400a98515735e1f17bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac.meta b/Assets/AppsFlyer/Mac.meta new file mode 100644 index 0000000..fd182bd --- /dev/null +++ b/Assets/AppsFlyer/Mac.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 96a328019e42349aabc478b546b8605e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle.meta new file mode 100644 index 0000000..a7aa6da --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 682114f7790724ab3b9410e89bbc076c +folderAsset: yes +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents.meta new file mode 100644 index 0000000..4b06604 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28175da64865f4e398b3b9ddfbe97b24 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist new file mode 100644 index 0000000..3303ccd --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist @@ -0,0 +1,48 @@ + + + + + BuildMachineOSBuild + 20G417 + CFBundleDevelopmentRegion + en + CFBundleExecutable + AppsFlyerBundle + CFBundleIdentifier + com.appsflyer.support.two.AppsFlyerBundle + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + AppsFlyerBundle + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 13A1030d + DTPlatformName + macosx + DTPlatformVersion + 12.0 + DTSDKBuild + 21A344 + DTSDKName + macosx12.0 + DTXcode + 1310 + DTXcodeBuild + 13A1030d + LSMinimumSystemVersion + 11.6 + NSHumanReadableCopyright + + + diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist.meta new file mode 100644 index 0000000..dac263e --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/Info.plist.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 58a86b0b376564c06bf8ce29e1dbfb04 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS.meta new file mode 100644 index 0000000..b55a757 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 218a2e7ff5a4c461981bc41f7d7bfeba +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle new file mode 100644 index 0000000..3376a47 Binary files /dev/null and b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle differ diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle.meta new file mode 100644 index 0000000..a6e35c7 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/MacOS/AppsFlyerBundle.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0889edee891d84a8eb0b7cc87071b91e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature.meta new file mode 100644 index 0000000..d3cac98 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 16068f30788004029bd487756623799b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources new file mode 100644 index 0000000..d5d0fd7 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources @@ -0,0 +1,115 @@ + + + + + files + + files2 + + rules + + ^Resources/ + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^version.plist$ + + + rules2 + + .*\.dSYM($|/) + + weight + 11 + + ^(.*/)?\.DS_Store$ + + omit + + weight + 2000 + + ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ + + nested + + weight + 10 + + ^.* + + ^Info\.plist$ + + omit + + weight + 20 + + ^PkgInfo$ + + omit + + weight + 20 + + ^Resources/ + + weight + 20 + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^[^/]+$ + + nested + + weight + 10 + + ^embedded\.provisionprofile$ + + weight + 20 + + ^version\.plist$ + + weight + 20 + + + + diff --git a/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources.meta b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources.meta new file mode 100644 index 0000000..4cbf196 --- /dev/null +++ b/Assets/AppsFlyer/Mac/AppsFlyerBundle.bundle/Contents/_CodeSignature/CodeResources.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 724b52b308e9a4a6d889d7bf3945a2ca +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins.meta b/Assets/AppsFlyer/Plugins.meta new file mode 100644 index 0000000..5394930 --- /dev/null +++ b/Assets/AppsFlyer/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 66297743248ab4e47abdc371a59f1111 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS.meta b/Assets/AppsFlyer/Plugins/iOS.meta new file mode 100644 index 0000000..286d70c --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d8325c12a80ff4323b82e2833a8fc287 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h new file mode 100644 index 0000000..c838a93 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h @@ -0,0 +1,22 @@ +// +// AFUnityUtils.h +// +// Created by Andrii H. and Dmitry O. on 16 Oct 2023 +// + +#if __has_include() +#import +#else +#import "AppsFlyerLib.h" +#endif + +static NSString* stringFromChar(const char *str); +static NSDictionary* dictionaryFromJson(const char *jsonString); +static const char* stringFromdictionary(NSDictionary* dictionary); +static NSArray *NSArrayFromCArray(int length, const char **arr); +static char* getCString(const char* string); +static AppsFlyerLinkGenerator* generatorFromDictionary(NSDictionary* dictionary, AppsFlyerLinkGenerator* generator); +static EmailCryptType emailCryptTypeFromInt(int emailCryptTypeInt); +static NSString* stringFromDeepLinkResultStatus(AFSDKDeepLinkResultStatus deepLinkResult); +static NSString* stringFromDeepLinkResultError(AppsFlyerDeepLinkResult *result); + diff --git a/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h.meta b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h.meta new file mode 100644 index 0000000..f6811a6 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 4b0609ff467554f2088aee1c52bf54a2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm new file mode 100644 index 0000000..59e0163 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm @@ -0,0 +1,145 @@ +// +// AFUnityUtils.mm +// Unity-iPhone +// +// Created by Jonathan Wesfield on 24/07/2019. +// + +#import "AFUnityUtils.h" + +static NSString* stringFromChar(const char *str) { + return str ? [NSString stringWithUTF8String:str] : nil; +} + +static NSDictionary* dictionaryFromJson(const char *jsonString) { + if(jsonString){ + NSData *jsonData = [[NSData alloc] initWithBytes:jsonString length:strlen(jsonString)]; + NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]; + return dictionary; + } + + return nil; +} + +static const char* stringFromdictionary(NSDictionary* dictionary) { + if(dictionary){ + NSError * err; + NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&err]; + NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return [myString UTF8String]; + } + + return nil; +} + +static NSDictionary* dictionaryFromNSError(NSError* error) { + if(error){ + NSInteger code = [error code]; + NSString *localizedDescription = [error localizedDescription]; + + NSDictionary *errorDictionary = @{ + @"code" : @(code) ?: @(-1), + @"localizedDescription" : localizedDescription, + }; + return errorDictionary; + } + + return nil; +} + + +static NSArray *NSArrayFromCArray(int length, const char **arr) { + NSMutableArray *res = [[NSMutableArray alloc] init]; + for(int i = 0; i < length; i++) { + if (arr[i]) { + [res addObject:[NSString stringWithUTF8String:arr[i]]]; + } + } + + return res; +} + +static char* getCString(const char* string){ + if (string == NULL){ + return NULL; + } + + char* res = (char*)malloc(strlen(string) + 1); + strcpy(res, string); + + return res; +} + +static AppsFlyerLinkGenerator* generatorFromDictionary(NSDictionary* dictionary, AppsFlyerLinkGenerator* generator) { + + NSArray* generatorKeys = @[@"channel", @"customerID", @"campaign", @"referrerName", @"referrerImageUrl", @"deeplinkPath", @"baseDeeplink", @"brandDomain"]; + + NSMutableDictionary* mutableDictionary = [dictionary mutableCopy]; + + [generator setChannel:[dictionary objectForKey: @"channel"]]; + [generator setReferrerCustomerId:[dictionary objectForKey: @"customerID"]]; + [generator setCampaign:[dictionary objectForKey: @"campaign"]]; + [generator setReferrerName:[dictionary objectForKey: @"referrerName"]]; + [generator setReferrerImageURL:[dictionary objectForKey: @"referrerImageUrl"]]; + [generator setDeeplinkPath:[dictionary objectForKey: @"deeplinkPath"]]; + [generator setBaseDeeplink:[dictionary objectForKey: @"baseDeeplink"]]; + [generator setBrandDomain:[dictionary objectForKey: @"brandDomain"]]; + + + [mutableDictionary removeObjectsForKeys:generatorKeys]; + + [generator addParameters:mutableDictionary]; + + return generator; +} + +static EmailCryptType emailCryptTypeFromInt(int emailCryptTypeInt){ + + EmailCryptType emailCryptType; + switch (emailCryptTypeInt){ + case 1: + emailCryptType = EmailCryptTypeSHA256; + break; + default: + emailCryptType = EmailCryptTypeNone; + break; + } + + return emailCryptType; +} + +static NSString* stringFromDeepLinkResultStatus(AFSDKDeepLinkResultStatus deepLinkResult){ + NSString* result; + switch (deepLinkResult){ + case AFSDKDeepLinkResultStatusFound: + result = @"FOUND"; + break; + case AFSDKDeepLinkResultStatusFailure: + result = @"ERROR"; + break; + case AFSDKDeepLinkResultStatusNotFound: + result = @"NOT_FOUND"; + break; + default: + result = @"ERROR"; + break; + } + + return result; +} + +static NSString* stringFromDeepLinkResultError(AppsFlyerDeepLinkResult *result){ + NSString* res; + + if (result && result.error){ + if ([[result.error userInfo][NSUnderlyingErrorKey] code] == -1001) { + res = @"TIMEOUT"; + } else if ([[result.error userInfo][NSUnderlyingErrorKey] code] == -1009) { + res = @"NETWORK"; + } + } + + res = @"UNKNOWN"; + + return res; +} diff --git a/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm.meta b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm.meta new file mode 100644 index 0000000..b411375 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AFUnityUtils.mm.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 18a03931864e84d86bedcc99c440e060 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + - first: + tvOS: tvOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m b/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m new file mode 100644 index 0000000..f877576 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m @@ -0,0 +1,164 @@ +// +// AppsFlyer+AppController.m +// Unity-iPhone +// +// Created by Jonathan Wesfield on 24/07/2019. +// + +#import +#import "UnityAppController.h" +#import "AppsFlyeriOSWrapper.h" +#if __has_include() +#import +#else +#import "AppsFlyerLib.h" +#endif + + +@implementation UnityAppController (AppsFlyerSwizzledAppController) + +static BOOL didEnteredBackGround __unused; +static IMP __original_applicationDidBecomeActive_Imp __unused; +static IMP __original_applicationDidEnterBackground_Imp __unused; +static IMP __original_didReceiveRemoteNotification_Imp __unused; +static IMP __original_continueUserActivity_Imp __unused; +static IMP __original_openUrl_Imp __unused; + + ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + +#if !AFSDK_SHOULD_SWIZZLE + + id swizzleFlag = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"AppsFlyerShouldSwizzle"]; + BOOL shouldSwizzle = swizzleFlag ? [swizzleFlag boolValue] : NO; + + if(shouldSwizzle){ + + Method method1 = class_getInstanceMethod([self class], @selector(applicationDidBecomeActive:)); + __original_applicationDidBecomeActive_Imp = method_setImplementation(method1, (IMP)__swizzled_applicationDidBecomeActive); + + Method method2 = class_getInstanceMethod([self class], @selector(applicationDidEnterBackground:)); + __original_applicationDidEnterBackground_Imp = method_setImplementation(method2, (IMP)__swizzled_applicationDidEnterBackground); + + + Method method3 = class_getInstanceMethod([self class], @selector(didReceiveRemoteNotification:)); + __original_didReceiveRemoteNotification_Imp = method_setImplementation(method3, (IMP)__swizzled_didReceiveRemoteNotification); + + + Method method4 = class_getInstanceMethod([self class], @selector(application:openURL:options:)); + __original_openUrl_Imp = method_setImplementation(method4, (IMP)__swizzled_openURL); + + if (_AppsFlyerdelegate == nil) { + _AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init]; + } + + [self swizzleContinueUserActivity:[self class]]; + } +#elif AFSDK_SHOULD_SWIZZLE + Method method1 = class_getInstanceMethod([self class], @selector(applicationDidBecomeActive:)); + __original_applicationDidBecomeActive_Imp = method_setImplementation(method1, (IMP)__swizzled_applicationDidBecomeActive); + + Method method2 = class_getInstanceMethod([self class], @selector(applicationDidEnterBackground:)); + __original_applicationDidEnterBackground_Imp = method_setImplementation(method2, (IMP)__swizzled_applicationDidEnterBackground); + + + Method method3 = class_getInstanceMethod([self class], @selector(didReceiveRemoteNotification:)); + __original_didReceiveRemoteNotification_Imp = method_setImplementation(method3, (IMP)__swizzled_didReceiveRemoteNotification); + + + Method method4 = class_getInstanceMethod([self class], @selector(application:openURL:options:)); + __original_openUrl_Imp = method_setImplementation(method4, (IMP)__swizzled_openURL); + + if (_AppsFlyerdelegate == nil) { + _AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init]; + } + + [self swizzleContinueUserActivity:[self class]]; + +#endif + + + }); +} + ++(void)swizzleContinueUserActivity:(Class)class { + + SEL originalSelector = @selector(application:continueUserActivity:restorationHandler:); + + Method defaultMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, @selector(__swizzled_continueUserActivity)); + + BOOL isMethodExists = !class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); + + if (isMethodExists) { + __original_continueUserActivity_Imp = method_setImplementation(defaultMethod, (IMP)__swizzled_continueUserActivity); + } else { + class_replaceMethod(class, originalSelector, (IMP)__swizzled_continueUserActivity, method_getTypeEncoding(swizzledMethod)); + } +} + +BOOL __swizzled_continueUserActivity(id self, SEL _cmd, UIApplication* application, NSUserActivity* userActivity, void (^restorationHandler)(NSArray*)) { + NSLog(@"swizzled continueUserActivity"); + [[AppsFlyerAttribution shared] continueUserActivity:userActivity restorationHandler:restorationHandler]; + + if(__original_continueUserActivity_Imp){ + return ((BOOL(*)(id, SEL, UIApplication*, NSUserActivity*, void (^)(NSArray*)))__original_continueUserActivity_Imp)(self, _cmd, application, userActivity, NULL); + } + + return YES; +} + + + +void __swizzled_applicationDidBecomeActive(id self, SEL _cmd, UIApplication* launchOptions) { + NSLog(@"swizzled applicationDidBecomeActive"); + [[AppsFlyerLib shared] setDelegate:_AppsFlyerdelegate]; + + if(didEnteredBackGround && AppsFlyeriOSWarpper.didCallStart == YES){ + [[AppsFlyerLib shared] start]; + } + + if(__original_applicationDidBecomeActive_Imp){ + ((void(*)(id,SEL, UIApplication*))__original_applicationDidBecomeActive_Imp)(self, _cmd, launchOptions); + } +} + + +void __swizzled_applicationDidEnterBackground(id self, SEL _cmd, UIApplication* application) { + NSLog(@"swizzled applicationDidEnterBackground"); + didEnteredBackGround = YES; + if(__original_applicationDidEnterBackground_Imp){ + ((void(*)(id,SEL, UIApplication*))__original_applicationDidEnterBackground_Imp)(self, _cmd, application); + } +} + + +BOOL __swizzled_didReceiveRemoteNotification(id self, SEL _cmd, UIApplication* application, NSDictionary* userInfo,void (^UIBackgroundFetchResult)(void) ) { + NSLog(@"swizzled didReceiveRemoteNotification"); + + [[AppsFlyerLib shared] handlePushNotification:userInfo]; + + if(__original_didReceiveRemoteNotification_Imp){ + return ((BOOL(*)(id, SEL, UIApplication*, NSDictionary*, int(UIBackgroundFetchResult)))__original_didReceiveRemoteNotification_Imp)(self, _cmd, application, userInfo, nil); + } + return YES; +} + + + +BOOL __swizzled_openURL(id self, SEL _cmd, UIApplication* application, NSURL* url, NSDictionary * options) { + NSLog(@"swizzled openURL"); + [[AppsFlyerAttribution shared] handleOpenUrl:url options:options]; + if(__original_openUrl_Imp){ + return ((BOOL(*)(id, SEL, UIApplication*, NSURL*, NSDictionary*))__original_openUrl_Imp)(self, _cmd, application, url, options); + } + return NO; +} + + +@end + + + diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m.meta new file mode 100644 index 0000000..24856fa --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyer+AppController.m.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 6ae9e1f7daef2427588fab2fbf8d35d5 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + - first: + tvOS: tvOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm new file mode 100644 index 0000000..3e492c0 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm @@ -0,0 +1,131 @@ +// +// AppsFlyerAppController.mm +// Unity-iPhone +// +// Created by Jonathan Wesfield on 30/07/2019. +// + +#import +#import "UnityAppController.h" +#import "AppDelegateListener.h" +#import "AppsFlyeriOSWrapper.h" +#if __has_include() +#import +#else +#import "AppsFlyerLib.h" +#endif +#import + +/** + Note if you would like to use method swizzeling see AppsFlyer+AppController.m + If you are using swizzeling then comment out the method that is being swizzeled in AppsFlyerAppController.mm + Only use swizzeling if there are conflicts with other plugins that needs to be resolved. +*/ + + +@interface AppsFlyerAppController : UnityAppController +{ + BOOL didEnteredBackGround; +} +@end + +@implementation AppsFlyerAppController + +- (instancetype)init +{ + self = [super init]; + if (self) { + + id swizzleFlag = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"AppsFlyerShouldSwizzle"]; + BOOL shouldSwizzle = swizzleFlag ? [swizzleFlag boolValue] : NO; + + if(!shouldSwizzle){ + UnityRegisterAppDelegateListener(self); + } + } + return self; +} + +- (void)didFinishLaunching:(NSNotification*)notification { + NSLog(@"got didFinishLaunching = %@",notification.userInfo); + + + if (_AppsFlyerdelegate == nil) { + _AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init]; + } + [[AppsFlyerLib shared] setDelegate:_AppsFlyerdelegate]; + + if (notification.userInfo[@"url"]) { + [self onOpenURL:notification]; + } +} + +-(void)didBecomeActive:(NSNotification*)notification { + NSLog(@"got didBecomeActive(out) = %@", notification.userInfo); + if (didEnteredBackGround == YES && AppsFlyeriOSWarpper.didCallStart == YES) { + [[AppsFlyerLib shared] start]; + didEnteredBackGround = NO; + } +} + +- (void)didEnterBackground:(NSNotification*)notification { + NSLog(@"got didEnterBackground = %@", notification.userInfo); + didEnteredBackGround = YES; +} + +- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler { + [[AppsFlyerAttribution shared] continueUserActivity:userActivity restorationHandler:restorationHandler]; + return YES; +} + + +- (void)onOpenURL:(NSNotification*)notification { + NSLog(@"got onOpenURL = %@", notification.userInfo); + NSURL *url = notification.userInfo[@"url"]; + NSString *sourceApplication = notification.userInfo[@"sourceApplication"]; + + if (sourceApplication == nil) { + sourceApplication = @""; + } + + if (url != nil) { + [[AppsFlyerAttribution shared] handleOpenUrl:url sourceApplication:sourceApplication annotation:nil]; + } + +} + +- (void)didReceiveRemoteNotification:(NSNotification*)notification { + NSLog(@"got didReceiveRemoteNotification = %@", notification.userInfo); + [[AppsFlyerLib shared] handlePushNotification:notification.userInfo]; +} + +@end + +#if !(AFSDK_SHOULD_SWIZZLE) + +IMPL_APP_CONTROLLER_SUBCLASS(AppsFlyerAppController) + +#endif +/** +Note if you would not like to use IMPL_APP_CONTROLLER_SUBCLASS you can replace it with the code below. + + +(void)load + { + [AppsFlyerAppController plugin]; + } + + // Singleton accessor. + + (AppsFlyerAppController *)plugin + { + static AppsFlyerAppController *sharedInstance = nil; + static dispatch_once_t onceToken; + + dispatch_once(&onceToken, ^{ + + sharedInstance = [[AppsFlyerAppController alloc] init]; + }); + + return sharedInstance; + } + + **/ diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm.meta new file mode 100644 index 0000000..2e8e52c --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAppController.mm.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 2d1497a1493b24fecaa58bd3a7b707f9 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + - first: + tvOS: tvOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h new file mode 100644 index 0000000..c79fec4 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h @@ -0,0 +1,34 @@ +// +// AppsFlyerAttribution.h +// UnityFramework +// +// Created by Margot Guetta on 11/04/2021. +// + +#ifndef AppsFlyerAttribution_h +#define AppsFlyerAttribution_h +#endif /* AppsFlyerAttribution_h */ +#if __has_include() +#import +#else +#import "AppsFlyerLib.h" +#endif + + +@interface AppsFlyerAttribution : NSObject +@property NSUserActivity*_Nullable userActivity; +@property (nonatomic, copy) void (^ _Nullable restorationHandler)(NSArray *_Nullable ); +@property NSURL * _Nullable url; +@property NSDictionary * _Nullable options; +@property NSString* _Nullable sourceApplication; +@property id _Nullable annotation; +@property BOOL isBridgeReady; + ++ (AppsFlyerAttribution *_Nullable)shared; +- (void) continueUserActivity: (NSUserActivity*_Nullable) userActivity restorationHandler: (void (^_Nullable)(NSArray * _Nullable))restorationHandler; +- (void) handleOpenUrl:(NSURL*_Nullable)url options:(NSDictionary*_Nullable) options; +- (void) handleOpenUrl: (NSURL *_Nonnull)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation; + +@end + +static NSString * _Nullable const AF_BRIDGE_SET = @"bridge is set"; diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h.meta new file mode 100644 index 0000000..5b77c9b --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 8544dc3b3c7bb40d397b2de568df1058 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m new file mode 100644 index 0000000..c4e7278 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m @@ -0,0 +1,86 @@ +// +// NSObject+AppsFlyerAttribution.m +// UnityFramework +// +// Created by Margot Guetta on 11/04/2021. +// + +#import +#import "AppsFlyerAttribution.h" + +@implementation AppsFlyerAttribution + ++ (id)shared { + static AppsFlyerAttribution *shared = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shared = [[self alloc] init]; + }); + return shared; +} + +- (id)init { + if (self = [super init]) { + self.options = nil; + self.restorationHandler = nil; + self.url = nil; + self.userActivity = nil; + self.annotation = nil; + self.sourceApplication = nil; + self.isBridgeReady = NO; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(receiveBridgeReadyNotification:) + name:AF_BRIDGE_SET + object:nil]; + } + return self; +} + +- (void) continueUserActivity: (NSUserActivity*_Nullable) userActivity restorationHandler: (void (^_Nullable)(NSArray * _Nullable))restorationHandler{ + if(self.isBridgeReady == YES){ + [[AppsFlyerLib shared] continueUserActivity:userActivity restorationHandler:restorationHandler]; + }else{ + [AppsFlyerAttribution shared].userActivity = userActivity; + [AppsFlyerAttribution shared].restorationHandler = restorationHandler; + } +} + +- (void) handleOpenUrl:(NSURL *)url options:(NSDictionary *)options{ + if(self.isBridgeReady == YES){ + [[AppsFlyerLib shared] handleOpenUrl:url options:options]; + }else{ + [AppsFlyerAttribution shared].url = url; + [AppsFlyerAttribution shared].options = options; + } +} + +- (void) handleOpenUrl:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation{ + if(self.isBridgeReady == YES){ + [[AppsFlyerLib shared] handleOpenURL:url sourceApplication:sourceApplication withAnnotation:annotation]; + }else{ + [AppsFlyerAttribution shared].url = url; + [AppsFlyerAttribution shared].sourceApplication = sourceApplication; + [AppsFlyerAttribution shared].annotation = annotation; + } + +} + +- (void) receiveBridgeReadyNotification:(NSNotification *) notification +{ + NSLog (@"AppsFlyer Debug: handle deep link"); + if(self.url && self.sourceApplication){ + [[AppsFlyerLib shared] handleOpenURL:self.url sourceApplication:self.sourceApplication withAnnotation:self.annotation]; + self.url = nil; + self.sourceApplication = nil; + self.annotation = nil; + }else if(self.options && self.url){ + [[AppsFlyerLib shared] handleOpenUrl:self.url options:self.options]; + self.options = nil; + self.url = nil; + }else if(self.userActivity){ + [[AppsFlyerLib shared] continueUserActivity:self.userActivity restorationHandler:nil]; + self.userActivity = nil; + self.restorationHandler = nil; + } +} +@end diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m.meta new file mode 100644 index 0000000..9f071e6 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyerAttribution.m.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 1060e47d7b9e2453ba575f0b455b2bf8 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + - first: + tvOS: tvOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h new file mode 100644 index 0000000..d4cd3c3 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h @@ -0,0 +1,50 @@ +// +// AppsFlyeriOSWarpper.h +// Unity-iPhone +// +// Created by Jonathan Wesfield on 24/07/2019. +// + +#import "AFUnityUtils.mm" +#import "UnityAppController.h" +#import "AppsFlyerAttribution.h" +#if __has_include() +#import +#else +#import "AppsFlyerLib.h" +#endif + +@interface AppsFlyeriOSWarpper : NSObject ++ (BOOL) didCallStart; ++ (void) setDidCallStart:(BOOL)val; +@end + + +static AppsFlyeriOSWarpper *_AppsFlyerdelegate; +static const int kPushNotificationSize = 32; + +static NSString* ConversionDataCallbackObject = @"AppsFlyerObject"; + +static const char* VALIDATE_CALLBACK = "didFinishValidateReceipt"; +static const char* VALIDATE_ERROR_CALLBACK = "didFinishValidateReceiptWithError"; +static const char* GCD_CALLBACK = "onConversionDataSuccess"; +static const char* GCD_ERROR_CALLBACK = "onConversionDataFail"; +static const char* OAOA_CALLBACK = "onAppOpenAttribution"; +static const char* OAOA_ERROR_CALLBACK = "onAppOpenAttributionFailure"; +static const char* GENERATE_LINK_CALLBACK = "onInviteLinkGenerated"; +static const char* OPEN_STORE_LINK_CALLBACK = "onOpenStoreLinkGenerated"; +static const char* START_REQUEST_CALLBACK = "requestResponseReceived"; +static const char* IN_APP_RESPONSE_CALLBACK = "inAppResponseReceived"; +static const char* ON_DEEPLINKING = "onDeepLinking"; +static const char* VALIDATE_AND_LOG_V2_CALLBACK = "onValidateAndLogComplete"; +static const char* VALIDATE_AND_LOG_V2_ERROR_CALLBACK = "onValidateAndLogFailure"; + + +static NSString* validateObjectName = @""; +static NSString* openStoreObjectName = @""; +static NSString* generateInviteObjectName = @""; +static NSString* validateAndLogObjectName = @""; +static NSString* startRequestObjectName = @""; +static NSString* inAppRequestObjectName = @""; +static NSString* onDeeplinkingObjectName = @""; + diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h.meta new file mode 100644 index 0000000..5284989 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.h.meta @@ -0,0 +1,27 @@ +fileFormatVersion: 2 +guid: 147104b04b5794eaa92b4195cc328e13 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm new file mode 100644 index 0000000..95b0f9a --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm @@ -0,0 +1,370 @@ +// +// AppsFlyeriOSWarpper.mm +// Unity-iPhone +// +// Created by Jonathan Wesfield on 24/07/2019. +// + +#import "AppsFlyeriOSWrapper.h" + + +static void unityCallBack(NSString* objectName, const char* method, const char* msg) { + if(objectName){ + UnitySendMessage([objectName UTF8String], method, msg); + } +} + +extern "C" { + + const void _startSDK(bool shouldCallback, const char* objectName) { + [[AppsFlyerLib shared] setPluginInfoWith: AFSDKPluginUnity + pluginVersion:@"6.14.4" + additionalParams:nil]; + startRequestObjectName = stringFromChar(objectName); + AppsFlyeriOSWarpper.didCallStart = YES; + [AppsFlyerAttribution shared].isBridgeReady = YES; + [[NSNotificationCenter defaultCenter] postNotificationName:AF_BRIDGE_SET object: [AppsFlyerAttribution shared]]; + [[AppsFlyerLib shared] startWithCompletionHandler:^(NSDictionary *dictionary, NSError *error) { + if(shouldCallback){ + if (error) { + NSDictionary *callbackDictionary = @{@"statusCode":[NSNumber numberWithLong:[error code]]}; + unityCallBack(startRequestObjectName, START_REQUEST_CALLBACK, stringFromdictionary(callbackDictionary)); + return; + } + if (dictionary) { + unityCallBack(startRequestObjectName, START_REQUEST_CALLBACK, stringFromdictionary(dictionary)); + return; + } + } + }]; + } + + const void _setCustomerUserID (const char* customerUserID) { + [[AppsFlyerLib shared] setCustomerUserID:stringFromChar(customerUserID)]; + } + + const void _setAdditionalData (const char* customData) { + [[AppsFlyerLib shared] setAdditionalData:dictionaryFromJson(customData)]; + } + + const void _setAppsFlyerDevKey (const char* appsFlyerDevKey) { + [AppsFlyerLib shared].appsFlyerDevKey = stringFromChar(appsFlyerDevKey); + } + + const void _setAppleAppID (const char* appleAppID) { + [AppsFlyerLib shared].appleAppID = stringFromChar(appleAppID); + } + + const void _setCurrencyCode (const char* currencyCode) { + [[AppsFlyerLib shared] setCurrencyCode:stringFromChar(currencyCode)]; + } + + const void _setDisableCollectAppleAdSupport (bool disableAdvertisingIdentifier) { + [AppsFlyerLib shared].disableAdvertisingIdentifier = disableAdvertisingIdentifier; + } + + const void _setIsDebug (bool isDebug) { + [AppsFlyerLib shared].isDebug = isDebug; + } + + const void _setShouldCollectDeviceName (bool shouldCollectDeviceName) { + [AppsFlyerLib shared].shouldCollectDeviceName = shouldCollectDeviceName; + } + + const void _setAppInviteOneLinkID (const char* appInviteOneLinkID) { + [[AppsFlyerLib shared] setAppInviteOneLink:stringFromChar(appInviteOneLinkID)]; + } + + const void _setDeepLinkTimeout (long deepLinkTimeout) { + [AppsFlyerLib shared].deepLinkTimeout = deepLinkTimeout; + } + + const void _anonymizeUser (bool anonymizeUser) { + [AppsFlyerLib shared].anonymizeUser = anonymizeUser; + } + + const void _enableTCFDataCollection (bool shouldCollectTcfData) { + [[AppsFlyerLib shared] enableTCFDataCollection:shouldCollectTcfData]; + } + + const void _setConsentData(bool isUserSubjectToGDPR, bool hasConsentForDataUsage, bool hasConsentForAdsPersonalization) { + AppsFlyerConsent *consentData = nil; + if (isUserSubjectToGDPR) { + consentData = [[AppsFlyerConsent alloc] initForGDPRUserWithHasConsentForDataUsage:hasConsentForDataUsage hasConsentForAdsPersonalization:hasConsentForAdsPersonalization]; + } else { + consentData = [[AppsFlyerConsent alloc] initNonGDPRUser]; + } + [[AppsFlyerLib shared] setConsentData:consentData]; + } + + const void _setDisableCollectIAd (bool disableCollectASA) { + [AppsFlyerLib shared].disableCollectASA = disableCollectASA; + } + + const void _setUseReceiptValidationSandbox (bool useReceiptValidationSandbox) { + [AppsFlyerLib shared].useReceiptValidationSandbox = useReceiptValidationSandbox; + } + + const void _setUseUninstallSandbox (bool useUninstallSandbox) { + [AppsFlyerLib shared].useUninstallSandbox = useUninstallSandbox; + } + + const void _setResolveDeepLinkURLs (int length, const char **resolveDeepLinkURLs) { + if(length > 0 && resolveDeepLinkURLs) { + [[AppsFlyerLib shared] setResolveDeepLinkURLs:NSArrayFromCArray(length, resolveDeepLinkURLs)]; + } + } + + const void _setOneLinkCustomDomains (int length, const char **oneLinkCustomDomains) { + if(length > 0 && oneLinkCustomDomains) { + [[AppsFlyerLib shared] setOneLinkCustomDomains:NSArrayFromCArray(length, oneLinkCustomDomains)]; + } + } + + const void _afSendEvent (const char* eventName, const char* eventValues, bool shouldCallback, const char* objectName) { + inAppRequestObjectName = stringFromChar(objectName); + [[AppsFlyerLib shared] logEventWithEventName:stringFromChar(eventName) eventValues:dictionaryFromJson(eventValues) completionHandler:^(NSDictionary *dictionary, NSError *error) { + if(shouldCallback){ + if (error) { + NSDictionary *callbackDictionary = @{@"statusCode":[NSNumber numberWithLong:[error code]]}; + unityCallBack(inAppRequestObjectName, IN_APP_RESPONSE_CALLBACK, stringFromdictionary(callbackDictionary)); + return; + } + if (dictionary) { + unityCallBack(inAppRequestObjectName, IN_APP_RESPONSE_CALLBACK, stringFromdictionary(dictionary)); + return; + } + } + }]; + } + + const void _recordLocation (double longitude, double latitude) { + [[AppsFlyerLib shared] logLocation:longitude latitude:latitude]; + } + + const char* _getAppsFlyerId () { + return getCString([[[AppsFlyerLib shared] getAppsFlyerUID] UTF8String]); + } + + const void _registerUninstall (unsigned char* deviceToken) { + if(deviceToken){ + NSData* tokenData = [NSData dataWithBytes:(const void *)deviceToken length:sizeof(unsigned char)*kPushNotificationSize]; + [[AppsFlyerLib shared] registerUninstall:tokenData]; + } + } + + const void _handlePushNotification (const char* pushPayload) { + [[AppsFlyerLib shared] handlePushNotification:dictionaryFromJson(pushPayload)]; + } + + const char* _getSDKVersion () { + return getCString([[[AppsFlyerLib shared] getSDKVersion] UTF8String]); + } + + const void _setHost (const char* host, const char* hostPrefix) { + [[AppsFlyerLib shared] setHost:stringFromChar(host) withHostPrefix:stringFromChar(hostPrefix)]; + } + + const void _setMinTimeBetweenSessions (int minTimeBetweenSessions) { + [AppsFlyerLib shared].minTimeBetweenSessions = minTimeBetweenSessions; + } + + const void _stopSDK (bool isStopped) { + [AppsFlyerLib shared].isStopped = isStopped; + } + + const BOOL _isSDKStopped () { + return [AppsFlyerLib shared].isStopped; + } + + const void _handleOpenUrl(const char *url, const char *sourceApplication, const char *annotation) { + [[AppsFlyerLib shared] handleOpenURL:[NSURL URLWithString:stringFromChar(url)] sourceApplication:stringFromChar(sourceApplication) withAnnotation:stringFromChar(annotation)]; } + + const void _recordCrossPromoteImpression (const char* appID, const char* campaign, const char* parameters) { + [AppsFlyerCrossPromotionHelper logCrossPromoteImpression:stringFromChar(appID) campaign:stringFromChar(campaign) parameters:dictionaryFromJson(parameters)]; } + + const void _attributeAndOpenStore (const char* appID, const char* campaign, const char* parameters, const char* objectName) { + + openStoreObjectName = stringFromChar(objectName); + + [AppsFlyerCrossPromotionHelper + logAndOpenStore:stringFromChar(appID) + campaign:stringFromChar(campaign) + parameters:dictionaryFromJson(parameters) + openStore:^(NSURLSession * _Nonnull urlSession, NSURL * _Nonnull clickURL) { + unityCallBack(openStoreObjectName, OPEN_STORE_LINK_CALLBACK, [clickURL.absoluteString UTF8String]); + }]; + } + + const void _generateUserInviteLink (const char* parameters, const char* objectName) { + + generateInviteObjectName = stringFromChar(objectName); + + [AppsFlyerShareInviteHelper generateInviteUrlWithLinkGenerator:^AppsFlyerLinkGenerator * _Nonnull(AppsFlyerLinkGenerator * _Nonnull generator) { + return generatorFromDictionary(dictionaryFromJson(parameters), generator); + } completionHandler:^(NSURL * _Nullable url) { + unityCallBack(generateInviteObjectName, GENERATE_LINK_CALLBACK, [url.absoluteString UTF8String]); + }]; + } + + const void _recordInvite (const char* channel, const char* parameters) { + [AppsFlyerShareInviteHelper logInvite:stringFromChar(channel) parameters:dictionaryFromJson(parameters)]; + } + + const void _setUserEmails (int emailCryptTypeInt , int length, const char **userEmails) { + if(length > 0 && userEmails) { + [[AppsFlyerLib shared] setUserEmails:NSArrayFromCArray(length, userEmails) withCryptType:emailCryptTypeFromInt(emailCryptTypeInt)]; + } + } + + const void _setPhoneNumber (const char* phoneNumber) { + [[AppsFlyerLib shared] setPhoneNumber:stringFromChar(phoneNumber)]; + } + + const void _setSharingFilterForAllPartners () { + [[AppsFlyerLib shared] setSharingFilterForAllPartners]; + } + + const void _setSharingFilter (int length, const char **partners) { + if(length > 0 && partners) { + [[AppsFlyerLib shared] setSharingFilter:NSArrayFromCArray(length, partners)]; + } + } + + const void _setSharingFilterForPartners (int length, const char **partners) { + if(length > 0 && partners) { + [[AppsFlyerLib shared] setSharingFilterForPartners:NSArrayFromCArray(length, partners)]; + } else { + [[AppsFlyerLib shared] setSharingFilterForPartners:nil]; + } + } + + const void _validateAndSendInAppPurchase (const char* productIdentifier, const char* price, const char* currency, const char* transactionId, const char* additionalParameters, const char* objectName) { + + validateObjectName = stringFromChar(objectName); + + [[AppsFlyerLib shared] + validateAndLogInAppPurchase:stringFromChar(productIdentifier) + price:stringFromChar(price) + currency:stringFromChar(currency) + transactionId:stringFromChar(transactionId) + additionalParameters:dictionaryFromJson(additionalParameters) + success:^(NSDictionary *result){ + unityCallBack(validateObjectName, VALIDATE_CALLBACK, stringFromdictionary(result)); + } failure:^(NSError *error, id response) { + if(response && [response isKindOfClass:[NSDictionary class]]) { + NSDictionary* value = (NSDictionary*)response; + unityCallBack(validateObjectName, VALIDATE_ERROR_CALLBACK, stringFromdictionary(value)); + } else { + unityCallBack(validateObjectName, VALIDATE_ERROR_CALLBACK, error ? [[error localizedDescription] UTF8String] : "error"); + } + }]; + } + + const void _validateAndSendInAppPurchaseV2 (const char* product, const char* price, const char* currency, const char* transactionId, const char* extraEventValues, const char* objectName) { + + validateAndLogObjectName = stringFromChar(objectName); + AFSDKPurchaseDetails *details = [[AFSDKPurchaseDetails alloc] initWithProductId:stringFromChar(product) price:stringFromChar(price) currency:stringFromChar(currency) transactionId:stringFromChar(transactionId)]; + + [[AppsFlyerLib shared] + validateAndLogInAppPurchase:details + extraEventValues:dictionaryFromJson(extraEventValues) + completionHandler:^(AFSDKValidateAndLogResult * _Nullable result) { + if (result.status == AFSDKValidateAndLogStatusSuccess) { + unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_CALLBACK, stringFromdictionary(result.result)); + } else if (result.status == AFSDKValidateAndLogStatusFailure) { + unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_CALLBACK, stringFromdictionary(result.errorData)); + } else { + unityCallBack(validateAndLogObjectName, VALIDATE_AND_LOG_V2_ERROR_CALLBACK, stringFromdictionary(dictionaryFromNSError(result.error))); + } + }]; + + } + + const void _getConversionData(const char* objectName) { + if (_AppsFlyerdelegate == nil) { + _AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init]; + } + ConversionDataCallbackObject = stringFromChar(objectName); + [[AppsFlyerLib shared] setDelegate:_AppsFlyerdelegate]; + } + + const void _waitForATTUserAuthorizationWithTimeoutInterval (int timeoutInterval) { + [[AppsFlyerLib shared] waitForATTUserAuthorizationWithTimeoutInterval:timeoutInterval]; + } + + const void _disableSKAdNetwork (bool isDisabled) { + [AppsFlyerLib shared].disableSKAdNetwork = isDisabled; + } + + const void _addPushNotificationDeepLinkPath (int length, const char **paths) { + if(length > 0 && paths) { + [[AppsFlyerLib shared] addPushNotificationDeepLinkPath:NSArrayFromCArray(length, paths)]; + } + } + + const void _subscribeForDeepLink (const char* objectName) { + + onDeeplinkingObjectName = stringFromChar(objectName); + + if (_AppsFlyerdelegate == nil) { + _AppsFlyerdelegate = [[AppsFlyeriOSWarpper alloc] init]; + } + [[AppsFlyerLib shared] setDeepLinkDelegate:_AppsFlyerdelegate]; + } + + const void _setCurrentDeviceLanguage(const char* language) { + [[AppsFlyerLib shared] setCurrentDeviceLanguage:stringFromChar(language)]; + } + + const void _setPartnerData(const char* partnerId, const char* partnerInfo) { + [[AppsFlyerLib shared] setPartnerDataWithPartnerId: stringFromChar(partnerId) partnerInfo:dictionaryFromJson(partnerInfo)]; + } + + const void _disableIDFVCollection(bool isDisabled) { + [AppsFlyerLib shared].disableIDFVCollection = isDisabled; + } + +} + +@implementation AppsFlyeriOSWarpper + +static BOOL didCallStart; ++ (BOOL) didCallStart +{ @synchronized(self) { return didCallStart; } } ++ (void) setDidCallStart:(BOOL)val +{ @synchronized(self) { didCallStart = val; } } + +- (void)onConversionDataSuccess:(NSDictionary *)installData { + unityCallBack(ConversionDataCallbackObject, GCD_CALLBACK, stringFromdictionary(installData)); +} + +- (void)onConversionDataFail:(NSError *)error { + unityCallBack(ConversionDataCallbackObject, GCD_ERROR_CALLBACK, [[error localizedDescription] UTF8String]); +} + +- (void)onAppOpenAttribution:(NSDictionary *)attributionData { + unityCallBack(ConversionDataCallbackObject, OAOA_CALLBACK, stringFromdictionary(attributionData)); +} + +- (void)onAppOpenAttributionFailure:(NSError *)error { + unityCallBack(ConversionDataCallbackObject, OAOA_ERROR_CALLBACK, [[error localizedDescription] UTF8String]); +} + +- (void)didResolveDeepLink:(AppsFlyerDeepLinkResult *)result{ + + NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; + + [dict setValue:stringFromDeepLinkResultError(result) forKey:@"error"]; + [dict setValue:stringFromDeepLinkResultStatus(result.status) forKey:@"status"]; + + if(result && result.deepLink){ + [dict setValue:result.deepLink.description forKey:@"deepLink"]; + [dict setValue:@(result.deepLink.isDeferred) forKey:@"is_deferred"]; + } + + unityCallBack(onDeeplinkingObjectName, ON_DEEPLINKING, stringFromdictionary(dict)); +} + +@end + diff --git a/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm.meta b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm.meta new file mode 100644 index 0000000..3799161 --- /dev/null +++ b/Assets/AppsFlyer/Plugins/iOS/AppsFlyeriOSWrapper.mm.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 2bff3788f3d8747fe9679bd3818e1d76 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + iPhone: iOS + second: + enabled: 1 + settings: {} + - first: + tvOS: tvOS + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests.meta b/Assets/AppsFlyer/Tests.meta new file mode 100644 index 0000000..8217a6a --- /dev/null +++ b/Assets/AppsFlyer/Tests.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1f19f272c71674582bed1d93925da003 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/Castle.Core.dll b/Assets/AppsFlyer/Tests/Castle.Core.dll new file mode 100644 index 0000000..268e311 Binary files /dev/null and b/Assets/AppsFlyer/Tests/Castle.Core.dll differ diff --git a/Assets/AppsFlyer/Tests/Castle.Core.dll.meta b/Assets/AppsFlyer/Tests/Castle.Core.dll.meta new file mode 100644 index 0000000..14cc646 --- /dev/null +++ b/Assets/AppsFlyer/Tests/Castle.Core.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 7b5b4579db85b4cfd8395bfb19aa309e +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/NSubstitute.dll b/Assets/AppsFlyer/Tests/NSubstitute.dll new file mode 100644 index 0000000..f32e491 Binary files /dev/null and b/Assets/AppsFlyer/Tests/NSubstitute.dll differ diff --git a/Assets/AppsFlyer/Tests/NSubstitute.dll.meta b/Assets/AppsFlyer/Tests/NSubstitute.dll.meta new file mode 100644 index 0000000..b716f6a --- /dev/null +++ b/Assets/AppsFlyer/Tests/NSubstitute.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 642cf65ed2573419bab7e7d44fc73181 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll b/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll new file mode 100644 index 0000000..c5ba4e4 Binary files /dev/null and b/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll differ diff --git a/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll.meta b/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll.meta new file mode 100644 index 0000000..fca3770 --- /dev/null +++ b/Assets/AppsFlyer/Tests/System.Runtime.CompilerServices.Unsafe.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 3a5ccbd864ba94a9a9ba47895ff14922 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll b/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll new file mode 100644 index 0000000..dfc4cdf Binary files /dev/null and b/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll differ diff --git a/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll.meta b/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll.meta new file mode 100644 index 0000000..cb661ca --- /dev/null +++ b/Assets/AppsFlyer/Tests/System.Threading.Tasks.Extensions.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: ee45ae2608f3c44d08fc6e21a94d133f +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/Tests.asmdef b/Assets/AppsFlyer/Tests/Tests.asmdef new file mode 100644 index 0000000..4d10363 --- /dev/null +++ b/Assets/AppsFlyer/Tests/Tests.asmdef @@ -0,0 +1,24 @@ +{ + "name": "Tests", + "references": [ + "UnityEngine.TestRunner", + "UnityEditor.TestRunner", + "AppsFlyer" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll", + "NSubstitute.dll", + "Castle.Core.dll", + "System.Threading.Tasks.Extensions.dll" + ], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/AppsFlyer/Tests/Tests.asmdef.meta b/Assets/AppsFlyer/Tests/Tests.asmdef.meta new file mode 100644 index 0000000..2778008 --- /dev/null +++ b/Assets/AppsFlyer/Tests/Tests.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1f155a0e4c9ab48eeb4b54b2dc0aeba7 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Tests/Tests_Suite.cs b/Assets/AppsFlyer/Tests/Tests_Suite.cs new file mode 100644 index 0000000..9523131 --- /dev/null +++ b/Assets/AppsFlyer/Tests/Tests_Suite.cs @@ -0,0 +1,810 @@ +using System.Collections.Generic; +using NUnit.Framework; +using UnityEngine; +using NSubstitute; + +namespace AppsFlyerSDK.Tests +{ + public class NewTestScript + { + + [Test] + public void test_startSDK_called() + { + var AppsFlyerMOCKInterface = Substitute.For(); + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.startSDK(); + AppsFlyerMOCKInterface.Received().startSDK(Arg.Any(), Arg.Any()); + + } + + [Test] + public void test_sendEvent_withValues() + { + var AppsFlyerMOCKInterface = Substitute.For(); + AppsFlyer.instance = AppsFlyerMOCKInterface; + var eventParams = new Dictionary(); + eventParams.Add("key", "value"); + AppsFlyer.sendEvent("testevent", eventParams); + AppsFlyerMOCKInterface.Received().sendEvent("testevent", eventParams, false, null); + } + + [Test] + public void test_sendEvent_withNullParams() + { + var AppsFlyerMOCKInterface = Substitute.For(); + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.sendEvent("testevent", null); + AppsFlyerMOCKInterface.Received().sendEvent("testevent", null,false, null); + } + + + [Test] + public void test_isSDKStopped_true() + { + var AppsFlyerMOCKInterface = Substitute.For(); + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.stopSDK(true); + + AppsFlyerMOCKInterface.Received().stopSDK(true); + + } + + [Test] + public void test_isSDKStopped_false() + { + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + AppsFlyer.stopSDK(false); + + AppsFlyerMOCKInterface.Received().stopSDK(false); + + } + + [Test] + public void test_isSDKStopped_called() + { + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + var isSDKStopped = AppsFlyer.isSDKStopped(); + + AppsFlyerMOCKInterface.Received().isSDKStopped(); + + } + + [Test] + public void test_isSDKStopped_receveivedFalse() + { + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + var isSDKStopped = AppsFlyer.isSDKStopped(); + + Assert.AreEqual(AppsFlyerMOCKInterface.Received().isSDKStopped(), false); + + + } + + + [Test] + public void test_getSdkVersion_called() + { + var AppsFlyerMOCKInterface = Substitute.For(); + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.getSdkVersion(); + AppsFlyerMOCKInterface.Received().getSdkVersion(); + } + + [Test] + public void test_setCustomerUserId_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCustomerUserId("test"); + AppsFlyerMOCKInterface.Received().setCustomerUserId("test"); + + } + + [Test] + public void Test_setAppInviteOneLinkID_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setAppInviteOneLinkID("2f36"); + AppsFlyerMOCKInterface.Received().setAppInviteOneLinkID("2f36"); + + } + + [Test] + public void Test_setAdditionalData_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + var customData = new Dictionary(); + customData.Add("test", "test"); + AppsFlyer.setAdditionalData(customData); + AppsFlyerMOCKInterface.Received().setAdditionalData(customData); + } + + [Test] + public void Test_setResolveDeepLinkURLs_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setResolveDeepLinkURLs("url1", "url2"); + AppsFlyerMOCKInterface.Received().setResolveDeepLinkURLs("url1", "url2"); + + } + + [Test] + public void Test_setOneLinkCustomDomain_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setOneLinkCustomDomain("url1", "url2"); + AppsFlyerMOCKInterface.Received().setOneLinkCustomDomain("url1", "url2"); + + } + + [Test] + public void Test_setCurrencyCode_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCurrencyCode("usd"); + AppsFlyerMOCKInterface.Received().setCurrencyCode("usd"); + + } + + [Test] + public void Test_recordLocation_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.recordLocation(0.3, 5.2); + AppsFlyerMOCKInterface.Received().recordLocation(0.3, 5.2); + + } + + [Test] + public void Test_anonymizeUser_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.anonymizeUser(true); + AppsFlyerMOCKInterface.Received().anonymizeUser(true); + + } + + [Test] + public void Test_anonymizeUser_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.anonymizeUser(false); + AppsFlyerMOCKInterface.Received().anonymizeUser(false); + + } + + [Test] + public void Test_getAppsFlyerId_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.getAppsFlyerId(); + AppsFlyerMOCKInterface.Received().getAppsFlyerId(); + + } + + [Test] + public void Test_setMinTimeBetweenSessions_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setMinTimeBetweenSessions(3); + AppsFlyerMOCKInterface.Received().setMinTimeBetweenSessions(3); + + } + + [Test] + public void Test_setHost_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setHost("prefix", "name"); + AppsFlyerMOCKInterface.Received().setHost("prefix", "name"); + + } + + [Test] + public void Test_setPhoneNumber_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setPhoneNumber("002"); + AppsFlyerMOCKInterface.Received().setPhoneNumber("002"); + + } + + + [Test] + [System.Obsolete] + public void Test_setSharingFilterForAllPartners_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setSharingFilterForAllPartners(); + AppsFlyerMOCKInterface.Received().setSharingFilterForAllPartners(); + + } + + [Test] + [System.Obsolete] + public void Test_setSharingFilter_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + + AppsFlyer.setSharingFilter("filter1", "filter2"); + AppsFlyerMOCKInterface.Received().setSharingFilter("filter1", "filter2"); + + } + + [Test] + public void Test_getConversionData_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + AppsFlyer.getConversionData("ObjectName"); + AppsFlyerMOCKInterface.Received().getConversionData("ObjectName"); + + } + + [Test] + public void Test_attributeAndOpenStore_called_withParams() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + Dictionary parameters = new Dictionary(); + parameters.Add("af_sub1", "val"); + parameters.Add("custom_param", "val2"); + AppsFlyer.attributeAndOpenStore("appid", "campaign", parameters, new MonoBehaviour()); + AppsFlyerMOCKInterface.Received().attributeAndOpenStore("appid", "campaign", parameters, Arg.Any()); + + } + + [Test] + public void Test_attributeAndOpenStore_called_nullParams() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + AppsFlyer.attributeAndOpenStore("appid", "campaign", null, new MonoBehaviour()); + AppsFlyerMOCKInterface.Received().attributeAndOpenStore("appid", "campaign", null, Arg.Any()); + + } + + [Test] + public void Test_recordCrossPromoteImpression_calledWithParameters() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + Dictionary parameters = new Dictionary(); + parameters.Add("af_sub1", "val"); + parameters.Add("custom_param", "val2"); + AppsFlyer.recordCrossPromoteImpression("appid", "campaign", parameters); + AppsFlyerMOCKInterface.Received().recordCrossPromoteImpression("appid", "campaign", parameters); + + } + + + + [Test] + public void Test_recordCrossPromoteImpression_calledWithoutParameters() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.recordCrossPromoteImpression("appid", "campaign", null); + AppsFlyerMOCKInterface.Received().recordCrossPromoteImpression("appid", "campaign", null); + + } + + [Test] + public void Test_generateUserInviteLink_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + + AppsFlyer.generateUserInviteLink(new Dictionary(), new MonoBehaviour()); + AppsFlyerMOCKInterface.Received().generateUserInviteLink(Arg.Any>(), Arg.Any()); + + } + + + [Test] + public void Test_addPushNotificationDeepLinkPath_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.addPushNotificationDeepLinkPath("path1", "path2"); + AppsFlyerMOCKInterface.Received().addPushNotificationDeepLinkPath("path1", "path2"); + + } + +#if UNITY_ANDROID + [Test] + public void updateServerUninstallToken_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.updateServerUninstallToken("tokenTest"); + AppsFlyerMOCKInterface.Received().updateServerUninstallToken("tokenTest"); + + } + + [Test] + public void setImeiData_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setImeiData("imei"); + AppsFlyerMOCKInterface.Received().setImeiData("imei"); + + } + + [Test] + public void setAndroidIdData_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setAndroidIdData("androidId"); + AppsFlyerMOCKInterface.Received().setAndroidIdData("androidId"); + + } + + [Test] + public void waitForCustomerUserId_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.waitForCustomerUserId(true); + AppsFlyerMOCKInterface.Received().waitForCustomerUserId(true); + + } + + [Test] + public void setCustomerIdAndStartSDK_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCustomerIdAndStartSDK("01234"); + AppsFlyerMOCKInterface.Received().setCustomerIdAndStartSDK("01234"); + + } + + + [Test] + public void getOutOfStore_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.getOutOfStore(); + AppsFlyerMOCKInterface.Received().getOutOfStore(); + + } + + [Test] + public void setOutOfStore_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setOutOfStore("test"); + AppsFlyerMOCKInterface.Received().setOutOfStore("test"); + + } + + [Test] + public void setCollectAndroidID_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCollectAndroidID(true); + AppsFlyerMOCKInterface.Received().setCollectAndroidID(true); + + } + + [Test] + public void setCollectIMEI_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCollectIMEI(true); + AppsFlyerMOCKInterface.Received().setCollectIMEI(true); + + } + + [Test] + public void setIsUpdate_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setIsUpdate(true); + AppsFlyerMOCKInterface.Received().setIsUpdate(true); + + } + + [Test] + public void setPreinstallAttribution_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setPreinstallAttribution("mediaSourceTestt", "campaign", "sideId"); + AppsFlyerMOCKInterface.Received().setPreinstallAttribution("mediaSourceTestt", "campaign", "sideId"); + + } + + [Test] + public void isPreInstalledApp_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.isPreInstalledApp(); + AppsFlyerMOCKInterface.Received().isPreInstalledApp(); + + } + + [Test] + public void getAttributionId_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.getAttributionId(); + AppsFlyerMOCKInterface.Received().getAttributionId(); + + } + + [Test] + public void handlePushNotifications_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.handlePushNotifications(); + AppsFlyerMOCKInterface.Received().handlePushNotifications(); + + } + + [Test] + public void validateAndSendInAppPurchase_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.validateAndSendInAppPurchase("ewjkekwjekw","hewjehwj", "purchaseData", "3.0", "USD", null, null); + AppsFlyerMOCKInterface.Received().validateAndSendInAppPurchase("ewjkekwjekw", "hewjehwj", "purchaseData", "3.0", "USD", null, null); + + } + + [Test] + public void setCollectOaid_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCollectOaid(true); + AppsFlyerMOCKInterface.Received().setCollectOaid(true); + + } + + [Test] + public void setDisableAdvertisingIdentifiers_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableAdvertisingIdentifiers(true); + AppsFlyerMOCKInterface.Received().setDisableAdvertisingIdentifiers(true); + + } + + [Test] + public void setDisableNetworkData_called() { + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableNetworkData(true); + AppsFlyerMOCKInterface.Received().setDisableNetworkData(true); + } +#elif UNITY_IOS + + [Test] + public void setDisableCollectAppleAdSupport_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableCollectAppleAdSupport(true); + AppsFlyerMOCKInterface.Received().setDisableCollectAppleAdSupport(true); + + } + + [Test] + public void setDisableCollectAppleAdSupport_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableCollectAppleAdSupport(false); + AppsFlyerMOCKInterface.Received().setDisableCollectAppleAdSupport(false); + + } + + [Test] + [System.Obsolete] + public void setShouldCollectDeviceName_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setShouldCollectDeviceName(true); + AppsFlyerMOCKInterface.Received().setShouldCollectDeviceName(true); + + } + + [Test] + [System.Obsolete] + public void setShouldCollectDeviceName_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setShouldCollectDeviceName(false); + AppsFlyerMOCKInterface.Received().setShouldCollectDeviceName(false); + + } + + [Test] + public void setDisableCollectIAd_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableCollectIAd(true); + AppsFlyerMOCKInterface.Received().setDisableCollectIAd(true); + + } + + [Test] + public void setDisableCollectIAd_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setDisableCollectIAd(false); + AppsFlyerMOCKInterface.Received().setDisableCollectIAd(false); + + } + + [Test] + public void setUseReceiptValidationSandbox_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setUseReceiptValidationSandbox(true); + AppsFlyerMOCKInterface.Received().setUseReceiptValidationSandbox(true); + + } + + [Test] + public void setUseReceiptValidationSandbox_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setUseReceiptValidationSandbox(false); + AppsFlyerMOCKInterface.Received().setUseReceiptValidationSandbox(false); + + } + + [Test] + public void ssetUseUninstallSandbox_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setUseUninstallSandbox(true); + AppsFlyerMOCKInterface.Received().setUseUninstallSandbox(true); + + } + + [Test] + public void setUseUninstallSandbox_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setUseUninstallSandbox(false); + AppsFlyerMOCKInterface.Received().setUseUninstallSandbox(false); + + } + + [Test] + public void validateAndSendInAppPurchase_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.validateAndSendInAppPurchase("3d2", "5.0","USD", "45", null, null); + AppsFlyerMOCKInterface.Received().validateAndSendInAppPurchase("3d2", "5.0", "USD", "45", null, null); + + } + + [Test] + public void registerUninstall_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + byte[] token = System.Text.Encoding.UTF8.GetBytes("740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad"); + AppsFlyer.registerUninstall(token); + AppsFlyerMOCKInterface.Received().registerUninstall(token); + + } + + [Test] + public void handleOpenUrl_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.handleOpenUrl("www.test.com", "appTest", "test"); + AppsFlyerMOCKInterface.Received().handleOpenUrl("www.test.com", "appTest", "test"); + + } + + [Test] + public void waitForATTUserAuthorizationWithTimeoutInterval_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.waitForATTUserAuthorizationWithTimeoutInterval(30); + AppsFlyerMOCKInterface.Received().waitForATTUserAuthorizationWithTimeoutInterval(30); + + } + + [Test] + public void setCurrentDeviceLanguage_called() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.setCurrentDeviceLanguage("en"); + AppsFlyerMOCKInterface.Received().setCurrentDeviceLanguage("en"); + + } + + [Test] + public void disableSKAdNetwork_called_true() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.disableSKAdNetwork(true); + AppsFlyerMOCKInterface.Received().disableSKAdNetwork(true); + + } + + [Test] + public void disableSKAdNetwork_called_false() + { + + var AppsFlyerMOCKInterface = Substitute.For(); + + AppsFlyer.instance = AppsFlyerMOCKInterface; + AppsFlyer.disableSKAdNetwork(false); + AppsFlyerMOCKInterface.Received().disableSKAdNetwork(false); + + } + +#endif + } +} diff --git a/Assets/AppsFlyer/Tests/Tests_Suite.cs.meta b/Assets/AppsFlyer/Tests/Tests_Suite.cs.meta new file mode 100644 index 0000000..c20a62c --- /dev/null +++ b/Assets/AppsFlyer/Tests/Tests_Suite.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b1a24aa01166451d804d7c03c14a3db +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Windows.meta b/Assets/AppsFlyer/Windows.meta new file mode 100644 index 0000000..859b3f2 --- /dev/null +++ b/Assets/AppsFlyer/Windows.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1fbfcb6aeaa7f40e69a0daff450a2450 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb b/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb new file mode 100644 index 0000000..1bea160 Binary files /dev/null and b/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb differ diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb.meta b/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb.meta new file mode 100644 index 0000000..fd461dc --- /dev/null +++ b/Assets/AppsFlyer/Windows/AppsFlyerLib.pdb.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d0748deab2f031f42b801afab0837a59 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.pri b/Assets/AppsFlyer/Windows/AppsFlyerLib.pri new file mode 100644 index 0000000..f3993be Binary files /dev/null and b/Assets/AppsFlyer/Windows/AppsFlyerLib.pri differ diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.pri.meta b/Assets/AppsFlyer/Windows/AppsFlyerLib.pri.meta new file mode 100644 index 0000000..ed4fbf8 --- /dev/null +++ b/Assets/AppsFlyer/Windows/AppsFlyerLib.pri.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c621896ec81267f478e98555031271ef +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd b/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd new file mode 100644 index 0000000..381ce32 Binary files /dev/null and b/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd differ diff --git a/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd.meta b/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd.meta new file mode 100644 index 0000000..728454c --- /dev/null +++ b/Assets/AppsFlyer/Windows/AppsFlyerLib.winmd.meta @@ -0,0 +1,38 @@ +fileFormatVersion: 2 +guid: 5186898c6f4665f438e46763d4cff3ae +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + XboxOne: XboxOne + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs b/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs new file mode 100644 index 0000000..a44fea4 --- /dev/null +++ b/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs @@ -0,0 +1,145 @@ +//#define AFSDK_WIN_DEBUG +//#define UNITY_WSA_10_0 +//#define ENABLE_WINMD_SUPPORT + +#if UNITY_WSA_10_0 +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.ComponentModel; +using UnityEngine; +using System.Threading.Tasks; + +#if ENABLE_WINMD_SUPPORT +using AppsFlyerLib; +#endif + +namespace AppsFlyerSDK +{ + public class AppsFlyerWindows + { +#if ENABLE_WINMD_SUPPORT + static private MonoBehaviour _gameObject = null; +#endif + + public static void InitSDK(string devKey, string appId, MonoBehaviour gameObject) + { +#if ENABLE_WINMD_SUPPORT + +#if AFSDK_WIN_DEBUG + // Remove callstack + Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None); +#endif + Log("[InitSDK]: devKey: {0}, appId: {1}, gameObject: {2}", devKey, appId, gameObject == null ? "null" : gameObject.ToString()); + AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker(); + tracker.devKey = devKey; + tracker.appId = appId; + // Interface + _gameObject = gameObject; +#endif + } + + public static string GetAppsFlyerId() + { +#if ENABLE_WINMD_SUPPORT + Log("[GetAppsFlyerId]"); + return AppsFlyerTracker.GetAppsFlyerTracker().GetAppsFlyerUID(); +#else + return ""; +#endif + } + + public static void SetCustomerUserId(string customerUserId) + { +#if ENABLE_WINMD_SUPPORT + Log("[SetCustomerUserId] customerUserId: {0}", customerUserId); + if (customerUserId.Contains("test_device:")) + { + string testDeviceId = customerUserId.Substring(12); + AppsFlyerTracker.GetAppsFlyerTracker().testDeviceId = testDeviceId; + } + AppsFlyerTracker.GetAppsFlyerTracker().customerUserId = customerUserId; +#endif + } + + public static void Start() + { +#if ENABLE_WINMD_SUPPORT + Log("[Start]"); + AppsFlyerTracker.GetAppsFlyerTracker().TrackAppLaunchAsync(Callback); +#endif + } + +#if ENABLE_WINMD_SUPPORT + public static void Callback(AppsFlyerLib.ServerStatusCode code) + { + Log("[Callback]: {0}", code.ToString()); + + AppsFlyerRequestEventArgs eventArgs = new AppsFlyerRequestEventArgs((int)code, code.ToString()); + if (_gameObject != null) { + var method = _gameObject.GetType().GetMethod("AppsFlyerOnRequestResponse"); + if (method != null) { + method.Invoke(_gameObject, new object[] { AppsFlyerTracker.GetAppsFlyerTracker(), eventArgs }); + } + } + } +#endif + + public static void LogEvent(string eventName, Dictionary eventValues) + { +#if ENABLE_WINMD_SUPPORT + if (eventValues == null) + { + eventValues = new Dictionary(); + } + IDictionary result = new Dictionary(); + foreach (KeyValuePair kvp in eventValues) + { + result.Add(kvp.Key.ToString(), kvp.Value); + } + + Log("[LogEvent]: eventName: {0} result: {1}", eventName, result.ToString()); + + AppsFlyerTracker tracker = AppsFlyerTracker.GetAppsFlyerTracker(); + tracker.TrackEvent(eventName, result); + +#endif + } + + + public static void GetConversionData(string _reserved) + { +#if ENABLE_WINMD_SUPPORT + Task.Run(async () => + { + AppsFlyerLib.AppsFlyerTracker tracker = AppsFlyerLib.AppsFlyerTracker.GetAppsFlyerTracker(); + string conversionData = await tracker.GetConversionDataAsync(); + + IAppsFlyerConversionData conversionDataHandler = _gameObject as IAppsFlyerConversionData; + + if (conversionDataHandler != null) + { + Log("[GetConversionData] Will call `onConversionDataSuccess` with: {0}", conversionData); + conversionDataHandler.onConversionDataSuccess(conversionData); + } else { + Log("[GetConversionData] Object with `IAppsFlyerConversionData` interface not found! Check `InitSDK` implementation"); + } + // _gameObject.GetType().GetMethod("onConversionDataSuccess").Invoke(_gameObject, new[] { conversionData }); + }); +#endif + } + + private static void Log(string format, params string[] args) + { +#if AFSDK_WIN_DEBUG +#if ENABLE_WINMD_SUPPORT + Debug.Log("AF_UNITY_WSA_10_0" + String.Format(format, args)); +#endif +#endif + } + + } + +} +#endif diff --git a/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs.meta b/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs.meta new file mode 100644 index 0000000..66f10a1 --- /dev/null +++ b/Assets/AppsFlyer/Windows/AppsFlyerWindows.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 034d11e52b599954181d7f08c0d89ca8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/AppsFlyer/package.json b/Assets/AppsFlyer/package.json new file mode 100644 index 0000000..d335039 --- /dev/null +++ b/Assets/AppsFlyer/package.json @@ -0,0 +1,8 @@ +{ + "name": "appsflyer-unity-plugin", + "displayName": "AppsFlyer", + "description": "AppsFlyer Unity plugin", + "version": "6.14.3", + "unity": "2019.4", + "license": "MIT" + } diff --git a/Assets/AppsFlyer/package.json.meta b/Assets/AppsFlyer/package.json.meta new file mode 100644 index 0000000..e9b3d87 --- /dev/null +++ b/Assets/AppsFlyer/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a2b3ab5da7dda473b8791503604647b4 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Configs.meta b/Assets/Configs.meta new file mode 100644 index 0000000..50ae46a --- /dev/null +++ b/Assets/Configs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c1a09420c1d944149b93170add8b91e4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Configs/public_conf_1732532495.json b/Assets/Configs/public_conf_1732532495.json new file mode 100644 index 0000000..aab8838 --- /dev/null +++ b/Assets/Configs/public_conf_1732532495.json @@ -0,0 +1 @@ +{"GameUrlsConst":{"webMarginTopDownLeftRight":[0,0,0,0],"webMaxCTByToday":99999,"webOrder_X":2,"webAutoResetCD":[20,20]},"LangueConfig(BaseLangue)":[],"TextLanguage":[{"key":"pmf3wbjif1i4d-n5_f1i4","mz":"title","es":"Atrás","fr":"Dos","@in":"Kembali","id":1,"en":"Back","ru":"Назад","pt":"Voltar"},{"@in":"Hall","id":2,"mz":"n3","en":"Hall","fr":"Hall","pt":"Hall","key":"pmf3wbjif1i43-n3_f1i4","ru":"Hall","es":"Hall"},{"en":"Main","ru":"Main","es":"Main","fr":"Main","pt":"Main","id":3,"key":"pmf3wbjif1i42-n2_f1i4","mz":"n2","@in":"Main"},{"id":4,"mz":"n4","en":"CheckList","@in":"CheckList","key":"pmf3wbjif1i44-n4_f1i4","ru":"CheckList","es":"CheckList","fr":"CheckList","pt":"CheckList"},{"key":"pmf3wbjifd7ska-n11_fd7s","en":"Yes","ru":"Да","fr":"Oui","pt":"Sim","@in":"Ya","id":5,"mz":"title","es":"Sí"},{"key":"pmf3wbjifd7so-n11_fd7s","mz":"title","ru":"Да","@in":"Ya","id":6,"en":"Yes","es":"Sí","fr":"Oui","pt":"Sim"},{"en":"Yes","pt":"Sim","@in":"Ya","id":7,"key":"pmf3wbjifd7sp-n13_fd7s","es":"Sí","fr":"Oui","mz":"title","ru":"Да"},{"es":"Sí","fr":"Oui","pt":"Sim","id":8,"en":"Yes","ru":"Да","key":"pmf3wbjifd7sn-n15_fd7s","mz":"title","@in":"Ya"},{"id":9,"mz":"n7","en":"Get cash quickly by playing in hall","ru":"Быстро получайте деньги, играя в зале","pt":"Obtenha dinheiro rapidamente jogando no salão","@in":"Dapatkan uang tunai dengan cepat dengan bermain di Hall","key":"pmf3wbjiqvoqkt-n7_qvoq","es":"Obtenga efectivo rápidamente jugando en Hall","fr":"Obtenez de l'argent rapidement en jouant dans le hall"},{"key":"pmf3wbjisv84j-n19_sg71","en":"Google is not a sponsor nor is involved in any way with these contests and sweepstakes.","fr":"Google n'est pas un sponsor et n'est pas impliqué dans en aucun cas avec ces concours et ces concours.","@in":"Google bukan sponsor atau terlibat dengan cara apa pun dengan kontes dan undian ini.","id":10,"mz":"n19","ru":"Google не является спонсором и никаким образом не участвует в этих конкурсах и лотереях.","es":"Google no es patrocinador ni está involucrado de ninguna manera con estos concursos y sorteo.","pt":"O Google não é patrocinador nem está envolvido de forma alguma com esses concursos e sorteios."},{"ru":"политика конфиденциальности","fr":"politique de confidentialité","@in":"Kebijakan pribadi","key":"pmf3wbjisv84j-n20_sg71","mz":"text_privacy","es":"política de privacidad","pt":"política de Privacidade","id":11,"en":"Privacy Policy"},{"fr":"Collectez {left=$20.00} de plus pour encaisser","pt":"Colete {left=$20.00} mais para sacar","id":12,"mz":"text_more","en":"Collect {left=$20.00} more to cash out","es":"Cobrar {left=$20.00} más para cobrar","key":"pmf3wbjikj3hkj-n14_fbkw","ru":"Соберите еще {left=$20} чтобы обналичить их.","@in":"Kumpulkan {left=$20.00} Lebih banyak uang tunai"},{"es":"Cancelar","pt":"Cancelar","@in":"Membatalkan","id":13,"mz":"btn_cancel","en":"Cancel","ru":"Отмена","key":"2cbookqicy0io-n2_iwg9","fr":"Annuler"},{"key":"2cbookqicy0io-n3_iwg9","mz":"btn_update","es":"Actualizar","@in":"Memperbarui","id":14,"en":"Update","ru":"Обновлять","fr":"Mise à jour","pt":"Atualizar"},{"mz":"n25","ru":"ОБНОВЛЯТЬ","fr":"MISE À JOUR","es":"ACTUALIZAR","pt":"ATUALIZAR","@in":"MEMPERBARUI","id":15,"key":"2cbookqicy0ir-n25_scox","en":"UPDATE"},{"fr":"CONNEXION","@in":"GABUNG","id":16,"key":"2cbookqicy0is-n7_kmcp","en":"LOGIN","ru":"АВТОРИЗОВАТЬСЯ","mz":"n7","es":"ACCESO","pt":"CONECTE-SE"},{"en":"Network connection fail.\nPlease try again.","fr":"La connexion réseau échoue.\nVeuillez réessayer.","pt":"Falha na conexão da rede.\nPor favor, tente novamente.","@in":"Koneksi jaringan gagal.\nTolong coba lagi.","id":17,"key":"2cbookqip0hkn-n1_kqtu","es":"FALLO DE CONEXIÓN DE LA NETA.\nInténtalo de nuevo.","mz":"n1","ru":"Ошибка подключения к сети.\nПожалуйста, попробуйте еще раз."},{"pt":"Erro de rede","mz":"n2","fr":"Erreur de réseau","en":"Network Error","ru":"Ошибка сети","es":"Error de red","@in":"Kesalahan jaringan","id":18,"key":"2cbookqip0hkn-n2_kqtu"},{"ru":"ХОРОШО","es":"DE ACUERDO","fr":"D'ACCORD","id":19,"mz":"btn_ok","en":"OK","pt":"OK","@in":"OKE","key":"2cbookqip0hkn-n5_kqtu"},{"id":20,"mz":"n29","en":"CONNECT ERROR","es":"Error de conexión","key":"2cbookqicy0it-n29_scox","ru":"ОШИБКА ПОДКЛЮЧЕНИЯ","fr":"Connecter l'erreur","pt":"Erro de conexão","@in":"Hubungkan kesalahan"},{"es":"¡Conecte el problema ocurre!","fr":"Connecter le problème se produit!","pt":"Conectar o problema!","@in":"Hubungkan masalah terjadi!","en":"Connect Problem occur!","ru":"Подключить Возникла проблема!","mz":"text_reconnectStatus","id":21,"key":"2cbookqicy0it-n22_b72q"},{"@in":"Status: init","key":"2cbookqicy0it-n24_b72q","mz":"text_status","ru":"Статус: инициализация","fr":"Statut: init","id":22,"en":"Status : Init","es":"Estado: init","pt":"Status: init"},{"id":23,"fr":"RRRRRR","pt":"RRRRRR","@in":"RRRRRR","key":"2cbookqixeq4i-n58_rcj0","mz":"text_code","en":"RRRRRR","ru":"РРРРРР","es":"RRRRRR"},{"ru":"Google не является спонсором и никаким образом не участвует в этих конкурсах и лотереях.","pt":"O Google não é patrocinador nem está envolvido de forma alguma com esses concursos e sorteios.","id":24,"key":"pc0wa25bs9b7j-n19_sg71","mz":"n19","en":"Google is not a sponsor nor is involved in any way with these contests and sweepstakes.","es":"Google no es patrocinador ni está involucrado de ninguna manera con estos concursos y sorteo.","fr":"Google n'est pas un sponsor et n'est pas impliqué dans en aucun cas avec ces concours et ces concours.","@in":"Google bukan sponsor atau terlibat dengan cara apa pun dengan kontes dan undian ini."},{"mz":"text_privacy","ru":"политика конфиденциальности","es":"política de privacidad","@in":"Kebijakan pribadi","pt":"política de Privacidade","id":25,"key":"pc0wa25bs9b7j-n20_sg71","en":"Privacy Policy","fr":"politique de confidentialité"},{"fr":"En acceptant la politique de confidentialité, nous pouvons vous fournir des services de jeu. Confirmer l'accord?","pt":"Ao concordar com a Política de Privacidade, podemos fornecer serviços de jogo. Confirmar o contrato?","key":"pc0wa25bsg71i-n2_sg71","mz":"n2","ru":"Соглашаясь с Политикой конфиденциальности, мы можем предоставлять вам игровые услуги. Подтвердить соглашение?","es":"Al aceptar la Política de privacidad, podemos proporcionarle servicios de juego. Confirmar el acuerdo?","@in":"Dengan menyetujui kebijakan privasi, kami dapat memberi Anda layanan game. Konfirmasikan perjanjian?","id":26,"en":"By agreeing to the Privacy Policy, we can provide you with game services. Confirm the agreement?"},{"id":27,"ru":"Войти в игру?","fr":"Entrez dans le jeu?","key":"pc0wa25bsg71i-n3_sg71","mz":"n3","en":"Enter the game?","es":"Ingresar al juego?","pt":"Entrar no jogo?","@in":"Masukkan game?"},{"fr":"Entrer dans le jeu","pt":"Entrar no jogo","id":28,"key":"pc0wa25bsg71i-n5_jfbe","mz":"btn_yes","@in":"Masukkan game","en":"Enter Game","ru":"Войти в игру","es":"Entrar en juego"},{"key":"pc0wa25bt268a-n16_i2uj","en":"IsTestSever","fr":"IsTestSever","es":"IsTestSever","pt":"IsTestSever","@in":"IsTestSever","id":29,"mz":"text_severStatus","ru":"Истестсевер"},{"key":"pc0wa25bt268a-n21_fd7s","mz":"text_loadquiz","es":"Loading questions: {per=18%}","fr":"Loading questions: {per=18%}","@in":"Loading questions: {per=18%}","id":30,"ru":"Загрузка вопросов: {per=18%}","pt":"Loading questions: {per=18%}","en":"Loading questions: {per=18%}"},{"en":"Play","ru":"Играть","es":"Jugar","fr":"Jouer","id":31,"key":"bw2zghfmfd7s0-n9_fbkw","mz":"btn_login","pt":"Jogar","@in":"Bermain"},{"mz":"text_name","ru":"Илон Маск Босс","es":"Elon Musk Boss","fr":"Elon Musk Boss","id":32,"key":"b55ys1yyrezmd-n8_rezm","en":"Elon Musk Bossssssssss","pt":"Elon Musk Boss","@in":"Elon Musk Boss"},{"ru":"[color=#8A4B00,#660000]{title=Geography}[/color]","es":"[color=#8A4B00,#660000]{title=Geography}[/color]","fr":"[color=#8A4B00,#660000]{title=Geography}[/color]","pt":"[color=#8A4B00,#660000]{title=Geography}[/color]","id":33,"key":"b55ys1yyf1i47-n9_f1i4","mz":"text_name","en":"[color=#FFFFFF,#CEFFAD]{title=Geography}[/color]","@in":"[color=#8A4B00,#660000]{title=Geography}[/color]"},{"pt":"[color=#8A4B00,#660000]{title=Geography}[/color]","key":"b55ys1yyf1i47-n9_f1i4-texts_0","mz":"text_name","en":"[color=#FFFFFF,#FFFF6B7]{title=Geography}[/color]","ru":"[color=#8A4B00,#660000]{title=Geography}[/color]","es":"[color=#8A4B00,#660000]{title=Geography}[/color]","fr":"[color=#8A4B00,#660000]{title=Geography}[/color]","id":34,"@in":"[color=#8A4B00,#660000]{title=Geography}[/color]"},{"@in":"[color=#008376,#005432]{title=Geography}[/color]","pt":"[color=#008376,#005432]{title=Geography}[/color]","id":35,"key":"b55ys1yyf1i47-n9_f1i4-texts_1","mz":"text_name","en":"[color=#FFFFFF,#FFC59F]{title=Geography}[/color]","ru":"[color=#008376,#005432]{title=Geography}[/color]","es":"[color=#008376,#005432]{title=Geography}[/color]","fr":"[color=#008376,#005432]{title=Geography}[/color]"},{"pt":"[color=#A300B9,#660099]{title=Geography}[/color]","mz":"text_name","es":"[color=#A300B9,#660099]{title=Geography}[/color]","fr":"[color=#A300B9,#660099]{title=Geography}[/color]","ru":"[color=#A300B9,#660099]{title=Geography}[/color]","@in":"[color=#A300B9,#660099]{title=Geography}[/color]","id":36,"key":"b55ys1yyf1i47-n9_f1i4-texts_2","en":"[color=#FFFFFF,#CEFFAD]{title=Geography}[/color]"},{"mz":"text_quiz","ru":"Пройдите тест и заработайте до {cash=$30.00}","pt":"Passe no teste para ganhar até {dinheiro=$30,00}","id":37,"en":"Pass the quiz to earn up to {cash=$30.00}","es":"Passe no teste para ganhar até {dinheiro=$30,00}","fr":"Réussissez le quiz pour gagner jusqu'à {cash=$30.00}","@in":"Lulus kuis untuk mendapatkan hingga {cash=$30.00}","key":"b55ys1yyf1i47-n10_f1i4"},{"es":"Atualizar categoria","fr":"Actualiser la catégorie","@in":"Segarkan Kategori","mz":"text_name","en":"Refresh Category","ru":"Обновить категорию","pt":"Atualizar categoria","id":38,"key":"b55ys1yyf1i4b-n12_f1i4"},{"key":"b55ys1yyf1i46-n5_f1i4","ru":"Соберите еще {left=$20,00}, чтобы обналичить их.","fr":"Collectez {left=$20.00} de plus pour encaisser","pt":"Colete {left=$20,00} a mais para sacar","id":39,"mz":"text_more","en":"Collect {left=$20.00} more to cash out","es":"Colete {left=$20,00} a mais para sacar","@in":"Kumpulkan {left=$20.00} lebih banyak untuk diuangkan"},{"mz":"btn_out","en":"Cash out","pt":"Sacar","@in":"kas keluar","id":40,"key":"b55ys1yyf1i46-n6_f1i4","fr":"encaisser","ru":"обналичить","es":"sacar"},{"key":"b55ys1yyf1i46-n9_oee9","mz":"t12","ru":"МОЙ БАЛАНС","es":"MEU SALDO","pt":"MEU SALDO","id":41,"en":"MY BALANCE","fr":"MON SOLDE","@in":"SALDO SAYA"},{"fr":"Mon portefeuille","id":42,"key":"b55ys1yyfd7s0-n13_ootm","mz":"text_wallet","en":"My Wallet","es":"Minha carteira","ru":"Мой бумажник","pt":"Minha carteira","@in":"Dompetku"},{"pt":"Quiz Desafio","id":43,"key":"b55ys1yyfd7s0-n14_ootm","mz":"n14","es":"Quiz Desafio","fr":"Défi Quiz","en":"Quiz Challenge","ru":"Викторина Вызов","@in":"Tantangan Kuis"},{"ru":"Вызов сейчас!","es":"Desafie agora!","pt":"Desafie agora!","@in":"Tantang Sekarang!","key":"b55ys1yyfd7s0-n16_rsuk","mz":"btn_playnow","en":"Challenge Now!","id":44,"fr":"Défiez maintenant !"},{"key":"b55ys1yyf1i4c-n1_f1i4","es":"Iniciando {name=Logo} Questionário","fr":"Démarrage du quiz {name=Logo}","pt":"Iniciando {name=Logo} Questionário","id":45,"mz":"text_name","en":"Starting {name=Logo} Quiz","ru":"Запуск викторины {name=Logo}","@in":"Memulai Kuis {name=Logo}"},{"en":"You must pass all questions in order to receive cash reward.","ru":"Вы должны пройти все вопросы, чтобы получить денежное вознаграждение.","@in":"Anda harus melewati semua pertanyaan untuk menerima hadiah uang tunai.","id":46,"mz":"t1","fr":"Vous devez réussir toutes les questions afin de recevoir une récompense en espèces.","pt":"Você deve passar em todas as perguntas para receber a recompensa em dinheiro.","key":"b55ys1yyf1i4c-n3_f1i4","es":"Você deve passar em todas as perguntas para receber a recompensa em dinheiro."},{"es":"começar","fr":"commencer","pt":"Começar","@in":"awal","mz":"btn_start","en":"Start","ru":"начинать","id":47,"key":"b55ys1yyf1i4c-n4_f1i4"},{"fr":"Répondre","mz":"text_ans","ru":"отвечать","es":"Responder","pt":"Responder","@in":"Menjawab","id":48,"key":"bmphtric902wc-n15_902w","en":"Answer"},{"key":"bmphtricrsukm-n15_902w","ru":"отвечать","fr":"Répondre","@in":"Menjawab","pt":"Responder","id":49,"mz":"text_ans","en":"Answer","es":"Responder"},{"ru":"Соберите еще {left=$20,00}, чтобы обналичить их.","es":"Recoja {left=$20.00} más para cobrar","fr":"Collectez {left=$20.00} de plus pour encaisser","@in":"Kumpulkan {left=$20.00} lebih banyak untuk diuangkan","key":"bmphtrickj3hf-n14_fbkw","mz":"text_more","pt":"Colete {left=$20,00} a mais para sacar","id":50,"en":"Collect {left=$20.00} more to cash out"},{"en":"What was the first product launched by apple?","ru":"Какой первый продукт выпустила компания Apple?","fr":"Quel a été le premier produit lancé par Apple ?","pt":"Qual foi o primeiro produto lançado pela apple?","@in":"Apa produk pertama yang diluncurkan oleh apple?","id":51,"key":"bmphtric902wd-n12_902w","mz":"text_txt","es":"¿Cuál fue el primer producto lanzado por Apple?"},{"key":"bmphtricfd7s0-n6_f1i4","mz":"text_question","@in":"Pertanyaan: {cur=1}/{tol=10}","id":52,"ru":"Вопрос: {cur=1}/{tol=10}","es":"Pregunta: {cur=1}/{tol=10}","fr":"Question : {cur=1}/{tol=10}","pt":"Pergunta: {cur=1}/{tol=10}","en":"Question: {cur=1}/{tol=10}"},{"key":"bmphtric902we-n1_902w","mz":"title","fr":"Échec du défi","pt":"Falha no desafio","id":53,"ru":"Вызов провален","es":"Desafío fallido","@in":"Tantangan Gagal","en":"Challenge Fail"},{"id":54,"ru":"Выйти из игры","fr":"Quitter le jeu","key":"bmphtric902we-n1_902w-texts_0","mz":"title","en":"Exit Game","es":"salir del juego","pt":"Sair do jogo","@in":"Keluar permainan"},{"en":"Challenge Fail","es":"Desafío fallido","fr":"Échec du défi","@in":"Tantangan Gagal","key":"bmphtric902we-n1_902w-texts_def","mz":"title","ru":"Вызов провален","pt":"Falha no Desafio","id":55},{"key":"bmphtric902we-n2_902w","mz":"t2","en":"You will lose your cash reward if you quit now","fr":"Vous perdrez votre récompense en espèces si vous arrêtez maintenant","@in":"Anda akan kehilangan hadiah uang tunai jika Anda berhenti sekarang","id":56,"es":"Perderá su recompensa en efectivo si renuncia ahora","pt":"Você perderá sua recompensa em dinheiro se sair agora","ru":"Вы потеряете свое денежное вознаграждение, если выйдете сейчас"},{"id":57,"en":"You will lose your cash reward if you quit now","ru":"Вы потеряете свое денежное вознаграждение, если выйдете сейчас","fr":"Vous perdrez votre récompense en espèces si vous arrêtez maintenant","pt":"Você perderá sua recompensa em dinheiro se sair agora","key":"bmphtric902we-n2_902w-texts_0","mz":"t2","es":"Perderá su recompensa en efectivo si renuncia ahora","@in":"Anda akan kehilangan hadiah uang tunai jika Anda berhenti sekarang"},{"es":"Perderá su recompensa en efectivo si renuncia ahora","key":"bmphtric902we-n2_902w-texts_1","mz":"t2","en":"You will lose your cash reward if you quit now","ru":"Вы потеряете свое денежное вознаграждение, если выйдете сейчас","fr":"Vous perdrez votre récompense en espèces si vous arrêtez maintenant","pt":"Você perderá sua recompensa em dinheiro se sair agora","@in":"Anda akan kehilangan hadiah uang tunai jika Anda berhenti sekarang","id":58},{"pt":"você ganhou","id":59,"mz":"t2","en":"You won","es":"ganaste","key":"bmphtric902we-n2_902w-texts_def","ru":"Ты победил","fr":"tu as gagné","@in":"kamu menang"},{"en":"Giveup Cash","es":"dar dinero en efectivo","ru":"Денежные средства","fr":"Abandonner de l'argent","pt":"Dinheiro de Devolução","@in":"Penyerahan Uang Tunai","id":60,"key":"bmphtric902we-n5_902w","mz":"btn_close"},{"id":61,"key":"bmphtric902we-n6_902w","pt":"continuar","@in":"melanjutkan","mz":"btn_continueAd","en":"Continue","ru":"продолжать","es":"continúa","fr":"continuer"},{"key":"bmphtric902we-n7_902w","mz":"btn_continue","pt":"continuar","@in":"melanjutkan","id":62,"ru":"продолжать","es":"continúa","fr":"continuer","en":"Continue"},{"es":"Desafío fallido","fr":"Échec du défi","id":63,"mz":"text_congrat","ru":"Вызов провален","pt":"Falha no Desafio","@in":"Tantangan Gagal","key":"bmphtric902we-n9_902w","en":"Challenge Fail"},{"en":"Exit Game","es":"salir del juego","id":64,"key":"bmphtric902we-n9_902w-texts_0","fr":"Quitter le jeu","pt":"Sair do jogo","@in":"Keluar permainan","mz":"text_congrat","ru":"Выйти из игры"},{"ru":"Поздравляем, {name=Jasper}!","es":"¡Felicidades, {nombre=Jasper}!","fr":"Félicitations, {name=Jasper} !","pt":"Parabéns, {name=Jasper}!","@in":"Selamat, {name=Jasper}!","en":"Congratulations, {name=Jasper}!","key":"bmphtric902we-n9_902w-texts_1","mz":"text_congrat","id":65},{"mz":"text_congrat","en":"Challenge Fail","fr":"Échec du défi","pt":"Falha no desafio","id":66,"key":"bmphtric902we-n9_902w-texts_def","ru":"Вызов провален","es":"Desafío fallido","@in":"Tantangan Gagal"},{"en":"x3 Reward: $18.88","mz":"btn_multi","key":"bmphtric902we-n10_fbkw","ru":"x3Награды: $18,88","es":"Recompensa x3: $18.88","fr":"x3Récompenses : 18,88 $","pt":"Recompensas x3: $ 18,88","@in":"x3Hadiah: $18,88","id":67},{"id":68,"mz":"btn_collect","es":"recolectar","fr":"collecter","pt":"coletar","key":"bmphtric902we-n13_fbkw","en":"Collect","ru":"собирать","@in":"mengumpulkan"},{"fr":"PRÊT!","id":69,"en":"READY!","ru":"ГОТОВЫЙ!","es":"¡LISTO!","pt":"PREPARAR!","@in":"SIAP!","key":"bfkmhq3qym5rg-n6_ttt6","mz":"n6"},{"mz":"text_type","es":"News","@in":"News","id":70,"en":"News","ru":"Новости","fr":"News","pt":"News","key":"bfkmhq3qfbkwd-n4_fbkw"},{"key":"bfkmhq3qfbkwd-n4_fbkw-texts_0","en":"Games","pt":"Games","@in":"Games","id":71,"mz":"text_type","ru":"Игры","es":"Games","fr":"Games"},{"mz":"text_type","en":"Hot","ru":"Горячий","es":"Hot","fr":"Hot","pt":"Hot","@in":"Hot","id":72,"key":"bfkmhq3qfbkwd-n4_fbkw-texts_1"},{"@in":"News","ru":"Новости","es":"News","pt":"News","en":"News","fr":"News","id":73,"key":"bfkmhq3qfbkwd-n4_fbkw-texts_def","mz":"text_type"},{"en":"Invite Friends","ru":"Пригласить друзей","es":"Invitar a amigos","@in":"Mengundang teman-teman","id":74,"key":"xv1nzk1ir4u4c-n14_r4u4","mz":"n14","fr":"Inviter des amis","pt":"Convide amigos"},{"ru":"Получите {coin=10000} за каждого приглашенного!","id":75,"mz":"text_inviteShow","en":"Receive {coin=10000} for each invitee!","es":"¡Recibe {coin=10000} por cada invitado!","fr":"Recevoir {coin=10000} pour chaque invité!","pt":"Receba {coin=10000} para cada convitee!","@in":"Terima {coin=10000} untuk setiap undangan!","key":"xv1nzk1ir4u4c-n15_r4u4"},{"pt":"Check-in diário","key":"xv1nzk1ir4u4d-n16_r4u4","mz":"n16","ru":"Ежедневная регистрация","es":"Check-in diario","fr":"Enregistrement quotidien","@in":"Check-in harian","id":76,"en":"Daily Check-in"},{"key":"xv1nzk1ir4u4d-n17_r4u4","es":"Compruebe todos los días para ganar {coin=100000}","ru":"Заходите каждый день, чтобы заработать {coin=100000}","fr":"Enregistrez tous les jours pour gagner {coin=100000}","pt":"Verifique todos os dias para ganhar {coin=100000}","@in":"Check -in setiap hari untuk mendapatkan {coin=100000}","id":77,"mz":"text_signShow","en":"Check in everyday to earn {coin=100000}"},{"fr":"Tâches vidéo","key":"xv1nzk1is1dll-n17_s1dl","es":"Tareas de video","en":"Video Tasks","ru":"Видео Задания","pt":"Tarefas de vídeo","@in":"Tugas video","id":78,"mz":"n17"},{"ru":"Получайте больше денег за каждое видео!","es":"¡Reciba más efectivo para cada video!","pt":"Receba mais dinheiro para cada vídeo!","@in":"Terima lebih banyak uang untuk setiap video!","id":79,"key":"xv1nzk1is1dll-n18_s1dl","mz":"text_vidShow","en":"Receive more cash for each video!","fr":"Recevez plus d'argent pour chaque vidéo!"},{"id":80,"mz":"text_read","en":"[color=#FFCC00]{cur=12}/{tol=50}[/color] correct answers","ru":"[color=#FF9900]{cur=12}/{tol=50}[/color] правильные ответы","es":"[color=#FF9900]{cur=12}/{tol=50}[/color] correct answers","pt":"[color=#FF9900]{cur=12}/{tol=50}[/color] correct answers","key":"xv1nzk1ik9wjo-n27_k9wj","fr":"[color=#FF9900]{cur=12}/{tol=50}[/color] correct answers","@in":"[color=#FF9900]{cur=12}/{tol=50}[/color] correct answers"},{"id":81,"ru":"Ежедневные задачи","fr":"Tâches quotidiennes","pt":"TO-DOS diário","@in":"To-dos setiap hari","key":"xv1nzk1io6ge0-n35_k9wj","mz":"n35","en":"Daily To-Dos","es":"Tareas diarias"},{"es":"Logro","pt":"Conquista","mz":"n36","en":"Achievement","ru":"Достижение","fr":"Réalisation","@in":"Pencapaian","id":82,"key":"xv1nzk1io6ge0-n36_k9wj"},{"mz":"text_lang","en":"English","es":"Inglés","id":83,"key":"mqs6max7rezm1e-n4_rkol","ru":"Английский","fr":"Anglais","pt":"Inglês","@in":"Bahasa inggris"},{"mz":"n5","en":"Off","ru":"Off","es":"Off","pt":"Off","@in":"Off","id":84,"key":"mqs6max7rezm1f-n5_m2gl","fr":"Off"},{"en":"On","fr":"On","pt":"On","@in":"On","id":85,"key":"mqs6max7rezm1f-n6_m2gl","mz":"n6","ru":"On","es":"On"},{"id":86,"key":"mqs6max7rezm1g-n4_csgq","mz":"t1","en":"Withdraw Record","pt":"Contate-nos","@in":"Hubungi kami","ru":"Связаться с нами","es":"Contáctenos","fr":"Contactez-nous"},{"es":"Récord de retiro","id":87,"key":"mqs6max7rezm1g-n4_csgq-texts_0","ru":"Вывести запись","fr":"Retirer le dossier","pt":"Retirar registro","@in":"Tarik catatan","mz":"t1","en":"Withdraw Record"},{"id":88,"key":"mqs6max7rezm1g-n4_csgq-texts_1","mz":"t1","pt":"política de Privacidade","@in":"Kebijakan pribadi","en":"Privacy Policy","ru":"политика конфиденциальности","es":"política de privacidad","fr":"politique de confidentialité"},{"id":89,"en":"User Agreement","fr":"Accord de l'utilisateur","key":"mqs6max7rezm1g-n4_csgq-texts_2","mz":"t1","ru":"Пользовательское Соглашение","es":"Acuerdo del Usuario","pt":"Termo de Acordo do Usuário","@in":"Perjanjian Pengguna"},{"@in":"Hubungi kami","key":"mqs6max7rezm1g-n4_csgq-texts_3","en":"Contact Us","es":"Contáctenos","fr":"Contactez-nous","pt":"Contate-nos","id":90,"mz":"t1","ru":"Связаться с нами"},{"pt":"línguas","fr":"Langues","@in":"Bahasa","id":91,"key":"mqs6max7rezm1g-n4_csgq-texts_def","mz":"t1","en":"Languages","ru":"Языки","es":"Lenguas"},{"key":"mqs6max7si1f0-n7_nvmp","fr":"Modifier mon avatar et nom d'utilisateur","pt":"Edite meu avatar e nome de usuário","@in":"Edit avatar & nama pengguna saya","id":92,"mz":"t2","en":"Edit my avatar & username","ru":"Изменить мой аватар и имя пользователя","es":"Editar mi avatar y nombre de usuario"},{"fr":"MyUsername","pt":"MyUsername","@in":"MyUsername","key":"mqs6max7si1f0-n12_nvmp","mz":"textp_name","en":"MyUsername","ru":"Мое имя пользователя","id":93,"es":"MyUsername"},{"@in":"Memperbarui","mz":"btn_ok","ru":"Обновлять","fr":"Mise à jour","es":"Actualizar","pt":"Atualizar","id":94,"key":"mqs6max7si1f0-n15_nvmp","en":"Update"},{"id":95,"es":"Lenguas","fr":"Langues","pt":"línguas","@in":"Bahasa","key":"mqs6max7rkol0-n1_rkol","mz":"t1","en":"Languages","ru":"Языки"},{"key":"mqs6max7u6tn12-n1_rezm","mz":"title","es":"Menú","pt":"Cardápio","id":96,"en":"Menu","ru":"Меню","fr":"Menu","@in":"Menu"},{"@in":"UID:{UID=1234567}","id":97,"mz":"text_uid","es":"UID:{UID=1234567}","fr":"UID:{UID=1234567}","key":"mqs6max7u6tn12-n10_kj3h","en":"UID:{UID=1234567}","ru":"UID:{UID=1234567}","pt":"UID:{UID=1234567}"},{"key":"mqs6max7u6tn12-n11_kj3h","mz":"text_version","fr":"Version:{Ver=1.0.1_v2}","pt":"Version:{Ver=1.0.1_v2}","id":98,"en":"Version:{Ver=1.0.1_v2}","ru":"Version:{Ver=1.0.1_v2}","es":"Version:{Ver=1.0.1_v2}","@in":"Version:{Ver=1.0.1_v2}"},{"id":99,"key":"md8tkwlzw3axb-n2_w3ax","mz":"title","en":"Later","@in":"Nanti","ru":"Позже","es":"Más tarde","fr":"Plus tard","pt":"Mais tarde"},{"key":"md8tkwlzdeiw1s-n11_deiw","en":"Edit","pt":"Editar","@in":"Edit","id":100,"mz":"text_title","ru":"Редактировать","es":"Editar","fr":"Modifier"},{"key":"md8tkwlzc0is1u-n48_c0is","mz":"n48","pt":"Vá para o resumo","@in":"Pergi ke ringkasan","id":101,"en":"Go to Summary","ru":"Перейти к сводке","es":"Ir al resumen","fr":"Aller en résumé"},{"es":"From","fr":"From","pt":"From","@in":"From","id":102,"key":"md8tkwlzmeh8c-n11_s0jg","mz":"text_payer","en":"From","ru":"От"},{"pt":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","@in":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","key":"md8tkwlzmeh8c-n13_s0jg","es":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","en":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","ru":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","fr":"Process in query [color=#3366FF]{cur=1000}/{tol=8000}[/color]","id":103,"mz":"text_name"},{"mz":"enter_email","ru":"[color=#BABBBB]E-mail Address[/color]","@in":"[color=#BABBBB]E-mail Address[/color]","pt":"[color=#BABBBB]E-mail Address[/color]","id":104,"key":"md8tkwlzdeiw1k-n33_deiw-prompt","en":"[color=#BABBBB]E-mail Address[/color]","es":"[color=#BABBBB]E-mail Address[/color]","fr":"[color=#BABBBB]E-mail Address[/color]"},{"es":"[color=#BABBBB]Phone Number[/color]","fr":"[color=#BABBBB]Phone Number[/color]","@in":"[color=#BABBBB]Phone Number[/color]","mz":"enter_phone","en":"[color=#BABBBB]Phone Number[/color]","ru":"[color=#BABBBB]Phone Number[/color]","pt":"[color=#BABBBB]Phone Number[/color]","id":105,"key":"md8tkwlzdeiw1k-n35_deiw-prompt"},{"mz":"enter_fname","fr":"[color=#BABBBB]First Name[/color]","en":"[color=#BABBBB]First Name[/color]","ru":"[color=#BABBBB]First Name[/color]","es":"[color=#BABBBB]First Name[/color]","pt":"[color=#BABBBB]First Name[/color]","@in":"[color=#BABBBB]First Name[/color]","id":106,"key":"md8tkwlzdeiw1j-n36_deiw-prompt"},{"id":107,"key":"md8tkwlzdeiw1i-n39_deiw-prompt","mz":"enter_lname","ru":"[color=#BABBBB]Last Name[/color]","es":"[color=#BABBBB]Last Name[/color]","pt":"[color=#BABBBB]Last Name[/color]","@in":"[color=#BABBBB]Last Name[/color]","en":"[color=#BABBBB]Last Name[/color]","fr":"[color=#BABBBB]Last Name[/color]"},{"ru":"Внимание:","fr":"Attention:","pt":"Attention:","key":"md8tkwlzdeiw1m-n42_deiw","en":"Attention:","es":"Attention:","@in":"Attention:","id":108,"mz":"n42"},{"id":109,"mz":"n43","ru":"Убедитесь, что вы правильно ввели данные своей учетной записи.\nПосле подтверждения вы не можете изменить всю информацию для своей учетной записи.","es":"Asegúrese de haber ingresado la información de su cuenta correctamente.\nDespués de haber confirmado, no puede cambiar toda la información para su cuenta.","pt":"Verifique se você inseriu as informações da sua conta corretamente.\nDepois de confirmar, você não pode alterar todas as informações da sua conta.","key":"md8tkwlzdeiw1m-n43_deiw","en":"Please make sure you have entered your account information correctly.\nAfter you have confirmed, you can not change all the information for your account.","fr":"Veuillez vous assurer que vous avez correctement saisi les informations de votre compte.\nAprès avoir confirmé, vous ne pouvez pas modifier toutes les informations de votre compte.","@in":"Pastikan Anda telah memasukkan informasi akun Anda dengan benar.\nSetelah Anda mengonfirmasi, Anda tidak dapat mengubah semua informasi untuk akun Anda."},{"pt":"Pedido feito. ID do pedido:","id":110,"en":"Order placed. Order ID:","ru":"Заказ размещен. Номер заказа:","fr":"Commande passée. Numéro de commande:","@in":"Pesanan ditempatkan. Id pemesanan:","key":"md8tkwlzes171x-n78_es17","mz":"n01","es":"Orden colocado. Solicitar ID:"},{"key":"md8tkwlzes171x-n83_es17","mz":"text_task_title","fr":"Regarder {ad=20} récompenses ADS:","@in":"Tonton {ad=20} Iklan Hadiah:","pt":"Assista {ad=20} Recompensa anúncios:","id":111,"en":"Watch {ad=20} Reward Ads:","ru":"Посмотрите {ad=20} рекламных объявлений:","es":"Ver {ad=20} anuncios de recompensa:"},{"pt":"Sacar o dinheiro","mz":"n03","es":"Cobrar el dinero","en":"Cash Out the Money","ru":"Обналичить деньги","fr":"Retirer l'argent","@in":"Uang uangnya","id":112,"key":"md8tkwlzes171x-n85_es17"},{"id":113,"mz":"text_payer","en":"{amt=$0.5} directly to your {payer=PayPal}","ru":"{amt=$5} напрямую на ваш {payer=PayPal}","pt":"{amt=$0.5} directly to your {payer=PayPal}","key":"md8tkwlzes171x-n86_es17","es":"{amt=$0.5} directly to your {payer=PayPal}","fr":"{amt=$0.5} directly to your {payer=PayPal}","@in":"{amt=$0.5} directly to your {payer=PayPal}"},{"id":114,"key":"md8tkwlzut66d-n8_jr4y","mz":"btn_tab","ru":"Заработайте больше токенов","fr":"Gagnez plus de jetons","pt":"Ganhe mais tokens","@in":"Hasilkan lebih banyak token","en":"Earn More Tokens","es":"Gana más fichas"},{"en":"Earn More Tokens","ru":"Заработайте больше токенов","fr":"Gagnez plus de jetons","id":115,"mz":"btn_tab","es":"Gana más fichas","pt":"Ganhe mais tokens","@in":"Hasilkan lebih banyak token","key":"md8tkwlzut66d-n8_jr4y-texts_0"},{"key":"md8tkwlzut66d-n8_jr4y-texts_1","mz":"btn_tab","en":"OK","ru":"ХОРОШО","fr":"D'ACCORD","id":116,"pt":"OK","@in":"OKE","es":"DE ACUERDO"},{"id":117,"pt":"confirme","@in":"Mengonfirmasi","key":"md8tkwlzut66d-n8_jr4y-texts_def","mz":"btn_tab","en":"Confirm","ru":"Подтверждать","es":"Confirmar","fr":"Confirmer"},{"key":"md8tkwlzut66d-n11_jr4y","mz":"text_payhint","en":"Please note that payment will take 3-5 days to deliver. You can check your payment status at withdrawals record page.","ru":"Обратите внимание, что оплата занимает 3-5 дней. Вы можете проверить статус платежа на странице записи о снятии средств.","es":"Tenga en cuenta que el pago tardará de 3 a 5 días en entregarse. Puede verificar su estado de pago en la página de registro de retiros.","pt":"Observe que o pagamento levará de 3 a 5 dias para entregar. Você pode verificar seu status de pagamento na página de registro dos saques.","@in":"Harap dicatat bahwa pembayaran akan memakan waktu 3-5 hari untuk dikirim. Anda dapat memeriksa status pembayaran Anda di halaman catatan penarikan.","id":118,"fr":"Veuillez noter que le paiement prendra 3 à 5 jours pour livrer. Vous pouvez vérifier votre état de paiement à la page d'enregistrement des retraits."},{"key":"md8tkwlzut66d-n11_jr4y-texts_0","mz":"text_payhint","en":"Processing the payment to\n {account=1234567@qq.com}","es":"Processing the payment to\n {account=1234567@qq.com}","fr":"Processing the payment to\n {account=1234567@qq.com}","pt":"Processing the payment to\n {account=1234567@qq.com}","id":119,"ru":"Обработка платежа на\n{account=1234567@qq.com}","@in":"Processing the payment to\n {account=1234567@qq.com}"},{"mz":"text_payhint","es":"Tenga en cuenta que el pago tardará de 3 a 5 días en entregarse. Puede verificar su estado de pago en la página de registro de retiros.","fr":"Veuillez noter que le paiement prendra 3 à 5 jours pour livrer. Vous pouvez vérifier votre état de paiement à la page d'enregistrement des retraits.","pt":"Observe que o pagamento levará de 3 a 5 dias para entregar. Você pode verificar seu status de pagamento na página de registro dos saques.","id":120,"key":"md8tkwlzut66d-n11_jr4y-texts_def","@in":"Harap dicatat bahwa pembayaran akan memakan waktu 3-5 hari untuk dikirim. Anda dapat memeriksa status pembayaran Anda di halaman catatan penarikan.","en":"Please note that payment will take 3-5 days to deliver. You can check your payment status at withdrawals record page.","ru":"Обратите внимание, что оплата занимает 3-5 дней. Вы можете проверить статус платежа на странице записи о снятии средств."},{"key":"md8tkwlzut66d-n12_mzwv","mz":"text_title","ru":"Войдите в свою учетную запись {payer=PayPal}","@in":"Enter your {payer=PayPal} Account","pt":"Enter your {payer=PayPal} Account","id":121,"en":"Enter your {payer=PayPal} Account","es":"Enter your {payer=PayPal} Account","fr":"Enter your {payer=PayPal} Account"},{"fr":"You can exchange cash to the following {payer=Paypal} account.","pt":"You can exchange cash to the following {payer=Paypal} account.","id":122,"es":"You can exchange cash to the following {payer=Paypal} account.","en":"You can exchange cash to the following {payer=Paypal} account.","ru":"Вы можете обменять наличные на следующий аккаунт {payer=Paypal}.","@in":"You can exchange cash to the following {payer=Paypal} account.","key":"md8tkwlzut66d-n29_v6mn","mz":"text_smaill_title"},{"fr":"Enregistrer les informations","@in":"Informasi uang tunai","id":123,"mz":"n49","ru":"Информация о выводе денег","es":"Información de retención","pt":"Dinheiro Informações","key":"md8tkwlzut66d-n49_c0is","en":"Cash out information"},{"id":124,"mz":"text_wallet","ru":"{Payer=PayPal}","pt":"{Payer=PayPal}","@in":"{Payer=PayPal}","key":"md8tkwlzut66d-n50_c2wf","en":"{Payer=PayPal}","es":"{Payer=PayPal}","fr":"{Payer=PayPal}"},{"mz":"n0","fr":"E-Wallet","pt":"E-Wallet","@in":"E-Wallet","id":125,"key":"md8tkwlzut66d-n56_c2wf","en":"E-Wallet","ru":"Электронный кошелек","es":"E-Wallet"},{"key":"md8tkwlzut66d-n57_c2wf","en":"Cash","ru":"наличные","es":"dinero","@in":"tunai","id":126,"mz":"n1","fr":"espèces","pt":"dinheiro"},{"fr":"Compte","id":127,"mz":"n00","ru":"Счет","es":"Cuenta","pt":"Conta","@in":"Akun","key":"md8tkwlzut66d-n60_c2wf","en":"Account"},{"ru":"Искупить","es":"Canjear","fr":"Racheter","id":128,"key":"md8tkwlzut66d-n64_c2wf","mz":"btn_earn","en":"Redeem","pt":"Resgatar","@in":"Menukarkan"},{"id":129,"ru":"Искупить","pt":"Resgatar","key":"md8tkwlzut66d-n64_c2wf-texts_0","mz":"btn_earn","en":"Redeem","es":"Canjear","fr":"Racheter","@in":"Menukarkan"},{"ru":"Полное состояние","es":"Condición completa","@in":"Kondisi lengkap","pt":"Condição completa","id":130,"key":"md8tkwlzut66d-n64_c2wf-texts_1","mz":"btn_earn","en":"Complete condition","fr":"État complet"},{"es":"Complete todas las condiciones para cobrar","fr":"Veuillez remplir toutes les conditions pour retirer","id":131,"key":"md8tkwlzut66d-n66_c2wf","mz":"n22","en":"Please complete all conditions to cash out","ru":"Пожалуйста, выполните все условия для вывода средств","pt":"Por favor, complete todas as condições para sacar","@in":"Harap selesaikan semua ketentuan untuk menguangkan"},{"fr":"Règles d'échange:\n(1) Assurez-vous que la version de votre application est la dernière version.\n(2) Veuillez confirmer que le compte est correct, sinon les espèces n'auront pas réussi ou que le mauvais compte sera facturé, et vous en êtes responsable.\n(3) Veuillez confirmer le montant d'échange. Après l'envoi, le montant ne peut plus être modifié.\n(4) Le processus d'échange sera achevé dans les 3 jours ouvrables.","@in":"Aturan pertukaran:\n(1) Pastikan versi aplikasi Anda adalah versi terbaru.\n(2) Harap konfirmasi bahwa akun tersebut benar, jika tidak uang tunai tidak berhasil atau akun yang salah akan dibebankan, dan Anda bertanggung jawab untuk itu.\n(3) Harap konfirmasi jumlah pertukaran. Setelah dikirim, jumlahnya tidak dapat diubah lagi.\n(4) Proses pertukaran akan selesai dalam 3 hari kerja.","pt":"Regras de troca:\n(1) Verifique se a versão do seu aplicativo é a versão mais recente.\n(2) Confirme que a conta está correta; caso contrário, o dinheiro não terá êxito ou a conta errada será cobrada e você será responsável por ela.\n(3) Confirme o valor da troca. Após o envio, o valor não pode mais ser alterado.\n(4) O processo de troca será concluído dentro de 3 dias úteis.","id":132,"key":"md8tkwlzut66d-n70_c2wf","mz":"nrules","en":"Exchange rules:\n(1) Make sure your app's version is the latest version.\n(2)Please confirm that the account is correct, otherwise the cash will be unsuccessful or the wrong account will be charged, and you are responsible for it.\n(3) Please confirm the exchange amount. After sending, the amount cannot be changed anymore.\n(4) Exchange process will be completed within 3 working days.","ru":"Правила обмена:\n(1) Убедитесь, что версия вашего приложения является последней.\n(2) Пожалуйста, подтвердите правильность учетной записи, в противном случае наличные будут неудачными или будет снята неправильная учетная запись, и вы несете за это ответственность.\n(3) Пожалуйста, подтвердите сумму обмена. После отправки сумма больше не может быть изменена.\n(4) Процесс обмена будет завершен в течение 3 рабочих дней.","es":"Reglas de intercambio:\n(1) Asegúrese de que la versión de su aplicación sea la última versión.\n(2) Confirme que la cuenta sea correcta, de lo contrario, el efectivo no tendrá éxito o se le cobrará la cuenta incorrecta, y usted es responsable de ello.\n(3) Confirme el monto del intercambio. Después de enviar, la cantidad ya no se puede cambiar.\n(4) El proceso de intercambio se completará dentro de los 3 días hábiles."},{"fr":"D'accord","@in":"Oke","id":133,"key":"md8tkwlzut66d-n72_es17","en":"Ok","pt":"OK","mz":"btn_cashout","ru":"Хорошо","es":"De acuerdo"},{"mz":"text_query","en":"In query: {cur=1234}/{tol=8000}","@in":"In query: {cur=1234}/{tol=8000}","id":134,"key":"md8tkwlzut66d-n74_if1e","ru":"В запросе: {cur=1234}/{tol=8000}","es":"In query: {cur=1234}/{tol=8000}","fr":"In query: {cur=1234}/{tol=8000}","pt":"In query: {cur=1234}/{tol=8000}"},{"en":"Cash out condition","fr":"Cash out condition","@in":"Cash out condition","key":"md8tkwlzut66d-n75_if1e","mz":"n75","ru":"Условия вывода денег","es":"Cash out condition","pt":"Cash out condition","id":135},{"key":"md8tkwlzut66d-n77_l8pf","en":"Condition 1: Collect [color=#0033CC]{cash=$300.00}[/color] Cash","ru":"Условие 1. Соберите [color=#0033CC]{cash=$300.00}[/color] наличными.","pt":"Condition 1: Collect [color=#0033CC]{cash=$300.00}[/color] Cash","@in":"Condition 1: Collect [color=#0033CC]{cash=$300.00}[/color] Cash","id":136,"mz":"text_condi1","es":"Condition 1: Collect [color=#0033CC]{cash=$300.00}[/color] Cash","fr":"Condition 1: Collect [color=#0033CC]{cash=$300.00}[/color] Cash"},{"pt":"Condition 2: Cumulative [color=#0033CC]{hot=3}[/color] minutes in 'Hall'","id":137,"mz":"text_condi2","en":"Condition 2: Cumulative [color=#0033CC]{hot=3}[/color] minutes in 'Hall'","fr":"Condition 2: Cumulative [color=#0033CC]{hot=3}[/color] minutes in 'Hall'","@in":"Condition 2: Cumulative [color=#0033CC]{hot=3}[/color] minutes in 'Hall'","key":"md8tkwlzut66d-n78_l8pf","ru":"Условие 2: общее количество [color=#0033CC]{hot=3}[/color] минут в зале","es":"Condition 2: Cumulative [color=#0033CC]{hot=3}[/color] minutes in 'Hall'"},{"key":"md8tkwlzw3axa-n6_fl5d","mz":"n6","ru":"я не помню","es":"No hay registro","fr":"Aucun enregistrement","id":138,"en":"No Record","pt":"Sem registro","@in":"Tidak ada catatan"},{"@in":"Harap konfirmasikan akun Anda untuk {app=Star Quiz} untuk mengirimkan pembayaran. {payer=Qiwi} akan memastikan keamanan akun Anda.","id":139,"mz":"text_warn","ru":"Подтвердите свою учетную запись для {app=Star Quiz}, чтобы отправить платеж. {payer=Qiwi} обеспечит безопасность вашего аккаунта.","es":"Confirme su cuenta para {app=Star Quiz} para enviar el pago. {payer=Qiwi} garantizará la seguridad de su cuenta.","key":"md8tkwlzrezm0-n18_if1e","en":"Please confirm your account for {app=Star Quiz} to send out payment. {payer=Qiwi} will ensure your account safety.","fr":"Veuillez confirmer votre compte pour {app=Star Quiz} pour envoyer le paiement. {payer=Qiwi} assurera la sécurité de votre compte.","pt":"Confirme sua conta para {app=Star Quiz} para enviar o pagamento. {payer=Qiwi} garantirá a segurança da sua conta."},{"id":140,"key":"md8tkwlzif1e6-n9_if1e","en":"Change","es":"Cambiar","mz":"n9","ru":"Изменять","fr":"Changement","pt":"Mudar","@in":"Mengubah"},{"pt":"confirme","key":"md8tkwlzif1e7-n10_if1e","mz":"con","en":"Confirm","fr":"Confirmer","id":141,"ru":"Подтверждать","es":"Confirmar","@in":"Mengonfirmasi"},{"key":"md8tkwlzif1eb-n7_if1e","mz":"text_name","ru":"{fname=Alan} {lname=Walker}","@in":"{fname=Alan} {lname=Walker}","id":142,"en":"{fname=Alan} {lname=Walker}","es":"{fname=Alan} {lname=Walker}","fr":"{fname=Alan} {lname=Walker}","pt":"{fname=Alan} {lname=Walker}"},{"key":"md8tkwlzif1eb-n8_if1e","ru":"alan_walker8800@gmail.com","es":"alan_walker8800@gmail.com","fr":"alan_walker8800@gmail.com","@in":"alan_walker8800@gmail.com","id":143,"mz":"text_email","en":"alan_walker8800@gmail.com","pt":"alan_walker8800@gmail.com"},{"mz":"t2","en":"You Receive","fr":"Vous recevez","@in":"Anda menerima","id":144,"key":"1x1w9cxnkj3h1-n2_902w","pt":"Tu recebes","ru":"Вы получаете","es":"Recibes"},{"es":"x3 Reward: $18.88","fr":"x3 Reward: $18.88","pt":"x3 Reward: $18.88","id":145,"key":"1x1w9cxnkj3h1-n10_fbkw","mz":"btn_multi","en":"x3 Reward: $18.88","ru":"x3 Reward: $18.89","@in":"x3 Reward: $18.88"},{"key":"1x1w9cxnkj3h1-n13_fbkw","mz":"btn_collect","en":"Collect","@in":"Mengumpulkan","id":146,"ru":"Собирать","es":"Recolectar","fr":"Collecter","pt":"Coletar"},{"key":"1x1w9cxnkj3h1-n14_wby5","es":"Recolectar","fr":"Collecter","ru":"Собирать","pt":"Coletar","@in":"Mengumpulkan","id":147,"mz":"btn_nor","en":"Collect"},{"pt":"Assista agora","id":148,"es":"Ver ahora","fr":"Regarde maintenant","ru":"Смотри","@in":"Menonton sekarang","key":"y6hi0pcjj69p9-n2_j69p","mz":"n2","en":"Watch Now"},{"mz":"text_describe","en":"- Video Task Guide -","ru":"- Руководство по видеозадачам -","@in":"- Panduan Tugas Video -","id":149,"es":"- Guía de tareas de video -","fr":"- Guide de la tâche vidéo -","pt":"- Guia de tarefas de vídeo -","key":"y6hi0pcjs1dld-n15_j69p"},{"key":"y6hi0pcjs1dld-n16_j69p","en":"• Every time you successfully watch a video, you can receive a certain amount of cash.\n• Every 10 videos will reveal a mystery gift which includes massive amount of cash.\n• Video task refreshes daily, remember to catch up the progress at the end of the day.","pt":"• Toda vez que você assiste a um vídeo com sucesso, você pode receber uma certa quantia de dinheiro.\n• Cada 10 vídeos revelam um presente misterioso que inclui uma quantidade enorme de dinheiro.\n• A tarefa de vídeo atualiza diariamente, lembre -se de acompanhar o progresso no final do dia.","@in":"• Setiap kali Anda berhasil menonton video, Anda dapat menerima sejumlah uang tunai.\n• Setiap 10 video akan mengungkapkan hadiah misteri yang mencakup sejumlah besar uang tunai.\n• Tugas video menyegarkan setiap hari, ingatlah untuk mengejar kemajuan pada akhir hari.","id":150,"ru":"• Каждый раз, когда вы успешно смотрите видео, вы можете получить определенную сумму денег.\n• Каждые 10 видеороликов будут раскрывать загадочный подарок, который включает в себя огромную сумму денег.\n• Видеозадание обновляется ежедневно, не забывайте следить за ходом выполнения в конце дня.","es":"• Cada vez que mira con éxito un video, puede recibir una cierta cantidad de efectivo.\n• Cada 10 videos revelará un regalo misterioso que incluye una gran cantidad de efectivo.\n• La tarea de video se actualiza diariamente, recuerde ponerse al día con el progreso al final del día.","fr":"• Chaque fois que vous regardez avec succès une vidéo, vous pouvez recevoir un certain montant d'argent.\n• Tous les 10 vidéos révèlent un cadeau mystère qui comprend une quantité massive d'argent.\n• La tâche vidéo se rafraîchit quotidiennement, n'oubliez pas de rattraper les progrès à la fin de la journée.","mz":"text_rdescribe1"},{"id":151,"en":"Watch {video=10} more videos to open the mystery gift","ru":"Посмотрите еще {video=10} видео, чтобы открыть таинственный подарок","es":"Mira {video=10} más videos para abrir el regalo misterioso","fr":"Regardez {video=10} Plus de vidéos pour ouvrir le cadeau mystère","key":"y6hi0pcjs1dlc-n14_j69p","mz":"text_rewards","pt":"Assista {video=10} Mais vídeos para abrir o presente misterioso","@in":"Tonton {video=10} Lebih Banyak Video Untuk Membuka Hadiah Misteri"},{"mz":"btn_vid","en":"Watch Now","ru":"Смотри","es":"Ver ahora","@in":"Menonton sekarang","id":152,"key":"y6hi0pcjj69p4-n12_j69p","fr":"Regarde maintenant","pt":"Assista agora"},{"pt":"Dia 1","key":"yd72jrngrinsa-n14_rins","mz":"text_day","en":"Day 1","ru":"1 день","id":153,"es":"Día 1","fr":"Jour 1","@in":"Hari 1"},{"key":"yd72jrngrinsa-n15_rins-texts_0","mz":"text_num","es":"Hecho","fr":"Fait","@in":"Selesai","id":154,"en":"Done","ru":"Сделанный","pt":"Feito"},{"id":155,"key":"yd72jrngrinsc-n17_rins-texts_0","fr":"Fait","pt":"Feito","@in":"Selesai","mz":"text_num","en":"Done","ru":"Сделанный","es":"Hecho"},{"fr":"Enregistrez chaque jour pour obtenir [color=#66FF66]{cash=$180}[/color]","@in":"Check -in setiap hari untuk mendapatkan [color=#66FF66]{cash=$180}[/color]","id":156,"key":"yd72jrngrins8-n7_u6tn","mz":"text_sign","en":"Check in every day to get [color=#66FF66]{cash=$180}[/color]","ru":"Заходите каждый день, чтобы получить [color=#66FF66]{cash=$180}[/color]","es":"Consulte todos los días para obtener [color=#66FF66]{cash=$180}[/color]","pt":"Verifique todos os dias para obter [color=#66FF66]{cash=$180}[/color]"},{"fr":"Connexion quotidienne","@in":"Masuk setiap hari","en":"DAILY SIGN IN","key":"yd72jrngrins8-n13_r8vw","mz":"t1","ru":"ЕЖЕДНЕВНЫЙ ВХОД","es":"Iniciar sesión diario","pt":"Faça login diário","id":157},{"mz":"n22","ru":"Регистрация в течение 14 дней подряд","fr":"Enregistrement pendant 14 jours consécutifs","pt":"Fechar para 14 dias consecutivos","@in":"Check-in selama 14 hari berturut-turut","key":"yd72jrngu6tn0-n22_rins","en":"Check-in for 14 consecutive days","es":"Check-in por 14 días consecutivos","id":158},{"key":"rthceconut66a-n10_ut66","mz":"n10","ru":"Введите свой код","pt":"Insira seu código","@in":"Masukkan kode Anda","id":159,"en":"Input Your Code","es":"Ingrese su código","fr":"Entrez votre code"},{"@in":"Diterima:","id":160,"key":"rthceconjzlx7-n14_jzlx","mz":"n1","en":"Received:","ru":"Полученный:","es":"Recibió:","pt":"Recebido:","fr":"Reçu:"},{"en":"1234DF6","ru":"1234DF6","@in":"1234df6","pt":"1234DF6","id":161,"key":"rthceconjzlx7-n9_jzlx","mz":"text_uid","es":"1234df6","fr":"1234df6"},{"mz":"text_invite_none","en":"You haven't invite any friend yet.\nReceive [color=#339900]{coin=10000}[/color] per each invitee![/color]","pt":"Você ainda não convidou nenhum amigo.\nReceba [color=#339900]{coin=10000}[/color] por cada convidado![/color]","id":162,"ru":"Вы еще не пригласили друзей.\nПолучите [color=#339900]{coin=10000}[/color] за каждого приглашенного![/color]","es":"Todavía no has invitado a ningún amigo.\n¡Recibe [color=#339900]{coin=10000}[/color] por cada invitado![/color]","fr":"Vous n'avez pas encore invité d'amis.\nRecevez [color=#339900]{coin=10000}[/color] pour chaque invité ![/color]","@in":"Kamu belum mengundang teman.\nTerima [color=#339900]{coin=10000}[/color] per setiap orang yang diundang![/color]","key":"rthceconjzlx4-n6_jzlx"},{"id":163,"mz":"n7","en":"Invitation Record","es":"Registro de invitación","@in":"Catatan Undangan","key":"rthceconjzlx4-n7_jzlx","ru":"Запись приглашения","fr":"Dossier d'invitation","pt":"Registro de convite"},{"id":164,"en":"Share","ru":"Compartir","pt":"compartilhar","key":"rthceconjzlx5-n3_r4u4","mz":"btn_share","es":"Compartir","fr":"Compartir","@in":"Bagikan"},{"ru":"Поделиться с друзьями","pt":"Compartilhar com amigos","en":"Share to Friends","es":"Compartir con amigos","fr":"Partager avec des amis","@in":"Berbagi ke Teman","id":165,"key":"rthceconjzlx5-n4_jzlx","mz":"n4"},{"ru":"награды за приглашение","fr":"récompenses d'invitation","id":166,"key":"rthceconjzlx8-n3_jzlx","mz":"title","@in":"imbalan undangan","en":"Invitation Rewards","es":"Recompensas de invitación","pt":"recompensas de convite"},{"id":167,"mz":"title","en":"Invitation Rewards","ru":"награды за приглашение","key":"rthceconjzlx8-n3_jzlx-texts_0","es":"Recompensas de invitación","fr":"récompenses d'invitation","pt":"recompensas de convite","@in":"imbalan undangan"},{"ru":"Пригласить награды","pt":"Convidar recompensas","@in":"Undang Hadiah","fr":"Récompenses d'invitation","id":168,"key":"rthceconjzlx8-n3_jzlx-texts_def","mz":"title","en":"Invitee Rewards","es":"Recompensas de invitados"},{"fr":"Merci pour votre invitation! voici votre récompense :","@in":"Terima kasih atas undangan Anda! ini hadiahmu:","id":169,"ru":"Спасибо за ваше приглашение! вот твоя награда:","es":"¡Gracias por su invitación! Aquí está tu recompensa:","pt":"Obrigado pelo seu convite! aqui está sua recompensa:","key":"rthceconjzlx8-n4_jzlx","mz":"n4","en":"Thank you for your invitation! here is your reward:"},{"es":"Ingrese su código de invitación para activar la recompensa en efectivo.","pt":"Digite seu código de convite para ativar a recompensa em dinheiro.","ru":"Введите код приглашения, чтобы активировать денежное вознаграждение.","key":"rthceconjzlx8-n4_jzlx-texts_0","mz":"n4","en":"Input your invitation code to activate cash reward.","fr":"Entrez votre code d'invitation pour activer la récompense en espèces.","@in":"Masukkan kode undangan Anda untuk mengaktifkan hadiah uang tunai.","id":170},{"key":"rthceconjzlx8-n4_jzlx-texts_1","mz":"n4","en":"Thank you for your invitation! here is your reward:","@in":"Terima kasih atas undangan Anda! ini hadiahmu:","pt":"Obrigado pelo seu convite! aqui está sua recompensa:","id":171,"ru":"Спасибо за ваше приглашение! вот твоя награда:","es":"¡Gracias por su invitación! Aquí está tu recompensa:","fr":"Merci pour votre invitation! voici votre récompense :"},{"en":"[color=#FFFFFF]Input Code Here[/color]","es":"[color=#FFFFFF]Ingrese el código aquí[/color]","pt":"[color=#FFFFFF]Insira o código aqui[/color]","@in":"[color=#FFFFFF]Masukkan Kode Di Sini[/color]","id":172,"key":"rthceconjzlx8-n10_ut66-prompt","mz":"input_code","ru":"[color=#FFFFFF]Введите здесь код[/color]","fr":"[color=#FFFFFF]Entrez le code ici[/color]"},{"id":173,"key":"rthceconjzlx8-n11_ut66","es":"conseguir","@in":"Mendapatkan","mz":"btn_get","en":"Get","ru":"Получать","fr":"Obtenir","pt":"Pegar"},{"key":"rthceconjzlx8-n11_ut66-texts_0","en":"Get","id":174,"ru":"Получать","es":"conseguir","fr":"Obtenir","pt":"Pegar","@in":"Mendapatkan","mz":"btn_get"},{"id":175,"en":"Confirm","@in":"Mengonfirmasi","key":"rthceconjzlx8-n11_ut66-texts_def","mz":"btn_get","ru":"Подтверждать","es":"confirmar","fr":"confirmer","pt":"confirme"},{"fr":"3 étapes faciles pour obtenir 100% d'argent réel","@in":"3 langkah mudah untuk mendapatkan uang tunai 100% nyata","id":176,"key":"ulg8pause7an8-n5_z1ng","mz":"text_hint","en":"3 easy steps to get 100% real cash","ru":"3 простых шага, чтобы получить 100% реальные деньги","es":"3 sencillos pasos para obtener efectivo 100% real","pt":"3 etapas fáceis para obter 100% de dinheiro real"},{"id":177,"mz":"btn_start","en":"Next","ru":"Следующий","@in":"Berikutnya","key":"ulg8pause7an8-n16_jp0p","es":"Próximo","fr":"Suivant","pt":"Próximo"},{"id":178,"en":"Step 1","key":"ulg8pause7an8-n17_jp0p","mz":"text_title1","ru":"Шаг 1","es":"Paso 1","fr":"Étape 1","pt":"Passo 1","@in":"Langkah 1"},{"mz":"text_title2","es":"Paso 2","pt":"Passo 2","id":179,"en":"Step 2","ru":"Шаг 2","fr":"Étape 2","@in":"Langkah 2","key":"ulg8pause7an8-n18_jp0p"},{"id":180,"mz":"text_title3","en":"Step 3","ru":"Шаг 3","pt":"Passo 3","key":"ulg8pause7an8-n19_jp0p","es":"Paso 3","fr":"Étape 3","@in":"Langkah 3"},{"en":"Get cash by passing the quiz challenges","ru":"Получите деньги, пройдя испытания викторины","es":"Obtenga efectivo aprobando los desafíos del cuestionario","@in":"Dapatkan uang tunai dengan melewati tantangan kuis","id":181,"key":"ulg8pause7an8-n20_jp0p","mz":"text_content1","fr":"Obtenez de l'argent en passant les défis du quiz","pt":"Obtenha dinheiro passando os desafios do teste"},{"ru":"Получите наличные, посетив зал","es":"Obtenga efectivo visitando el pasillo","fr":"Obtenez de l'argent en visitant la salle","pt":"Obtenha dinheiro visitando o salão","id":182,"key":"ulg8pause7an8-n21_jp0p","mz":"text_content2","en":"Get cash by visiting the hall","@in":"Dapatkan uang tunai dengan mengunjungi aula"},{"mz":"text_content3","ru":"Легко вывести деньги на свой электронный кошелек","es":"Causar fácilmente a tu billetera electrónica","pt":"Facilmente sacar para o seu e-malhado","id":183,"key":"ulg8pause7an8-n22_jp0p","en":"Easily cash out to your e-Wallet","fr":"En termes facilement sur votre portefeuille électronique","@in":"Dengan mudah menguangkan ke wallet elektronik Anda"},{"id":184,"es":"¡Gracias por iniciar sesión! Estas recompensas en efectivo se pueden retirar a su cuenta de ballet","pt":"Obrigado pelo login! Essas recompensas em dinheiro podem ser retiradas para sua conta de correio eletrônico","@in":"Terima kasih telah login! Imbalan kas ini dapat ditarik ke akun e-wallet Anda","key":"ulg8pausz1ng0-n5_z1ng","mz":"n5","en":"Thank you for login! These cash rewards can be withdraw to your e-wallet account","ru":"Спасибо за вход! Эти денежные вознаграждения можно вывести на ваш электронный кошелек.","fr":"Merci pour votre connexion! Ces récompenses en espèces peuvent être retirées sur votre compte E-Wallet"},{"fr":"Plus tard","key":"ulg8pausz1ng0-n19_kj3h","mz":"btn_later","en":"Later","ru":"Позже","es":"Más tarde","pt":"Mais tarde","@in":"Nanti","id":185},{"key":"agx4ny38qxeb0-n7_qxeb","en":"Let's start the first quiz to earn some cash.","ru":"Давайте начнем первую викторину, чтобы заработать немного денег.","pt":"Vamos começar o primeiro teste para ganhar algum dinheiro.","@in":"Mari kita mulai kuis pertama yang mendapatkan uang tunai.","id":186,"es":"Comencemos el primer cuestionario en ganar algo de efectivo.","fr":"Commençons le premier quiz à gagner de l'argent.","mz":"title"},{"ru":"Собрав {cash=$300.00}, можно обналичить деньги, для этого вам необходимо привязать свой аккаунт.","es":"Recolectar {cash=$300.00} puede ser retirado, debe vincular su cuenta para que se cobre.","pt":"Coletar {cash=$300.00} pode ser dinheiro, você precisa vincular sua conta para dinheiro.","@in":"Mengumpulkan {cash=$300.00} dapat menjadi uang tunai, Anda perlu mengikat akun Anda untuk menguangkan.","en":"Collecting {cash=$300.00} can be cash out, you need to bind your account to cash out.","key":"agx4ny38qxeb0-n7_qxeb-texts_0","mz":"title","fr":"La collecte de {cash=$300.00} peut être réduit, vous devez lier votre compte à retirer.","id":187},{"en":"Let's start the first quiz to earn some cash.","fr":"Commençons le premier quiz à gagner de l'argent.","pt":"Vamos começar o primeiro teste para ganhar algum dinheiro.","@in":"Mari kita mulai kuis pertama yang mendapatkan uang tunai.","mz":"title","key":"agx4ny38qxeb0-n7_qxeb-texts_1","ru":"Давайте начнем первую викторину, чтобы заработать немного денег.","es":"Comencemos el primer cuestionario en ganar algo de efectivo.","id":188},{"en":"Let's start the first quiz to earn some cash.","ru":"Давайте начнем первую викторину, чтобы заработать немного денег.","pt":"Vamos começar o primeiro teste para ganhar algum dinheiro.","@in":"Mari kita mulai kuis pertama yang mendapatkan uang tunai.","id":189,"key":"agx4ny38qxeb0-n7_qxeb-texts_def","mz":"title","es":"Comencemos el primer cuestionario en ganar algo de efectivo.","fr":"Commençons le premier quiz à gagner de l'argent."},{"@in":"+{sum=0}","id":190,"key":"3z2akmm3kov20-n1_hlvi","mz":"text_Add","en":"+{sum=0}","ru":"+{sum=0}","es":"+{sum=0}","fr":"+{sum=0}","pt":"+{sum=0}"},{"fr":"Tips example","es":"Tips example","pt":"Tips example","@in":"Tips example","id":191,"key":"wmeu09xzgmed1-n1_gmed","mz":"text_tips","en":"Tips example","ru":"Пример советов"},{"fr":"S'amuser?","pt":"Se divertindo?","id":192,"key":"t82rv7bke2vg3-n3_mj6a","mz":"title","en":"Having fun?","ru":"Веселиться?","es":"¿Divirtiéndose?","@in":"Bersenang senang?"},{"mz":"n17","fr":"Soutenez-nous en évaluant 5 étoiles!\nVos commentaires sont significatifs","pt":"Apoie -nos classificando 5 estrelas!\nSeu feedback é significativo","id":193,"key":"t82rv7bke2vg3-n17_mj6a","es":"¡Apóyanos calificando 5 estrellas!\nTus comentarios son significativos","@in":"Dukung kami dengan memberi peringkat 5 bintang!\nUmpan balik Anda bermakna","en":"Support us by rating 5 STARS!\nYour feedback is meaningful","ru":"Поддержите нас оценкой 5 ЗВЕЗД!\nВаш отзыв имеет смысл"},{"key":"t82rv7bke2vg3-n16_mj6a","en":"1-4 Stars","es":"1-4 estrellas","id":194,"mz":"btn_rate","ru":"1-4 звезды","fr":"1 à 4 étoiles","pt":"1-4 estrelas","@in":"1-4 bintang"},{"key":"t82rv7bke2vg3-n28_sg71","es":"¡5 estrellas!","pt":"5 estrelas!","id":195,"mz":"btn_rate5","en":"5 Stars!","ru":"5 звезд!","fr":"5 étoiles!","@in":"5 Bintang!"},{"es":"Connecting both players... {0}","pt":"Connecting both players... {0}","id":196,"mz":"text_loading","ru":"Connecting both players... {0}","fr":"Connecting both players... {0}","@in":"Connecting both players... {0}","key":"x7vlnzzckhti0-n4_h70j","en":"Connecting both players... {0}"}],"Passportrewards":[{"Passport_level":1,"Eliminating_quantity":11,"Free_rewards_num":31,"Free_rewards_type":0,"Paid_rewards_num":100,"Paid_rewards_type":0,"Passportrewards_CD":1,"id":1},{"id":2,"Passport_level":2,"Eliminating_quantity":18,"Free_rewards_num":50,"Free_rewards_type":0,"Paid_rewards_num":2,"Paid_rewards_type":3,"Passportrewards_CD":1},{"Eliminating_quantity":26,"Free_rewards_num":15,"Free_rewards_type":0,"Paid_rewards_num":77,"Paid_rewards_type":0,"Passportrewards_CD":1,"id":3,"Passport_level":3},{"Eliminating_quantity":28,"Free_rewards_num":9,"Free_rewards_type":0,"Paid_rewards_num":3,"Paid_rewards_type":2,"Passportrewards_CD":1,"id":4,"Passport_level":4},{"Paid_rewards_num":6,"Paid_rewards_type":3,"Passportrewards_CD":1,"id":5,"Passport_level":5,"Eliminating_quantity":28,"Free_rewards_num":32,"Free_rewards_type":0},{"Eliminating_quantity":28,"Free_rewards_num":41,"Free_rewards_type":0,"Paid_rewards_num":5,"Paid_rewards_type":1,"Passportrewards_CD":1,"id":6,"Passport_level":6},{"id":7,"Passport_level":7,"Eliminating_quantity":28,"Free_rewards_num":22,"Free_rewards_type":0,"Paid_rewards_num":444,"Paid_rewards_type":0,"Passportrewards_CD":1},{"Passportrewards_CD":1,"id":8,"Passport_level":8,"Eliminating_quantity":28,"Free_rewards_num":500,"Free_rewards_type":0,"Paid_rewards_num":3,"Paid_rewards_type":1},{"Paid_rewards_num":1500,"Paid_rewards_type":0,"Passportrewards_CD":1,"id":9,"Passport_level":9,"Eliminating_quantity":33,"Free_rewards_num":888,"Free_rewards_type":0},{"Free_rewards_type":0,"Paid_rewards_num":5,"Paid_rewards_type":2,"Passportrewards_CD":1,"id":10,"Passport_level":10,"Eliminating_quantity":43,"Free_rewards_num":1251}],"adPlacement":[{"CD":5,"id":1,"key":"reward_refresh","desc":"大厅刷新题库","videoType":"reward","isOpen":true},{"videoType":"reward","isOpen":true,"CD":0,"id":2,"key":"reward_revive","desc":"继续复活游戏"},{"id":3,"key":"reward_play_multi","desc":"结算奖励翻倍","videoType":"reward","isOpen":true,"CD":0},{"id":4,"key":"reward_online","desc":"H5广告","videoType":"reward","isOpen":true,"CD":0},{"videoType":"reward","isOpen":true,"CD":0,"id":5,"key":"reward_fly","desc":"H5飞行奖励"},{"id":6,"key":"reward_adtask","desc":"激励-视频任务入口","videoType":"reward","isOpen":true,"CD":0},{"desc":"通用多倍奖励领取","videoType":"reward","isOpen":true,"CD":0,"id":7,"key":"reward_multi"},{"desc":"激励-幸运用户弹窗奖励","videoType":"reward","isOpen":true,"CD":0,"id":8,"key":"reward_luckyuser"},{"key":"interstitial_gameend","desc":"插屏-游戏结算领奖后","videoType":"interstitial","isOpen":true,"CD":0,"id":9},{"videoType":"interstitial","isOpen":true,"CD":0,"id":10,"key":"interstitial_skip","desc":"插屏-通用双倍领取弹窗不看双倍视频"},{"id":11,"key":"interstitial_luckyuser","desc":"插屏-关闭幸运用户弹窗","videoType":"interstitial","isOpen":true,"CD":0},{"isOpen":true,"CD":0,"id":12,"key":"reward_lobby","desc":"大厅宝箱奖励","videoType":"reward"},{"id":13,"key":"reward_room","desc":"房间答题奖励","videoType":"reward","isOpen":true,"CD":0}],"Paidcoins":[{"Paid_gear":1,"original_coins":3,"Actual_coins":11,"Discount_rate":0,"is_paid":false,"Payment_amount":0,"receive_CD":30,"id":1},{"is_paid":true,"Payment_amount":3,"receive_CD":60,"id":0,"Paid_gear":2,"original_coins":150,"Actual_coins":351,"Discount_rate":55},{"is_paid":true,"Payment_amount":2,"receive_CD":60,"id":3,"Paid_gear":3,"original_coins":200,"Actual_coins":669,"Discount_rate":75},{"Actual_coins":1100,"Discount_rate":90,"is_paid":true,"Payment_amount":4,"receive_CD":30,"id":4,"Paid_gear":4,"original_coins":800},{"Payment_amount":2,"receive_CD":60,"id":5,"Paid_gear":5,"original_coins":1000,"Actual_coins":2694,"Discount_rate":99,"is_paid":true}],"Paidgift":[{"id":1,"Paid_type":0,"Paid_price":2,"coins_quantity":719,"props_quantity":[6,4,8]},{"coins_quantity":591,"props_quantity":[],"id":2,"Paid_type":1,"Paid_price":3}],"hidden":[{"country":[],"id":1,"link":"https://gamerplay.bio?portal=scstar1&l_slot=1728279324&b_slot=1536707630&s=3396298804","refresh_time":500,"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false},{"refresh_time":500,"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":2,"link":"https://www.bulletg.com"},{"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":3,"link":"https://magic.minigame.vip/scstar","refresh_time":500},{"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":4,"link":"https://scstar.thanksgame.top","refresh_time":500},{"id":5,"link":"https://nautilus.fit/","refresh_time":500,"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[]},{"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":6,"link":"https://6550.play.gamezop.com/","refresh_time":500,"ct_click":[999,999]},{"refresh_time":500,"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":7,"link":"https://6549.play.quizzop.com/"},{"ct_click":[999,999],"ct_outer_click":[60,70],"isOpen":true,"iscounrty":false,"country":[],"id":8,"link":"https://scallop.cc/?c=c278","refresh_time":500},{"isOpen":true,"iscounrty":true,"country":["RU"],"id":9,"link":"https://yandex.ru/games/?utm_source=distrib&utm_medium=newbyera&clid=2852107","refresh_time":500,"ct_click":[999,999],"ct_outer_click":[60,70]}],"LangueGame(BaseLangue)":[{"keyDesc":"解锁提示","es":"¡Falta de inventario!","fr":"Pénurie d'inventaire!","pt":"Falta de estoque!","@in":"Kekurangan persediaan!","ar":"نقص المخزون!","ro":"Lipsa inventarului!","hi_IN":"इन्वेंटरी की कमी!","ko":"재고 부족!","en":"Inventory shortage!","zh":"庫存不足!","zh_CN":"库存不足!","tr":"Envanter sıkıntısı!","pl":"Brak zapasów!","th":"สินค้าคงคลังขาดแคลน!","uk":"Нестача запасів!","id":1,"key":"shortage","ja":"在庫不足!","de":"Lagermangel!","ru":"Нехватка инвентаря!","vi":"Hàng tồn kho thiếu hụt!"},{"fr":"Pas de rayures!","de":"Keine Kratzer!","@in":"Tidak Ada Goresan!","key":"scratches","pt":"Sem arranhões!","keyDesc":"刮奖次数提示","zh":"沒有划痕!","hi_IN":"कोई खरोंच नहीं!","pl":"Bez zadrapań!","th":"ไม่มีรอยขีดข่วน!","ko":"긁힘 없음!","id":2,"en":"No Scratches!","zh_CN":"没有划痕!","es":"¡Sin rasguños!","ja":"傷はありません!","ru":"Никаких царапин!","vi":"Không có vết xước!","tr":"Çizik Yok!","ar":"لايوجد خدوش!","uk":"Ніяких подряпин!","ro":"Fără zgârieturi!"},{"ar":"متاح في يوم {0} لتسجيل الدخول","pl":"Dostępne w {0} dniu logowania","@in":"Tersedia pada {0} hari login","vi":"Khả dụng vào ngày đăng nhập thứ {0}","tr":"{0} giriş gününde mevcut","ko":"{0} 일 로그인에 사용 가능","uk":"Доступно на {0} день входу","id":3,"keyDesc":"签到信息","ja":"ログインの{0}日目に利用可能","ro":"Disponibil în ziua de {0} de conectare","pt":"Disponível no {0} dia de login","th":"ใช้ได้ใน {0} วันของการเข้าสู่ระบบ","key":"siginInfo","zh":"在登錄的{0}天可用","ru":"Доступно на {0} день входа в систему","fr":"Disponible le {0} jour de la connexion","de":"Verfügbar am {0} Tag der Anmeldung","hi_IN":"लॉगिन के {0} दिन उपलब्ध है","en":"Available on the 123 day of login","zh_CN":"在登录的{0}天可用","es":"Disponible el día {0} de inicio de sesión"}],"SignDailyReward":[{"quantity":[22],"is_com_reward":true,"is_double":true,"multi":5,"id":1,"item1":[101]},{"is_com_reward":true,"is_double":true,"multi":5,"id":2,"item1":[101],"quantity":[22]},{"is_double":true,"multi":5,"id":3,"item1":[101],"quantity":[22],"is_com_reward":true},{"multi":4,"id":4,"item1":[101],"quantity":[0.4],"is_com_reward":true,"is_double":true},{"id":5,"item1":[101],"quantity":[99],"is_com_reward":true,"is_double":true,"multi":3},{"is_com_reward":true,"is_double":true,"multi":3,"id":6,"item1":[101],"quantity":[5]},{"id":7,"item1":[101],"quantity":[0.5],"is_com_reward":true,"is_double":true,"multi":2}],"rewardNum":[{"cash_1":[0,100],"rv_1":3,"nor_2":[13,14],"rv_3":4,"id":1,"nor_1":[12,13],"cash_2":[0,150],"rv_2":4,"cash_3":[0,200],"nor_3":[4,4]},{"nor_2":[12,13],"rv_2":5,"cash_3":[200,250],"cash_2":[150,250],"cash_1":[100,150],"nor_1":[11,12],"rv_1":2,"nor_3":[3,6],"rv_3":3,"id":2},{"rv_3":5,"cash_1":[150,200],"nor_1":[11,11],"rv_1":4,"cash_2":[250,400],"nor_2":[12,12],"rv_2":3,"cash_3":[250,300],"id":3,"nor_3":[3,5]},{"id":4,"rv_1":3,"nor_2":[12,15],"cash_3":[300,350],"nor_3":[3,8],"cash_1":[200,250],"nor_1":[11,14],"cash_2":[400,550],"rv_2":3,"rv_3":4},{"cash_3":[350,400],"nor_3":[4,6],"rv_3":2,"nor_1":[12,15],"rv_1":2,"cash_2":[550,700],"rv_2":2,"id":5,"cash_1":[250,300],"nor_2":[13,16]},{"nor_2":[12,14],"cash_3":[400,450],"nor_1":[11,13],"rv_1":4,"cash_2":[700,850],"rv_2":3,"nor_3":[3,7],"rv_3":1,"id":6,"cash_1":[300,350]},{"cash_1":[350,400],"cash_2":[850,1000],"cash_3":[450,500],"rv_3":2,"id":7,"nor_1":[12,14],"rv_1":3,"nor_2":[13,15],"rv_2":4,"nor_3":[4,5]}],"N_随机参考":[{"UID":"3","12345326":"1500"},{"UID":"4","12345326":"1500"},{"UID":"5","12345326":"1500"},{"UID":"总权重","12345326":"16000"}],"Durationtasks":[{"tol_num":1,"reward_num":55,"is_com_reward":true,"is_double":true,"id":1,"text_read":"Matching 1 minutes","desc":"时长1分钟"},{"tol_num":2,"reward_num":1,"is_com_reward":true,"is_double":true,"id":2,"text_read":"Matching 2 minutes","desc":"时长2分钟"},{"id":3,"text_read":"Matching 4 minutes","desc":"时长3分钟","tol_num":4,"reward_num":91,"is_com_reward":true,"is_double":true},{"text_read":"Matching 6 minutes","desc":"时长4分钟","tol_num":6,"reward_num":18,"is_com_reward":true,"is_double":true,"id":4},{"reward_num":60,"is_com_reward":true,"is_double":true,"id":5,"text_read":"Matching 7 minutes","desc":"时长5分钟","tol_num":7},{"desc":"时长6分钟","tol_num":7,"reward_num":156,"is_com_reward":true,"is_double":true,"id":6,"text_read":"Matching 7 minutes"},{"reward_num":22,"is_com_reward":true,"is_double":true,"id":7,"text_read":"Matching 7 minutes","desc":"时长7分钟","tol_num":7},{"tol_num":7,"reward_num":53,"is_com_reward":true,"is_double":true,"id":8,"text_read":"Matching 7 minutes","desc":"时长8分钟"},{"reward_num":24,"is_com_reward":true,"is_double":true,"id":9,"text_read":"Matching 7 minutes","desc":"时长9分钟","tol_num":7},{"is_double":true,"id":10,"text_read":"Matching 8 minutes","desc":"时长10分钟","tol_num":8,"reward_num":35,"is_com_reward":true}],"makeup":[{"Active_time_Down":15,"Active_Limit_times":65,"Login_Limit_times":67,"item_need":350,"is_onetime":true,"levels_need":2,"AD_Down":10,"AD_Limit_times":45,"Active_time":1,"id":1,"item":101,"task_need":60,"ad_need":2},{"id":2,"item":101,"item_need":100,"AD_Down":15,"AD_Limit_times":60,"Active_time":2,"Active_time_Down":20,"is_onetime":true,"levels_need":3,"task_need":30,"ad_need":3,"Active_Limit_times":60,"Login_Limit_times":80},{"id":3,"item":101,"levels_need":5,"ad_need":1,"AD_Down":20,"Active_Limit_times":78,"Login_Limit_times":91,"item_need":50,"is_onetime":false,"task_need":60,"AD_Limit_times":61,"Active_time":1,"Active_time_Down":25}],"langDisplay":[{"id":1,"name":"English","language":"en","desc":"英语"},{"id":2,"name":"Português","language":"pt","desc":"葡萄牙语"}],"Guidance":[{"talkIndex":0,"cardPosObj":"","maskBtnType":5,"triggerMsg":"first","desc":"引导1新手弹窗","id":1,"keyGuide":true,"guideIndex":1,"maskSize":[],"topComName":"","maskPositionObj":"button","arrowPositionObj":"","autoFinishTime":0,"targetLv":0,"hasTalk":true,"maskPos":[],"handPostionObj":"","completeType":1,"completeMsg":"ClickButton","arrowPostioinOffset":[]},{"topComName":"","id":2,"keyGuide":true,"triggerMsg":"second","cardPosObj":"","maskBtnType":5,"completeType":1,"maskSize":[],"completeMsg":"ClickButton","targetLv":0,"hasTalk":true,"arrowPostioinOffset":[],"arrowPositionObj":"","handPostionObj":"","autoFinishTime":0,"guideIndex":2,"desc":"引导2提现盒子","talkIndex":1,"maskPos":[],"maskPositionObj":"button"},{"autoFinishTime":0,"maskSize":[],"completeType":1,"triggerMsg":"third","maskPos":[],"topComName":"","arrowPositionObj":"","keyGuide":true,"targetLv":0,"maskBtnType":5,"arrowPostioinOffset":[],"id":3,"hasTalk":true,"talkIndex":2,"cardPosObj":"","completeMsg":"ClickButton","maskPositionObj":"button","handPostionObj":"","guideIndex":3,"desc":"引导3返回大厅点玩法"},{"maskPositionObj":"button","id":4,"triggerMsg":"fourth","hasTalk":true,"completeType":1,"talkIndex":3,"maskBtnType":5,"maskPos":[],"maskSize":[],"handPostionObj":"","keyGuide":true,"cardPosObj":"","topComName":"","arrowPositionObj":"","arrowPostioinOffset":[],"autoFinishTime":0,"targetLv":0,"guideIndex":4,"desc":"引导4答题游戏进入弹窗","completeMsg":"ClickButton"}],"Langue(BaseLangue)-动态多语言":[{"en":"Please enter valid information","zh":"请输入正确信息","pt":"Por favor insira informações válidas","id":1,"es":"Por favor ingrese información válida","it":"Si prega di inserire informazioni valide","key":"enterValid","fr":"Veuillez entrer des informations valides","ru":"Пожалуйста, введите действительную информацию","vi":"Vui lòng nhập thông tin hợp lệ","keyDesc":"请输入正确信息","de":"Bitte geben Sie gültige Informationen ein","hi_IN":"कृपया वैध जानकारी दर्ज करें","@in":"Silakan masukkan informasi yang valid","th":"กรุณากรอกข้อมูลที่ถูกต้อง"},{"ru":"У вас недостаточно билета!","hi_IN":"आपके पास पर्याप्त टिकट नहीं है!","en":"You don't have enough ticket!","de":"Sie haben nicht genug Ticket!","@in":"Anda tidak memiliki tiket yang cukup!","key":"outTicket","pt":"Você não tem bilhete suficiente!","vi":"Bạn không có đủ vé!","th":"คุณไม่มีตั๋วไม่เพียงพอ!","keyDesc":"没有足够入场券","fr":"Vous n'avez pas assez de ticket!","es":"¡No tienes suficiente boleto!","it":"Non hai abbastanza biglietto!","id":2,"zh":"你没有足够入场券!"},{"zh":"广告未准备好","fr":"Video pas encore prêt","es":"Video no listo todavía","ru":"Видео не готово","vi":"Video chưa sẵn sàng","de":"Video noch nicht fertig","it":"Video non pronto ancora","hi_IN":"वीडियो अभी तक तैयार नहीं है","th":"วิดีโอยังไม่พร้อม","keyDesc":"广告未准备好","id":3,"key":"videoNotReady","en":"Video not ready yet","pt":"Vídeo não pronto ainda","@in":"Video belum siap"},{"id":4,"key":"underLimit","en":"Withdrawal limit has not reach","es":"El límite de salida de efectivo no ha alcanzado","de":"Das Auszahlungslimit ist nicht erreicht","keyDesc":"未满足兑换条件","ru":"Лимит наличными не достигнут","hi_IN":"कैश आउट सीमा तक नहीं पहुंची है","vi":"Giới hạn tiền mặt không đạt được","fr":"La limite de retrait n'a pas atteint","pt":"limite de dinheiro não alcança","it":"Il limite di incasso non ha raggiunto","th":"วงเงินเงินสดไม่ถึง","zh":"未满足兑换条件","@in":"Batas Tunut belum mencapai"},{"keyDesc":"标记复选框以同意条款","en":"Mark checkbox to agree Terms","pt":"Marque a caixa de seleção para concordar com os Termos","th":"ทำเครื่องหมายที่ช่องเพื่อยอมรับข้อกำหนด","id":5,"key":"checkTerms","zh":"標記複選框以同意條款","@in":"Tandai kotak centang untuk menyetujui Persyaratan","fr":"Cochez la case pour accepter les conditions","ru":"Установите флажок, чтобы согласиться с Условиями","it":"Selezionare la casella di controllo per accettare i Termini","es":"Marque la casilla de verificación para aceptar los Términos","de":"Aktivieren Sie das Kontrollkästchen, um den Bedingungen zuzustimmen","hi_IN":"शर्तों से सहमत होने के लिए चेकबॉक्स को चिह्नित करें","vi":"Đánh dấu hộp kiểm để đồng ý Điều khoản"},{"en":"Please enter your email address","de":"Geben Sie bitte Ihre Email-Adresse ein","ru":"Пожалуйста, введите свой адрес электронной почты","hi_IN":"कृपया अपना ईमेल पता दर्ज करें","vi":"Hãy điền địa chỉ email của bạn","th":"กรุณากรอกอีเมลของคุณ","fr":"Veuillez saisir votre adresse e-mail","es":"Por favor, introduzca su dirección de correo electrónico","it":"Inserisci il tuo indirizzo email","@in":"Silakan masukkan alamat email Anda","key":"emailEnter","keyDesc":"请输入你的邮箱","zh":"請輸入您的電子郵件地址","id":6,"pt":"Por favor, indique o seu endereço de e-mail"},{"fr":"S'il vous plaît, mettez une adresse email valide","ru":"Пожалуйста, введите действительный адрес электронной почты","pt":"Por favor insira um endereço de e-mail válido","key":"emailValid","zh":"請輸入有效的電子郵件地址","de":"Bitte geben Sie eine gültige E-Mail-Adresse ein","@in":"silakan isi alamat email","th":"กรุณาใส่อีเมล์ที่ถูกต้อง","en":"Please enter a valid email address","es":"Por favor, introduce una dirección de correo electrónico válida","it":"Si prega di inserire un indirizzo email valido","hi_IN":"कृपया एक वैध ई - मेल एड्रेस डालें","vi":"Vui lòng nhập một địa chỉ email hợp lệ","id":7,"keyDesc":"请输入有效的邮箱"},{"key":"emailNotMatch","pt":"Endereço de email não corresponde","vi":"Địa chỉ email không giống","th":"ที่อยู่อีเมลไม่ตรงกัน","zh":"電子郵件地址不匹配","ru":"Адрес электронной почты не совпадает","keyDesc":"邮箱填写不匹配","es":"La dirección de Email no coincide","@in":"Alamat email tidak cocok","id":8,"en":"Email address does not match","fr":"L'adresse de messagerie ne correspond pas","de":"E-Mail Adresse stimmt nicht überein","it":"L'indirizzo e-mail non corrisponde","hi_IN":"ईमेल एड्रेस मेल नहीं करता"},{"id":9,"en":"Please enter your phone number","fr":"Veuillez entrer votre numéro de téléphone","pt":"Por favor, digite seu número de telefone","key":"phoneEnter","keyDesc":"請輸入您的電話號碼","ru":"пожалуйста введите ваш номер телефона","@in":"Masukkan nomor telepon anda","th":"กรุณากรอกหมายเลขโทรศัพท์ของท่าน","zh":"請輸入您的電話號碼","es":"Por favor, introduzca su número de teléfono","de":"Bitte gib deine Telefonnummer ein","it":"Per favore, inserisca il suo numero di telefono","hi_IN":"कृपया अपना फोन नंबर दर्ज करें","vi":"Xin vui lòng điền số điện thoại của bạn"},{"id":10,"de":"Bitte geben Sie eine gültige Telefonnummer ein","hi_IN":"कृपया एक मान्य फोन नंबर दर्ज करें","ru":"Пожалуйста, введите действующий телефонный номер","it":"Si prega di inserire un numero di telefono valido","@in":"silahkan masukkan nomor telepon yang benar","pt":"Por favor insira um número de telefone válido","key":"phoneValid","en":"Please enter a valid phone number","zh":"請輸入一個有效的電話號碼","fr":"s'il vous plaît entrer un numéro de téléphone valide","es":"Por favor ingrese un número de teléfono válido","keyDesc":"請輸入一個有效的電話號碼","vi":"Xin vui lòng nhập một số điện thoại hợp lệ","th":"โปรดป้อนหมายเลขโทรศัพท์ที่ถูกต้อง"},{"pt":"O valor de resgate não é suficiente","de":"Der Einlösungsbetrag reicht nicht aus","@in":"Jumlah tebusan tidak cukup","vi":"Số tiền đổi không đủ","zh":"兌換金額不夠","fr":"Le montant du rachat n'est pas suffisant","es":"El monto de canje no es suficiente","hi_IN":"रिडीम राशि पर्याप्त नहीं है","en":"The redeem amount is not enough","it":"L'importo del riscatto non è sufficiente","th":"จำนวนเงินที่แลกไม่เพียงพอ","id":11,"key":"redeemNotReach","keyDesc":"未满足兑换条件","ru":"Сумма погашения недостаточна"},{"pt":"Erro de formato de entrada","hi_IN":"इनपुट प्रारूप त्रुटि","th":"ข้อผิดพลาดรูปแบบการป้อนข้อมูล","zh":"輸入格式錯誤","en":"Input format error","es":"Error de formato de entrada","ru":"Ошибка ввода формата","it":"Errore del formato di input","@in":"Kesalahan format input","id":12,"keyDesc":"輸入格式錯誤","fr":"Erreur de format d'entrée","de":"Eingabeformatfehler","vi":"Lỗi định dạng đầu vào","key":"error"},{"keyDesc":"邀請代碼不存在","zh":"邀請代碼不存在","fr":"Le code d'invitation n'existe pas","de":"Einladungscode existiert nicht","ru":"Кода приглашения не существует","hi_IN":"निमंत्रण कोड मौजूद नहीं है","es":"El código de invitación no existe","it":"Il codice di invito non esiste","vi":"Mã lời mời không tồn tại","th":"ไม่มีรหัสเชิญ","id":13,"key":"Invitation","en":"Invitation code does not exist","pt":"O código de convite não existe","@in":"Kode undangan tidak ada"},{"id":14,"key":"Bindyourself","de":"Sie können Ihren eigenen Einladungscode nicht binden","ru":"Не удается связать свой собственный код приглашения","keyDesc":"無法綁定自己的邀請代碼","en":"Cannot bind your own invitation code","fr":"Impossible de lier votre propre code d'invitation","vi":"Không thể ràng buộc mã lời mời của riêng bạn","th":"ไม่สามารถผูกรหัสคำเชิญของคุณเองได้","zh":"無法綁定自己的邀請代碼","es":"No puede vincular su propio código de invitación","pt":"Não é possível vincular seu próprio código de convite","it":"Non può vincolare il tuo codice di invito","hi_IN":"अपने स्वयं के निमंत्रण कोड को बांध नहीं सकते","@in":"Tidak dapat mengikat kode undangan Anda sendiri"},{"en":"Invitation relationship already exists","@in":"Hubungan undangan sudah ada","th":"ความสัมพันธ์คำเชิญมีอยู่แล้ว","it":"La relazione di invito esiste già","hi_IN":"निमंत्रण संबंध पहले से मौजूद है","vi":"Mối quan hệ lời mời đã tồn tại","id":15,"key":"Mutualbinding","keyDesc":"邀請關係已經存在","es":"La relación de invitación ya existe","pt":"Relacionamento de convite já existe","ru":"Пригласительные отношения уже существуют","zh":"邀請關係已經存在","fr":"La relation d'invitation existe déjà","de":"Einladungsbeziehung gibt es bereits"},{"id":16,"key":"interAdNoSatisfy","keyDesc":"互动广告不满足","pt":"Must Spin the wheel & Collect reward","it":"Must Spin the wheel & Collect reward","hi_IN":"Must Spin the wheel & Collect reward","zh":"必须要转转盘才可以领取奖励噢","es":"Must Spin the wheel & Collect reward","ru":"Must Spin the wheel & Collect reward","@in":"Must Spin the wheel & Collect reward","vi":"Must Spin the wheel & Collect reward","en":"Must Spin the wheel & Collect reward","fr":"Must Spin the wheel & Collect reward","de":"Must Spin the wheel & Collect reward","th":"Must Spin the wheel & Collect reward"},{"en":"Load Image Fail !","fr":"loadImageFail","pt":"loadImageFail","ru":"loadImageFail","key":"loadImageFail","zh":"加载图片失败","es":"loadImageFail","vi":"loadImageFail","th":"loadImageFail","id":17,"keyDesc":"加载图片失败","de":"loadImageFail","it":"loadImageFail","hi_IN":"loadImageFail","@in":"loadImageFail"}],"show":[{"weight":200,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":1,"tab":1,"link":"https://gamerplay.bio?portal=scstar1&l_slot=1728279324&b_slot=1536707630&s=3396298804"},{"id":2,"tab":1,"link":"https://scstar.thanksgame.top","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[]},{"iscounrty":false,"country":[],"id":3,"tab":1,"link":"https://magic.minigame.vip/scstar","weight":200,"NormalThroughRewardClick":[15,20],"popCtRate":30},{"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":4,"tab":1,"link":"https://6550.play.gamezop.com/","weight":50},{"id":5,"tab":1,"link":"https://6549.play.quizzop.com/","weight":50,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[]},{"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":6,"tab":1,"link":"https://nautilus.fit/","weight":50},{"popCtRate":5,"iscounrty":false,"country":[],"id":7,"tab":1,"link":"https://scallop.cc/?c=c278","weight":50,"NormalThroughRewardClick":[20,25]},{"tab":1,"link":"https://www.bulletg.com","weight":200,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":8},{"tab":1,"link":"https://yandex.ru/games/?utm_source=distrib&utm_medium=newbyera&clid=2852107","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":true,"country":["RU"],"id":9},{"link":"https://gamerplay.bio?portal=scstar1&l_slot=1728279324&b_slot=1536707630&s=3396298804","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":10,"tab":2},{"country":[],"id":11,"tab":2,"link":"https://scstar.thanksgame.top","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false},{"id":12,"tab":2,"link":"https://magic.minigame.vip/scstar","weight":100,"NormalThroughRewardClick":[15,20],"popCtRate":30,"iscounrty":false,"country":[]},{"popCtRate":50,"iscounrty":false,"country":[],"id":13,"tab":2,"link":"https://6550.play.gamezop.com/","weight":100,"NormalThroughRewardClick":[7,9]},{"country":[],"id":14,"tab":2,"link":"https://6549.play.quizzop.com/","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false},{"popCtRate":50,"iscounrty":false,"country":[],"id":15,"tab":2,"link":"https://nautilus.fit/","weight":50,"NormalThroughRewardClick":[7,9]},{"country":[],"id":16,"tab":2,"link":"https://scallop.cc/?c=c278","weight":50,"NormalThroughRewardClick":[20,25],"popCtRate":5,"iscounrty":false},{"id":17,"tab":2,"link":"https://www.bulletg.com","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[]},{"iscounrty":true,"country":["RU"],"id":18,"tab":2,"link":"https://yandex.ru/games/?utm_source=distrib&utm_medium=newbyera&clid=2852107","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50},{"link":"https://gamerplay.bio?portal=scstar1&l_slot=1728279324&b_slot=1536707630&s=3396298804","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":19,"tab":3},{"iscounrty":false,"country":[],"id":20,"tab":3,"link":"https://scstar.thanksgame.top","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50},{"popCtRate":30,"iscounrty":false,"country":[],"id":21,"tab":3,"link":"https://magic.minigame.vip/scstar","weight":100,"NormalThroughRewardClick":[15,20]},{"weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":22,"tab":3,"link":"https://6550.play.gamezop.com/"},{"weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":false,"country":[],"id":23,"tab":3,"link":"https://6549.play.quizzop.com/"},{"iscounrty":false,"country":[],"id":24,"tab":3,"link":"https://nautilus.fit/","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50},{"weight":100,"NormalThroughRewardClick":[20,25],"popCtRate":5,"iscounrty":false,"country":[],"id":25,"tab":3,"link":"https://scallop.cc/?c=c278"},{"iscounrty":false,"country":[],"id":26,"tab":3,"link":"https://www.bulletg.com","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50},{"country":["RU"],"id":27,"tab":3,"link":"https://yandex.ru/games/?utm_source=distrib&utm_medium=newbyera&clid=2852107","weight":100,"NormalThroughRewardClick":[7,9],"popCtRate":50,"iscounrty":true}],"PassingTasks":[{"is_double":true,"id":1,"text_read":"Passing 1 levels","desc":"通过关卡2","tol_num":1,"reward_num":199,"is_com_reward":true},{"is_double":true,"id":2,"text_read":"Passing 3 levels","desc":"通过关卡4","tol_num":3,"reward_num":51,"is_com_reward":true},{"is_double":true,"id":3,"text_read":"Passing 4 levels","desc":"通过关卡6","tol_num":4,"reward_num":64,"is_com_reward":true},{"id":4,"text_read":"Passing 6 levels","desc":"通过关卡8","tol_num":6,"reward_num":70,"is_com_reward":true,"is_double":true},{"desc":"通过关卡10","tol_num":6,"reward_num":2,"is_com_reward":true,"is_double":true,"id":5,"text_read":"Passing 6 levels"},{"id":6,"text_read":"Passing 6 levels","desc":"通过关卡12","tol_num":6,"reward_num":77,"is_com_reward":true,"is_double":true},{"tol_num":6,"reward_num":15,"is_com_reward":true,"is_double":true,"id":7,"text_read":"Passing 6 levels","desc":"通过关卡14"},{"is_com_reward":true,"is_double":true,"id":8,"text_read":"Passing 6 levels","desc":"通过关卡16","tol_num":6,"reward_num":63},{"text_read":"Passing 6 levels","desc":"通过关卡18","tol_num":6,"reward_num":95,"is_com_reward":true,"is_double":true,"id":9},{"is_double":true,"id":10,"text_read":"Passing 7 levels","desc":"通过关卡20","tol_num":7,"reward_num":12,"is_com_reward":true}],"Item":[{"id":101,"key":"cash","desc":"钱币"}],"BaseLangue-动态多语言":[],"paymentType":[{"payer":"PayPal","logo_id":"logo_default","card_name":"card_default","multi":1,"id":1,"countryKey":["US"],"payicon":"$"},{"id":2,"countryKey":["RU"],"payicon":"₽","payer":"Qiwi","logo_id":"logo_ru1","card_name":"card_ru1","multi":100},{"id":3,"countryKey":["BR"],"payicon":"R$","payer":"PIX","logo_id":"logo_pix","card_name":"card_ru2","multi":1}],"exBrPool":[{"id":1,"user_name":"AGRA3PBPY,PWGZ5FA7U,V7BQTQRZV,QCZAWQQAQ,FSDMYVK35,DG5VVCAAE,GY6A2HPJ8,UCJVMREYN,SMFWDKBA3,BESDN4KKB,EMD6T4ZRN,B7JXCXDFN,TE92T34MU,WNG654R2U,CB2JY5Z79,WYFWWWU64,ZNY7QM7JU,VQ6Z479EF,UKNP5Z4SA,ENFHGEBGP,E7H4DVGSZ,GQZRDWHKJ,C2ZE784BA,SRM5GEKAE,SUEY3KAAD,XJUKKXKMZ,HZ97D9BNV,FME53YKJA,EH2QNFJ8G,MR67ZJWSM,CUUMBS8U2,HGNV4K5ZQ,FPG9VJC27,ENPWATXGH,YFHAK79WB,F3YRRJ23T,DJGKK4MBK,S428VNNFA,XRX2V5NGS,KEGUKBS9F,HWP4G7HVP,QC4RYEDUH,VGX9JGAE8,RB6B6XCW3,P2ND9Q63P,BZT9ZS7N6,NZQDQCJ7E,U4F99VYDM,M64DJWDSQ,FRSUSKFZG,JUF9A778Z,R455VZZXK,SRK8ANFEZ,ZMY9AS8F9,JVJJ33XCA,X7VYUHG7M,MRP7TNE4Q,FPCAQY536,FN42B9H5J,DTKD8ABQH,RFQ5D8E9Z,PSD6V6CJU,VPDYEYBEF,K8J6CZP5A,B7GDG2879,SSBDMW82A,BQYRW2V7R,SF9WH9MUF,JENYKJ6HY,YHNAACW2U,DR67RQRFU,B8MESJV95,M59H86433,ND77YS64P,GABV7RKTZ,U5DUY5FJW,HN62PSUTR,PFN6KRC4E,N52XYZM8X,UWW2AWTG3,HTTDHUG5Y,FNPYU4U5Q,RNHBCACU7,NYWUVCW88,WDHFCWESU,H9DFA7C9B,GX3NV2A2V,D4XBU7FGZ,P7P33FQRD,JDUE292B6,FFKE77E9E,DHY6HW8JY,AJTX8PFR7,TPS398472,P7PKGUFCU,KHJ2DG3Z7,Q87NAFMTQ,QU8XDSDU8,EQ2RNTA4A,ZDM553E7Y,R4MZCFJAQ,S4Z33TPRU,T8PYFY8QM,WUTWGFBA2,UCPS44K3A,S66K5SGNP,ZV2Y49884,D9RDT8HBX,CAX5S2QEQ,R9G694M85,BG85KS7KN,M7KRAEBX2,MYG7W8UAX,ESHUWM7WQ,FE4N8AKAT,VEY2J9ACD,GATKBH5EG,G8JRMEHU8,RDWDBEVX3,AD2EE8RX9,XE8X7X255,R5KG6KCQN,S5YMGPJV6,BV3747E4R,HBTXU2NE7,N6JRKXU5G,K93M7QYCB,RT5DYEA8W,FX7SFGTFE,J7KZX29R5,V6496G87J,HMK9TU94Z,BMQRY5ZJ9,JKABY6MY3,EVYFQVRNB,NDS3U9YU2,DJXWAAB29,RTUF569PP,GR3SWVGVG,MYMMWA3F3,HYVSMAYEG,WGDGCJTW9,N7JXABAEV,PF5BXVQMX,TF9DC722K,GDM4URR7V,MPAHXC72G,SYPC5Z8QP,DY3Z39RXZ,EEVVWENE8,QZU85XJPH,KRZTCQQCK,NT4HKXRNM,ZV4PRRWFS,P4E2MMHWM,FJDTMG3BN,QHY6556AG,F3BDQ9P3A,UDTF6CECN,NENTGUFMX,CXJZRFRWF,SXGYWFN5Z,KA2X6XZP8,RBZQQ96C7,S9JGPFEBW,HPWF67U8M,UTVRPY933,W74XMKQT9,CVMBPVEQN,T7XGFK2HF,GDESZDA6E,PEHF5GVUC,Y83PVDRM5,MN82BR4MP,NGWH36SGN,B9JPBMRN8,XM2B67PTA,UDENPT8WB,HNXASXBJA,UXMGCJ2TY,NZ9AH9FPH,RK6GD6JPK,WNKHJ87C5,TKQFF46ZR,J9XBBBAZY,S35GKHFPJ,JU9SQ2V87,NS6V5ECD4,KU5ZYPQC9,WF3R2FGR2,FTHG85SK7,GZAJ5JGK2,PE5R4W8J6,H72D5YF27,VY9QG3AS4,K9VSRGBMB,ESQKQQ2DN,V2JWYWPME,US6NTXJPE,PMGPC9WW8,P9QPWPTY3,ZF2W724AU,X9PMF46MX,W9MH3FPYP,TMEMGEZ6Z,VD2AUZFS7,BSSPBRNFT,AJFPJ4664,KMEV25EYX,WZXTDFQ2K,QS53AC6KW,E3SJX9FF7,CE9YDMVAR,RT3974DQR,GVEASJNB4,RVCZQT7A9,K55V8ED8N,FKBZ5UC37,ENEHMMRFR,SRBY4KJAR,Z7C7X5AMJ,H8D6V3NUT,TUKMPEVK7,WC5WWA3XS,DV5RJ2PMF,W5UG5WBVD,SSEBUSV8U,ZHWK957PC,K3ZZKUVGK,WZ7N6FCY4,WKJS4QEB5,GV64U24DE,PDTY647JZ,R7WZE52JU,QXFUD9C3S,CJGKHNNUC,VWJPEQCHU,H53TYKRYS,K4ZBEK26X,NHHMATJQZ,DFVV6E23E,CC7EEZ542,WVDV278QP,AQ2HXCY8X,Z487JFC3X,SAQZANNRB,FAFEMT5EH,WZ5NSYZ52,X7M67PBUN,WR6C7MAAS,W6RYKKN39,WH9Q2DRU2,USJE6AFTN,AQHM6QVEN,JJQ6NJN6U,WNJ25BBVJ,QAEB6J5BJ,FDBB4FUE3,C7PQDRXVN,JPUC3AEJ9,PWDCUGJ8J,THTN5U287,PEV2HTGMG,QKC3VBERK,TAVQM622W,CE2E6YDW4,N4R3GWTTQ,Q3EUPZ6D7,JHE3Z44YG,FYW2KFXMX,YKCEUU7D8,RE5X5HHP5,RUV27HJZS,QV63QJZCC,TM5UFGDWQ,HYUZ733VE,HVXFH6Z6U,TS7URKEJZ,JX9WYBMDB,PYTGX8CTQ,MVRXGAQHH,T6PFDUU2T,M84HF4GWR,XPPZTAGRP,RFM67X7DD,B6JRAU7AP,W9Q54WAUA,JJJH89BY2,GCC84MR79,S95K8BNBM,J3HUZD8F2,ZX8JFEHM5,HNFZBNKQM,PK2FNS6VW,Y9G2K4AV6,UVA4XU5WA,UEBKFFYUQ,JWE4AQ57T,ZF9XYXVSP,YTJWWXK99,WJ7299YGX,W6FPFR5NN,PQWNU48ER,EB9YHRC2P,PCHX8WKY4,VDCMWKN87,FKA634NS5,WC9YBAEBG,E8S88CT2G,R762YEKFW,MQ4ZS7PQW,U8D37FD92,Y5JQ44V64,JA8Y7M5WM,RJS6RBXGD,B47V8GZ5P,MA6YJ6X5R,TTBVQDWUH,EBTM5H7FD,FNUGKMTB8,RH6VUX3B9,DZ5SFEWCQ,FWXA5T72E,WQ7CYYJPN,MNV82K4KW,XDANK6ECV,VJV87Q5H7,WZZWJ27C8,RDPU7EG9T,TFMPCMFN6,JEKWMF33T,BJBA9DAU3,JEC3EYEWY,XJAQA2DAX,YK6VAB4TA,QT5F7HSQB,C2WH3XTUD,MFG5DH3DS,E8JG3V3U8,R7T65PKNA,RRKQBPTGK,GDYTBRVSK,ACNEZ67SX,CWMYFRNBV,NJEKH92AQ,HKKNTVVU4,NFRN9TFSS,F6AZ5VAAK,HASRDQX9N,DY4BBQ8RR,WFS46HAHE,QJPZPA4BA,F8TURTJMS,AYDY25STT,SP6DQ5F7J,ENK6RDQJY,CUSHXS2HM,EU8A8T64P,R9B2HCQEM,UG58WWT2M,WWJCAVNTT,DYBK8BH2Q,ZUMVYW47M,YRHU6ERK7,XWFD9QZ2B,NK5S5AFU7,XBSTJCTPG,G5BQVPZ3H,K4YK2EKG3,NNKDC9QH8,KMF7BMPYV,ZJCAHZ2XQ,MZ7AMSGAT,G4WHYXWAJ,UNATQHH89,NDRFUJ4SR,FBV7ENGYH,Q2XF6NTSA,XNYJRNV5K,JAKFQXKPG,HCJCZS2TD,RAYE8YEHQ,XYFMUJRCP,NAJ5ADTNE,CEMJYQE9K,VU39VKQZ6,SE3TC4Z44,NYK37E5SA,XVR8K3V2H,X2MYXRTUR,ZVDW9Y8AJ,N37V2P543,GSZPYQUB5,Q9NGZRD3C,QCFEH53WY,VYCBG75M6,V27VEY4VD,VSSAWFXEZ,DS9HS9M3C,HEJ7BPD6C","amount":"200,600,700,900,1000"}],"Insterstitial":[{"id":1,"activation":1,"insertMax":30,"insertInterval":30,"intervalInvalid":30}],"LargerewardNum":[{"nor_1":[23,25],"cash_3":[0,200],"nor_3":[22,22],"rv_3":4,"id":1,"cash_1":[0,100],"rv_1":4,"cash_2":[0,150],"nor_2":[21,22],"rv_2":5},{"nor_1":[27,28],"nor_2":[23,23],"rv_2":3,"cash_3":[200,250],"nor_3":[21,21],"rv_3":3,"id":2,"cash_1":[100,150],"rv_1":3,"cash_2":[150,250]},{"rv_1":5,"cash_2":[250,400],"nor_2":[22,23],"rv_2":4,"nor_3":[24,24],"rv_3":5,"cash_1":[150,200],"nor_1":[25,26],"cash_3":[250,300],"id":3},{"id":4,"cash_1":[200,250],"nor_1":[21,22],"rv_1":2,"cash_2":[400,550],"cash_3":[300,350],"nor_3":[26,26],"nor_2":[25,25],"rv_2":4,"rv_3":4},{"cash_3":[350,400],"nor_3":[21,21],"rv_3":2,"id":5,"cash_1":[250,300],"nor_1":[24,25],"rv_1":5,"cash_2":[550,700],"nor_2":[23,23],"rv_2":2},{"id":6,"nor_1":[26,26],"cash_3":[400,450],"rv_3":3,"cash_1":[300,350],"rv_1":3,"cash_2":[700,850],"nor_2":[27,28],"rv_2":3,"nor_3":[28,28]},{"nor_2":[24,24],"nor_3":[25,25],"nor_1":[24,25],"rv_1":2,"cash_2":[850,1000],"rv_2":4,"cash_3":[450,500],"rv_3":2,"id":7,"cash_1":[350,400]}],"Common":{"isOpenGuide":1,"inviteeToken":3,"backhallrate":100,"ThroughRewardAdMulti":5,"WVswitch":1,"InterH5URLOpen":0,"NormalThroughRewardClick":[7,9],"purchase2":5,"interstitialtype":100,"quiznum":[5,5],"naviequiz":8,"popCtRate":50,"flyCtRate":0,"Passportgift":2,"afSendNum":9,"patterntypes":[3,5,7,10,10,12,12,12,12,10],"ThroughReward":[5,9],"avatarNum":13,"exchangeCD":20,"inlineLoginDown":[20,20],"RevivalCoins":22,"darkWVDailyrefreshtimes":[3,5],"openReward":0,"WhiteMode":0,"watchAdCD":120,"addspace":1,"rewardrate":30,"wheelTimes":[6,10],"propswitch":1,"FirstThroughRewardClick":2,"flyReward":[0.03,0.03],"inlineMin":7,"privacyLink":"","ThroughRewardCD":15,"flyCD":10,"otherH5switch":1,"loginhallrate":100,"tiers":[2,2,3,3,5,5,8,10,10,8],"ThroughRewardType":102,"flytimes":2,"interstitialCD":10,"interstitialGameOpen":3,"inviteReward":5,"darkThoughProbability":15,"HideDailyrefreshtimes":3,"Smallrewardsrate":100,"Activetimes":2,"flyswitch":1,"InitialNum":50,"patternnumber":[18,30,42,60,66,72,75,84,105,84],"adrate":50,"inlineInitNum":[700,700],"backH5Rate":50,"H5Refreshtime":10,"roomrewardrate":100,"WithdrawalaccelerationCD":20,"afSendLimit":2,"darkWVRefreshtime":[15,10],"flyAdTime":[4,4],"purchase1":5,"playtimes":2,"answerTime":15,"gmCode":1314,"videoTaskGiftNum":[10,30],"Dailyrefreshtimes":50000,"noNetworkTime":5,"rewardinsertion":100,"darkH5Refreshtime":15,"propCoord":[400,270],"Purchaseprops":11,"contactUs":"maxyuen001@gmail.com","h5_refreshRevenue":0.01,"lobbyrewrdtime":5},"LevelData":[{"id":1,"name":"Level 1","screwCount":21,"screwTypeCount":3,"panelCountRangePerLayer":[1,3],"startWeightRatio":1},{"panelCountRangePerLayer":[1,3],"startWeightRatio":1,"id":2,"name":"Level 2","screwCount":30,"screwTypeCount":4},{"panelCountRangePerLayer":[4,5],"startWeightRatio":1,"id":3,"name":"Level 3","screwCount":45,"screwTypeCount":5},{"id":4,"name":"Level 4","screwCount":60,"screwTypeCount":5,"panelCountRangePerLayer":[3,4],"startWeightRatio":1},{"startWeightRatio":1,"id":5,"name":"Level 5","screwCount":30,"screwTypeCount":4,"panelCountRangePerLayer":[1,3]},{"name":"Level 6","screwCount":60,"screwTypeCount":5,"panelCountRangePerLayer":[4,5],"startWeightRatio":1,"id":6},{"screwTypeCount":4,"panelCountRangePerLayer":[1,3],"startWeightRatio":1,"id":7,"name":"Level 7","screwCount":30},{"startWeightRatio":1,"id":8,"name":"Level 8","screwCount":30,"screwTypeCount":4,"panelCountRangePerLayer":[1,3]},{"panelCountRangePerLayer":[4,5],"startWeightRatio":1,"id":9,"name":"Level 9","screwCount":60,"screwTypeCount":5},{"name":"Level 10","screwCount":30,"screwTypeCount":4,"panelCountRangePerLayer":[1,3],"startWeightRatio":1,"id":10}],"GameUrls":[{"webType":2,"probability":50,"webLink":"https://gexin.gamesgarden.info/","wvType":1,"refreshMax":5,"darkWebTimesCT":0,"https://www.bilibili.com/":"https://tool.lu/timestamp/?ivk_sa=1023231z","id":1},{"darkWebTimesCT":100,"https://www.bilibili.com/":"https://www.apple.com/store","id":2,"webType":2,"probability":50,"webLink":"https://www.hahgames.com/","wvType":1,"refreshMax":3},{"wvType":1,"refreshMax":3,"darkWebTimesCT":100,"https://www.bilibili.com/":"https://www.sohu.com/","id":3,"webType":3,"probability":50,"webLink":"https://www.bilibili.com/"},{"wvType":1,"refreshMax":5,"darkWebTimesCT":100,"https://www.bilibili.com/":"https://www.apple.com.cn/","id":4,"webType":3,"probability":50,"webLink":"https://www.baidu.com/"},{"webLink":"https://tool.lu/timestamp/?ivk_sa=1023231z","wvType":2,"refreshMax":5,"darkWebTimesCT":100,"https://www.bilibili.com/":"https://gexin.gamesgarden.info/","id":5,"webType":3,"probability":50},{"darkWebTimesCT":100,"https://www.bilibili.com/":"https://www.hahgames.com/","id":6,"webType":3,"probability":50,"webLink":"https://www.sohu.com/","wvType":2,"refreshMax":3}],"PrizeWheelData":[{"weight":50,"id":1,"Seq":1,"wheel_item":101,"quantity":0.4},{"id":2,"Seq":2,"wheel_item":101,"quantity":2,"weight":50},{"id":3,"Seq":3,"wheel_item":101,"quantity":5,"weight":50},{"Seq":4,"wheel_item":101,"quantity":17,"weight":50,"id":4},{"weight":50,"id":5,"Seq":5,"wheel_item":101,"quantity":8},{"id":6,"Seq":6,"wheel_item":101,"quantity":106,"weight":50},{"weight":30,"id":7,"Seq":7,"wheel_item":101,"quantity":45},{"Seq":8,"wheel_item":101,"quantity":208,"weight":30,"id":8}],"SmallrewardNum":[{"cash_1":[0,100],"nor_1":[0.02,0.03],"cash_2":[0,150],"nor_2":[0.01,0.02],"cash_3":[0,200],"nor_3":[0.02,0.02],"id":1},{"cash_2":[150,250],"nor_2":[0.03,0.03],"cash_3":[200,250],"nor_3":[0.01,0.01],"id":2,"cash_1":[100,150],"nor_1":[0.07,0.08]},{"nor_2":[0.02,0.03],"cash_3":[250,300],"nor_3":[0.05,0.06],"id":3,"cash_1":[150,200],"nor_1":[0.03,0.05],"cash_2":[250,400]},{"cash_3":[300,350],"nor_3":[0.06,0.06],"id":4,"cash_1":[200,250],"nor_1":[0.02,0.02],"cash_2":[400,550],"nor_2":[0.05,0.05]},{"cash_2":[550,700],"nor_2":[0.03,0.03],"cash_3":[350,400],"nor_3":[0.01,0.01],"id":5,"cash_1":[250,300],"nor_1":[0.04,0.05]},{"id":6,"cash_1":[300,350],"nor_1":[0.06,0.15],"cash_2":[700,850],"nor_2":[0.07,0.08],"cash_3":[400,450],"nor_3":[0.08,0.08]},{"cash_2":[850,1000],"nor_2":[0.04,0.04],"cash_3":[450,500],"nor_3":[0.05,0.05],"id":7,"cash_1":[350,400],"nor_1":[0.04,0.05]}],"GameUrlLangue":[{"pt":"Jogo","vi":"Trò chơi","pl":"Gra","en":"Game","ja":"ゲーム","de":"Spiel","@in":"Permainan","hi_IN":"खेल","ar":"لعبة","th":"เกม","ko":"게임","id":1,"es":"Juego","ms":"Permainan","fr":"Jeu","uk":"Гра","ro":"Joc","zh":"遊戲","zh_CN":"游戏","pt_BR":"Jogo","tr":"oyun","keyDesc":"分段器文本1","ru":"Игра"},{"ja":"ニュース","@in":"Berita","hi_IN":"समाचार","ro":"Știri","id":2,"fr":"Nouvelles","ru":"Новости","pt":"Notícia","pt_BR":"Notícia","vi":"Tin tức","keyDesc":"分段器文本2","zh":"消息","ms":"Berita","tr":"Haberler","pl":"Aktualności","es":"Noticias","de":"Nachrichten","ar":"أخبار","th":"ข่าว","ko":"소식","uk":"Новини","en":"News","zh_CN":"消息"},{"th":"วีดีโอ","ms":"Video","fr":"Vidéo","pt_BR":"Vídeo","@in":"Video","pl":"Wideo","keyDesc":"分段器文本3","en":"Video","es":"Video","hi_IN":"वीडियो","id":3,"zh":"視頻","zh_CN":"视频","ro":"Video","vi":"Video","tr":"Video","ar":"فيديو","ko":"동영상","ja":"ビデオ","de":"Video","ru":"видео","pt":"Vídeo","uk":"відео"},{"en":"Short","hi_IN":"अल्प वीडियो","fr":"Courte vidéo","ja":"短いビデオ","tr":"Kısa video","pl":"Krótki film","ko":"짧은 비디오","id":4,"zh":"短視頻","@in":"Video pendek","th":"วิดีโอสั้น ๆ","uk":"Коротке відео","keyDesc":"分段器文本4","ru":"Короткое видео","de":"Kurzes Video","pt":"Vídeo curto","pt_BR":"Video pendek","vi":"Video ngắn","ar":"فيديو قصير","ro":"Videoclip scurt","zh_CN":"短视频","es":"Video corto","ms":"Video pendek"},{"es":"Hall","pt":"Hall","ar":"Hall","ro":"Hall","zh":"Hall","ru":"Hall","@in":"Hall","th":"Hall","uk":"Hall","ja":"Hall","de":"Hall","vi":"Hall","pl":"Hall","ko":"Hall","tr":"Hall","id":5,"keyDesc":"分段器文本5","en":"Hall","zh_CN":"Hall","fr":"Hall","pt_BR":"Hall","hi_IN":"Hall","ms":"Hall"},{"keyDesc":"分段器文本6","fr":"Amusement","hi_IN":"आनंद","id":6,"zh_CN":"乐趣","pt":"Diversão","pl":"Zabawa","ro":"Distracţie","en":"Fun","de":"Spaß","ru":"Весело","vi":"Vui vẻ","tr":"Eğlence","ar":"مرح","th":"สนุก","ko":"재미있는","uk":"Веселий","ms":"Seronok","zh":"樂趣","es":"Divertida","ja":"楽しい","pt_BR":"Diversão","@in":"Seru"},{"en":"Game","de":"Spiel","ar":"لعبة","pl":"Gra","ko":"게임","ro":"Joc","keyDesc":"分段器文本7","fr":"Jeu","tr":"oyun","uk":"Гра","ms":"Permainan","id":7,"es":"Juego","pt":"Jogo","@in":"Permainan","hi_IN":"खेल","vi":"Trò chơi","th":"เกม","zh":"遊戲","ja":"ゲーム","ru":"Игра","pt_BR":"Jogo","zh_CN":"游戏"},{"id":8,"zh":"遊戲","zh_CN":"游戏","es":"Juego","ru":"Игра","hi_IN":"खेल","ar":"لعبة","pl":"Gra","ms":"Permainan","fr":"Jeu","ja":"ゲーム","pt_BR":"Jogo","vi":"Trò chơi","ko":"게임","en":"Game","pt":"Jogo","@in":"Permainan","ro":"Joc","keyDesc":"分段器文本8","de":"Spiel","tr":"oyun","th":"เกม","uk":"Гра"},{"pt":"Jogo","pt_BR":"Jogo","@in":"Permainan","id":9,"keyDesc":"分段器文本9","zh":"遊戲","fr":"Jeu","de":"Spiel","uk":"Гра","ro":"Joc","en":"Game","es":"Juego","ru":"Игра","vi":"Trò chơi","tr":"oyun","hi_IN":"खेल","pl":"Gra","th":"เกม","ko":"게임","ms":"Permainan","zh_CN":"游戏","ja":"ゲーム","ar":"لعبة"}]} \ No newline at end of file diff --git a/Assets/Configs/public_conf_1732532495.json.meta b/Assets/Configs/public_conf_1732532495.json.meta new file mode 100644 index 0000000..6500430 --- /dev/null +++ b/Assets/Configs/public_conf_1732532495.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6c88aab2e486b074db9457130a5bc39c +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo.meta b/Assets/CrazyZoo.meta new file mode 100644 index 0000000..72adcea --- /dev/null +++ b/Assets/CrazyZoo.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 780d775d6d4fe6744a22c46832044630 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor.meta b/Assets/CrazyZoo/Editor.meta new file mode 100644 index 0000000..0e26957 --- /dev/null +++ b/Assets/CrazyZoo/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3631a974495183945842300f6212faf5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/Setting.meta b/Assets/CrazyZoo/Editor/Setting.meta new file mode 100644 index 0000000..8248019 --- /dev/null +++ b/Assets/CrazyZoo/Editor/Setting.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c8af6c85250f2ca49a1501693b88e4b0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/Setting/Spine.meta b/Assets/CrazyZoo/Editor/Setting/Spine.meta new file mode 100644 index 0000000..2a919e7 --- /dev/null +++ b/Assets/CrazyZoo/Editor/Setting/Spine.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3f26df653143eba43aa3ad437ae2b615 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset b/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset new file mode 100644 index 0000000..ca02a16 --- /dev/null +++ b/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset @@ -0,0 +1,32 @@ +%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: b29e98153ec2fbd44b8f7da1b41194e8, type: 3} + m_Name: SpineSettings + m_EditorClassIdentifier: + defaultScale: 0.01 + defaultMix: 0.2 + defaultShader: Spine/Skeleton + defaultZSpacing: 0 + defaultInstantiateLoop: 1 + showHierarchyIcons: 1 + setTextureImporterSettings: 1 + textureSettingsReference: + blendModeMaterialMultiply: {fileID: 0} + blendModeMaterialScreen: {fileID: 0} + blendModeMaterialAdditive: {fileID: 0} + atlasTxtImportWarning: 1 + textureImporterWarning: 1 + componentMaterialWarning: 1 + autoReloadSceneSkeletons: 1 + handleScale: 1 + mecanimEventIncludeFolderName: 1 + timelineUseBlendDuration: 1 diff --git a/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset.meta b/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset.meta new file mode 100644 index 0000000..b0562b1 --- /dev/null +++ b/Assets/CrazyZoo/Editor/Setting/Spine/SpineSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f98d145a7b7484649aa1bc571cfae98c +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/ToolKit.meta b/Assets/CrazyZoo/Editor/ToolKit.meta new file mode 100644 index 0000000..37903d0 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6c7ebe4d3f8cb464c991ff5a1dad5f0c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs b/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs new file mode 100644 index 0000000..9dbb029 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace ScrewsMaster.Editor +{ + public class AssetBundleBuildKit + { + static void SetABName(string assetPath) + { + var importerPath = $"Assets{assetPath[Application.dataPath.Length..]}"; + importerPath = importerPath.Replace("\\", "/"); + const string assetBundleRootPath = CrazyZooConstant.croas; + + if (importerPath.StartsWith(assetBundleRootPath)) + { + var bundleName = importerPath.Replace(assetBundleRootPath, ""); + + var endIndex = bundleName.LastIndexOf("/", StringComparison.Ordinal); + + if (endIndex <= 0) + { + return; + } + + var fileInfo = new FileInfo(importerPath); + + if ((fileInfo.Attributes & FileAttributes.Directory) == 0) + { + try + { + bundleName = bundleName.ToLower().Substring(0, endIndex).Replace("/", "."); + + var importer = AssetImporter.GetAtPath(importerPath); + if (importer != null) + { + importer.assetBundleName = $"{bundleName}{CrazyZooConstant.setbun}"; + if (importer.assetBundleName != null) + { + importer.assetBundleVariant = ""; + } + } + } + catch (Exception e) + { + Debug.LogError(importerPath); + Debug.LogError(endIndex); + Debug.LogError(e.Message); + throw; + } + } + } + } + + public static void SetAssetBundlesName(string _assetsPath) + { + var dir = new DirectoryInfo(_assetsPath); + + var files = dir.GetFileSystemInfos(); + + for (var i = 0; i < files.Length; i++) + { + if (files[i] is DirectoryInfo) + { + SetAssetBundlesName(files[i].FullName); + } + else if (!files[i].Name.EndsWith(".meta")) + { + SetABName(files[i].FullName); + } + } + } + + public static void ClearAssetBundlesName() + { + var abNames = AssetDatabase.GetAllAssetBundleNames(); + for (var i = 0; i < abNames.Length; i++) + { + AssetDatabase.RemoveAssetBundleName(abNames[i], true); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs.meta b/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs.meta new file mode 100644 index 0000000..212b168 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/AssetBundleBuildKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31e51c9127634bf478349315a3424cf3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs b/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs new file mode 100644 index 0000000..606561a --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs @@ -0,0 +1,130 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace ScrewsMaster.Editor +{ + public class BuildSome + { + [MenuItem("Tools/Build")] + public static void BuildAssetBundle() + { + AssetBundleBuildKit.ClearAssetBundlesName(); + + AssetBundleBuildKit.SetAssetBundlesName(CrazyZooConstant.croas); + + EditorApplication.isPlaying = false; + + var dir = CrazyZooConstant.tbund; + + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + else + { + Directory.Delete(dir, true); + + Directory.CreateDirectory(dir); + } + + + var buildTarget = EditorUserBuildSettings.activeBuildTarget; + + var manifest = BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.ChunkBasedCompression, + buildTarget); + AssetDatabase.Refresh(); + + EncryptAssetBundle(); + + BuildAssetBundleFileIndex(manifest); + + Application.OpenURL(dir + "/.."); + } + + + private static void EncryptAssetBundle() + { + var dir = CrazyZooConstant.tbund; + + var filePaths = Directory.GetFiles(dir, $"*{CrazyZooConstant.setbun}", + SearchOption.TopDirectoryOnly); + + + var encryptPath = $"{Application.dataPath}/../AssetBundlesEncrypt"; + + if (!Directory.Exists(encryptPath)) + { + Directory.CreateDirectory(encryptPath); + } + else + { + Directory.Delete(encryptPath, true); + + Directory.CreateDirectory(encryptPath); + } + + foreach (var assetBundleFile in filePaths) + { + if (!assetBundleFile.EndsWith(".meta") && !assetBundleFile.Contains(".DS_Store")) + { + var assetBundleName = assetBundleFile.Replace(dir, string.Empty).Replace("\\", ""); + var encryptFilePath = Path.Combine(encryptPath, assetBundleName); + AESForFileKit.EncryptFile(assetBundleFile, encryptFilePath, + CrazyZooConstant.admsie); + + File.Copy(encryptFilePath, Path.Combine(dir, assetBundleName), true); + } + } + + Directory.Delete(encryptPath, true); + } + + private static void BuildAssetBundleFileIndex(AssetBundleManifest manifest) + { + var dir = CrazyZooConstant.tbund; + var dirFile = $"{CrazyZooConstant.tbund}/../"; + + var filePath = Path.Combine(dirFile, CrazyZooConstant.zyzootx); + + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + + var filePaths = Directory.GetFiles(dir, $"*{CrazyZooConstant.setbun}", + SearchOption.TopDirectoryOnly); + + using var fileStream = new FileStream(filePath, FileMode.CreateNew); + + using var streamWriter = new StreamWriter(fileStream); + + var totalAssetBundlePath = $"{dir}/{CrazyZooConstant.undles}"; + + var totalAssetBundleManifestPath = $"{dir}/{CrazyZooConstant.lesest}"; + + var totalMD5 = MD5Kit.GetFileMD5(totalAssetBundlePath); + streamWriter.WriteLine(GetAssetBundleFileIndex(CrazyZooConstant.undles, totalMD5)); + + var manifestMD5 = MD5Kit.GetFileMD5(totalAssetBundleManifestPath); + streamWriter.WriteLine(GetAssetBundleFileIndex(CrazyZooConstant.lesest, + manifestMD5)); + foreach (var assetBundleFile in filePaths) + { + if (!assetBundleFile.EndsWith(".meta") && !assetBundleFile.Contains(".DS_Store")) + { + var fileMD5 = MD5Kit.GetFileMD5(assetBundleFile); + + var assetBundleName = assetBundleFile.Replace(dir, string.Empty).Replace("\\", ""); + + streamWriter.WriteLine(GetAssetBundleFileIndex(assetBundleName, fileMD5)); + } + } + } + + private static string GetAssetBundleFileIndex(string assetBundleName, string assetBundleFileMD5) + { + return $"{assetBundleName}{CrazyZooConstant.fgklpk}{assetBundleFileMD5}"; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs.meta b/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs.meta new file mode 100644 index 0000000..b38ac4d --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/BuildSome.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed953085dc79620428de22e21e047db9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs b/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs new file mode 100644 index 0000000..8753391 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs @@ -0,0 +1,222 @@ +using FairyGUI; +using System.IO; +using UnityEditor; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster.Editor +{ + public static class FGUIContollerConstantKit + { + private const string content = + @" +namespace FGUI.{0} +{ + public partial class className + { +{1} } +}"; + + private static Dictionary classDic = new(); + private static Dictionary constClassDic = new(); + + private static string C_DestFolderPath = + Application.dataPath + "/CrazyZoo/FGUI/ControlDefine/Common/"; + + private static string DestFolderPath = + Application.dataPath + "/CrazyZoo/FGUI/ControlDefine/Project/"; + + [MenuItem("Tools/CreateCtrl")] + public static void CreateAllControllerScripts() + { + UIPackage.RemoveAllPackages(); + + CreateControllerScripts(true); + CreateControllerScripts(false); + + UIPackage.RemoveAllPackages(); + var stage = GameObject.Find("Stage"); + if (stage != null) + { + Object.DestroyImmediate(stage); + } + + var stageCamera = GameObject.Find("Stage Camera"); + if (stageCamera != null) + { + Object.DestroyImmediate(stageCamera); + } + } + + private static void CreateControllerScripts(bool isCreateCommon) + { + classDic.Clear(); + constClassDic.Clear(); + + string[] ids = AssetDatabase.FindAssets("_fui t:textAsset"); + foreach (var item in ids) + { + string assetPath = AssetDatabase.GUIDToAssetPath(item); + int pos = assetPath.LastIndexOf("_fui"); + if (pos == -1) + continue; + + assetPath = assetPath.Substring(0, pos); + LoadOneUI(assetPath, isCreateCommon); + } + + CreateScripts(isCreateCommon); + } + + private static void CreateScripts(bool isCreateCommon) + { + if (isCreateCommon) + { + } + else + { + if (Directory.Exists(DestFolderPath)) + { + Directory.Delete(DestFolderPath, true); + } + + Directory.CreateDirectory(DestFolderPath); + } + + string startPre = isCreateCommon ? C_DestFolderPath : DestFolderPath; + foreach (var item in classDic) + { + if (item.Key.StartsWith(startPre)) + FileKit.CreateTxt(item.Key, item.Value, true); + } + + foreach (var item in constClassDic) + { + if (item.Key.StartsWith(startPre)) + FileKit.CreateTxt(item.Key, item.Value, true); + } + + if (isCreateCommon) + Debug.Log("[FGUIContollerCreateTool]生成通用界面控制器常量完成:" + startPre); + else + Debug.Log("[FGUIContollerCreateTool]生成项目界面控制器常量完成:" + startPre); + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + } + + private static void LoadOneUI(string resPath, bool isCreateCommon) + { + string objName = new FileInfo(Path.GetFullPath(resPath)).Name; + UIPackage pkg = UIPackage.GetByName(objName); + if (pkg == null) + { + pkg = UIPackage.AddPackage(resPath); + } + + foreach (var item in pkg.GetItems()) + { + if (item.type == PackageItemType.Component) + { + GComponent gComponent = null; + + var tmpGomponent = pkg.CreateObject(item.name); + gComponent = tmpGomponent as GComponent; + + if (gComponent == null) + { + DisposeGObject(tmpGomponent); + continue; + } + + string tmpPropertyStr = ""; + string constPropertyStr = ""; + List nameList = new List(); + foreach (var tmp in gComponent.Controllers) + { + nameList.Clear(); + for (int i = 0; i < tmp.pageCount; i++) + { + string name = tmp.GetPageName(i).Replace(" ", ""); + if (nameList.Contains(name)) + { + continue; + } + + nameList.Add(name); + + string summary = @" /// + /// {0}:{1} + /// + "; + summary = string.Format(summary, i, tmp.GetPageName(i)); + + tmpPropertyStr += summary; + constPropertyStr += summary; + string contName = tmp.name.Replace("cont_", ""); + contName = FirstLetterToUpper(contName); + tmpPropertyStr += string.Format("public int _{0}_{1} = {2};\r\n", contName, name, i); + constPropertyStr += string.Format("public const int {0}_{1} = {2};\r\n", contName, name, i); + } + } + + List controllers = gComponent.Controllers; + DisposeGObject(gComponent); + if (controllers.Count != 0) + { + if (isCreateCommon) + { + if (!pkg.name.StartsWith("C")) + { + continue; + } + } + else + { + if (pkg.name.StartsWith("C")) + { + continue; + } + } + + string objClassContent = content.Replace("{0}", pkg.name).Replace("{1}", tmpPropertyStr) + .Replace("className", item.name); + string constClassContent = content.Replace("{0}", pkg.name).Replace("{1}", constPropertyStr) + .Replace("className", item.name); + string prePath = pkg.name.StartsWith("C") ? C_DestFolderPath : DestFolderPath; + string path = prePath + pkg.name + "/" + item.name + "_AutoCreator.cs"; + string constPath = prePath + pkg.name + "/" + item.name + "_Const.cs"; + if (!classDic.ContainsKey(path)) + { + classDic.Add(path, objClassContent); + constClassDic.Add(constPath, constClassContent); + } + } + } + } + } + + private static void DisposeGObject(GObject gObject) + { + gObject.Dispose(); + if (gObject.displayObject != null) + { + if (gObject.displayObject.gameObject) + { + Object.Destroy(gObject.displayObject.gameObject); + } + } + } + + private static string FirstLetterToUpper(string str) + { + if (str == null) + return null; + + if (str.Length > 1) + return char.ToUpper(str[0]) + str.Substring(1); + + return str.ToUpper(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs.meta b/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs.meta new file mode 100644 index 0000000..179b8fd --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/FGUIContollerConstantKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81aeb2cc6bde11b47bce1e10f10a099e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs b/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs new file mode 100644 index 0000000..48603c1 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs @@ -0,0 +1,40 @@ +using System.IO; +using System.Text; +using UnityEngine; + +namespace ScrewsMaster.Editor +{ + public static class FileKit + { + public static void CreateTxt(string path, string Txt, bool IsCover = false, bool IsAssetPath = false) + { + if (IsAssetPath) + { + path = Application.dataPath.Replace("Assets", string.Empty) + path; + } + + if (!Directory.Exists(GetFullDiretoryPath(path))) + { + Directory.CreateDirectory(GetFullDiretoryPath(path)); + } + + if (File.Exists(path)) + { + if (!IsCover) + { + return; + } + + File.Delete(path); + } + + File.WriteAllText(path, Txt, new UTF8Encoding(false)); + } + + public static string GetFullDiretoryPath(string filePath) + { + string fileName = Path.GetFileName(filePath); + return filePath.Replace(fileName, string.Empty); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs.meta b/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs.meta new file mode 100644 index 0000000..8f5f230 --- /dev/null +++ b/Assets/CrazyZoo/Editor/ToolKit/FileKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfb22dd27fba6ca41ac694652c2c7abf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI.meta b/Assets/CrazyZoo/FGUI.meta new file mode 100644 index 0000000..c2012da --- /dev/null +++ b/Assets/CrazyZoo/FGUI.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9991148420ac46d9a69bd526959206ba +timeCreated: 1700452155 \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine.meta b/Assets/CrazyZoo/FGUI/ControlDefine.meta new file mode 100644 index 0000000..f68e22e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b962a30785ae4744c845c4e6010c442e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project.meta new file mode 100644 index 0000000..948139e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 42e46ce8651dd6c4eb74ac112ec61ce0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common.meta new file mode 100644 index 0000000..73e1ffb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e04e7726d602ab24fb5e4adf476aee5b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs new file mode 100644 index 0000000..d490bf2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_AdRevive + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs.meta new file mode 100644 index 0000000..17b8b19 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 960adcbd0ac8ac94e8e308cf087118db +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs new file mode 100644 index 0000000..1997b29 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_AdRevive + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs.meta new file mode 100644 index 0000000..55a89aa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_AdRevive_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 06b918462cc5a0e46899c4cfb41d67ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs new file mode 100644 index 0000000..061b5f0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_clo + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs.meta new file mode 100644 index 0000000..f6d5702 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c30d009ba584ccc40a36b56bcb7d8f78 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs new file mode 100644 index 0000000..5a225ce --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_clo + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs.meta new file mode 100644 index 0000000..054d7b2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_clo_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 56704fb66a529f54ba0af6ca678877b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs new file mode 100644 index 0000000..7d764d4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_close_new + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs.meta new file mode 100644 index 0000000..053c146 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 767d1fcbb33ab4f4e9b6fab574f419d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs new file mode 100644 index 0000000..d65b7eb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_close_new + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs.meta new file mode 100644 index 0000000..0ff5879 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_close_new_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2a22fb9653f73b45a43a375f9e430c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs new file mode 100644 index 0000000..a544bba --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_newClose + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs.meta new file mode 100644 index 0000000..cf4d22d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 878fd873bbebd7144912e89ae1309c68 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs new file mode 100644 index 0000000..109caa5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_newClose + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs.meta new file mode 100644 index 0000000..4cb9cbf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_newClose_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5221d0fc31731fd43bb9a3066a1c2f74 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs new file mode 100644 index 0000000..2ab0abd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_revive + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs.meta new file mode 100644 index 0000000..2327101 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a67ce34598df0234ca412fec2083e679 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs new file mode 100644 index 0000000..2bb652c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.A000_common +{ + public partial class btn_revive + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs.meta new file mode 100644 index 0000000..c0429c1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_revive_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51a008da78a37f8429751a186df49f27 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs new file mode 100644 index 0000000..1a53a2a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tab_record + { + /// + /// 0:none + /// + public int _Tab_none = 0; + /// + /// 1:tab + /// + public int _Tab_tab = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs.meta new file mode 100644 index 0000000..b4a6572 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86d902554d850c04094047f245957589 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs new file mode 100644 index 0000000..2fda189 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tab_record + { + /// + /// 0:none + /// + public const int Tab_none = 0; + /// + /// 1:tab + /// + public const int Tab_tab = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs.meta new file mode 100644 index 0000000..1997524 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tab_record_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 50112821465ef834083b8eb4cbef4a5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs new file mode 100644 index 0000000..5e22457 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tabad + { + /// + /// 0:blue + /// + public int _Color_blue = 0; + /// + /// 1:green + /// + public int _Color_green = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs.meta new file mode 100644 index 0000000..65d5455 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51addaf9ae830c549be5cf733b72e433 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs new file mode 100644 index 0000000..3a8a896 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tabad + { + /// + /// 0:blue + /// + public const int Color_blue = 0; + /// + /// 1:green + /// + public const int Color_green = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs.meta new file mode 100644 index 0000000..3c0dfea --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabad_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6a8a2105af269b748bbbf25e6b27b2f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs new file mode 100644 index 0000000..4d0da4b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tabwhite + { + /// + /// 0:gold + /// + public int _Btn_state_gold = 0; + /// + /// 1:money + /// + public int _Btn_state_money = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs.meta new file mode 100644 index 0000000..0086eb5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f8bae6f5a2faaa446a21ac5590c6036e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs new file mode 100644 index 0000000..0205e43 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.A000_common +{ + public partial class btn_tabwhite + { + /// + /// 0:gold + /// + public const int Btn_state_gold = 0; + /// + /// 1:money + /// + public const int Btn_state_money = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs.meta new file mode 100644 index 0000000..d8b83be --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/A000_common/btn_tabwhite_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d77cd3d278a5d24f8e89006316956b7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main.meta new file mode 100644 index 0000000..4d835f7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 55fbb3aeb911bf2468ffa0bd6927fa8c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs new file mode 100644 index 0000000..8389667 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G002_main +{ + public partial class btn_get_reward + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs.meta new file mode 100644 index 0000000..68a14fc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 263f6d5417d03264b90ef19d501c2d9e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs new file mode 100644 index 0000000..9c6a48b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G002_main +{ + public partial class btn_get_reward + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs.meta new file mode 100644 index 0000000..51ae203 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_get_reward_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0798c38a9fd04fe40bdee1431e9f2b5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs new file mode 100644 index 0000000..f2ce0b7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class btn_look_ad + { + /// + /// 0:can_look + /// + public int _Cool_down_can_look = 0; + /// + /// 1:canot_look + /// + public int _Cool_down_canot_look = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs.meta new file mode 100644 index 0000000..9e6c0dd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 310b84705c5a03a409c55f104bc66977 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs new file mode 100644 index 0000000..eefe82c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class btn_look_ad + { + /// + /// 0:can_look + /// + public const int Cool_down_can_look = 0; + /// + /// 1:canot_look + /// + public const int Cool_down_canot_look = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs.meta new file mode 100644 index 0000000..2b2aa3c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_look_ad_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15f19250e696bd747b2646d2f4140c89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs new file mode 100644 index 0000000..112238f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G002_main +{ + public partial class btn_question + { + /// + /// 0:faq + /// + public int _Btn_name_faq = 0; + /// + /// 1:sign + /// + public int _Btn_name_sign = 1; + /// + /// 2:setting + /// + public int _Btn_name_setting = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs.meta new file mode 100644 index 0000000..cf7265f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89530da4d53c478428406417aa3f5eed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs new file mode 100644 index 0000000..b71f559 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G002_main +{ + public partial class btn_question + { + /// + /// 0:faq + /// + public const int Btn_name_faq = 0; + /// + /// 1:sign + /// + public const int Btn_name_sign = 1; + /// + /// 2:setting + /// + public const int Btn_name_setting = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs.meta new file mode 100644 index 0000000..5369870 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_question_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e8dbb5308c96084aa8a742fe4269fe5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs new file mode 100644 index 0000000..e6a4b57 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs @@ -0,0 +1,39 @@ + +namespace FGUI.G002_main +{ + public partial class btn_quiz + { + /// + /// 0:color_1 + /// + public int _Color_color_1 = 0; + /// + /// 1:color_2 + /// + public int _Color_color_2 = 1; + /// + /// 2:color_3 + /// + public int _Color_color_3 = 2; + /// + /// 3:color_4 + /// + public int _Color_color_4 = 3; + /// + /// 4:color_5 + /// + public int _Color_color_5 = 4; + /// + /// 5:color_6 + /// + public int _Color_color_6 = 5; + /// + /// 0:none + /// + public int _White_none = 0; + /// + /// 1:white + /// + public int _White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs.meta new file mode 100644 index 0000000..c82788f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4cf054b2786d2e84faf9a634b231e6b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs new file mode 100644 index 0000000..be6289b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs @@ -0,0 +1,39 @@ + +namespace FGUI.G002_main +{ + public partial class btn_quiz + { + /// + /// 0:color_1 + /// + public const int Color_color_1 = 0; + /// + /// 1:color_2 + /// + public const int Color_color_2 = 1; + /// + /// 2:color_3 + /// + public const int Color_color_3 = 2; + /// + /// 3:color_4 + /// + public const int Color_color_4 = 3; + /// + /// 4:color_5 + /// + public const int Color_color_5 = 4; + /// + /// 5:color_6 + /// + public const int Color_color_6 = 5; + /// + /// 0:none + /// + public const int White_none = 0; + /// + /// 1:white + /// + public const int White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs.meta new file mode 100644 index 0000000..758d18e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_quiz_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48f63d2a5dd96e5449cca79140ab8223 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs new file mode 100644 index 0000000..ae4bb47 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G002_main +{ + public partial class btn_start + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs.meta new file mode 100644 index 0000000..cd2d3bf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 25031a243d51cf14a9f1a5f1cc2de02b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs new file mode 100644 index 0000000..b37d219 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G002_main +{ + public partial class btn_start + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs.meta new file mode 100644 index 0000000..9044d50 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/btn_start_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed336832dce0f2c45ba13f53cf3bf22b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs new file mode 100644 index 0000000..e5f9efe --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_box + { + /// + /// 0:none + /// + public int _White_none = 0; + /// + /// 1:white + /// + public int _White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs.meta new file mode 100644 index 0000000..b9f414c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 777b2e035ace9ba42a8967571f92b5af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs new file mode 100644 index 0000000..57322a5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_box + { + /// + /// 0:none + /// + public const int White_none = 0; + /// + /// 1:white + /// + public const int White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs.meta new file mode 100644 index 0000000..b61ca7f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_box_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d1675f58eafee674ebc1459410fe7956 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs new file mode 100644 index 0000000..690ea85 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_firstreward + { + /// + /// 0:box + /// + public int _State_box = 0; + /// + /// 1:page + /// + public int _State_page = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs.meta new file mode 100644 index 0000000..01b53df --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cdec83ccdc50529448b2a3db65569560 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs new file mode 100644 index 0000000..455fac1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_firstreward + { + /// + /// 0:box + /// + public const int State_box = 0; + /// + /// 1:page + /// + public const int State_page = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs.meta new file mode 100644 index 0000000..695495a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_firstreward_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6b0d6b3f12a6594f926413dc1181ce3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs new file mode 100644 index 0000000..1341922 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_main + { + /// + /// 0:none + /// + public int _White_none = 0; + /// + /// 1:white + /// + public int _White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs.meta new file mode 100644 index 0000000..f5662d9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e83404a6243605e40afab4f2bb3a1c66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs new file mode 100644 index 0000000..04757fa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G002_main +{ + public partial class com_main + { + /// + /// 0:none + /// + public const int White_none = 0; + /// + /// 1:white + /// + public const int White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs.meta new file mode 100644 index 0000000..6af7f83 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G002_main/com_main_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afb7fb48d81e99340bd21ae6c891193f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play.meta new file mode 100644 index 0000000..f5e639e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f6e8e4f5cf545704e9478d5ab4e5dd1c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs new file mode 100644 index 0000000..2218d9d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class SignInBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..2305dfe --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86f039fac57a31c41a22ce15ba295249 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs new file mode 100644 index 0000000..e5b2bf3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class SignInBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs.meta new file mode 100644 index 0000000..2af897c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/SignInBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e4122aa7edb49d340949dfd0cfc8d640 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs new file mode 100644 index 0000000..2df9fc3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_battle + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs.meta new file mode 100644 index 0000000..b370c4a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4586b8ea30594c4d8faebccdcf13f5b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs new file mode 100644 index 0000000..b036183 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_battle + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs.meta new file mode 100644 index 0000000..ee69591 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_battle_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3479d09fe6fbafd4da9eca50230e18f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs new file mode 100644 index 0000000..e3014a8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_cashout + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs.meta new file mode 100644 index 0000000..7b6c51a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 789a26904a3acb84cbaafeb770d4ac22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs new file mode 100644 index 0000000..bd58493 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_cashout + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs.meta new file mode 100644 index 0000000..c02a020 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_cashout_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 403b839202268734ca6d5dfd0221d639 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs new file mode 100644 index 0000000..de68bf5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_hall + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs.meta new file mode 100644 index 0000000..d620299 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 717d7dda0dd37b249964a7c8f5cc1849 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs new file mode 100644 index 0000000..32e7aa3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_hall + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs.meta new file mode 100644 index 0000000..6257689 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_hall_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d92cac2918d9a4d4ba6e7d37bf407729 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs new file mode 100644 index 0000000..0550c57 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G003_play +{ + public partial class btn_look_ad + { + /// + /// 0:can_look + /// + public int _Cool_down_can_look = 0; + /// + /// 1:canot_look + /// + public int _Cool_down_canot_look = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs.meta new file mode 100644 index 0000000..08a381a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9657998eb28bcef42b577ec3b911deda +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs new file mode 100644 index 0000000..8febe38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G003_play +{ + public partial class btn_look_ad + { + /// + /// 0:can_look + /// + public const int Cool_down_can_look = 0; + /// + /// 1:canot_look + /// + public const int Cool_down_canot_look = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs.meta new file mode 100644 index 0000000..53a58a2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_look_ad_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80219cf91f9c306469e77bfb16a498df +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs new file mode 100644 index 0000000..622b4f3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs @@ -0,0 +1,11 @@ + +namespace FGUI.G003_play +{ + public partial class btn_noads + { + /// + /// 0: + /// + public int _State_ = 0; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs.meta new file mode 100644 index 0000000..ef43bec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 34b4d418636ccd546b32f00fbbb2dd18 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs new file mode 100644 index 0000000..fd4643f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs @@ -0,0 +1,11 @@ + +namespace FGUI.G003_play +{ + public partial class btn_noads + { + /// + /// 0: + /// + public const int State_ = 0; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs.meta new file mode 100644 index 0000000..5d96213 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_noads_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3970f208d81839848be7466a54aa06ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs new file mode 100644 index 0000000..aa3f0ee --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_setting + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs.meta new file mode 100644 index 0000000..83ecacd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1818c5d96d270b4458883904e9197daf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs new file mode 100644 index 0000000..7e966dd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class btn_setting + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs.meta new file mode 100644 index 0000000..bc71bd5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/btn_setting_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2dbd3ec3ba0c83847826ff5f11cf3604 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs new file mode 100644 index 0000000..19b6abb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class com_prop + { + /// + /// 0:add + /// + public int _Prop_add = 0; + /// + /// 1:merge + /// + public int _Prop_merge = 1; + /// + /// 2:clean + /// + public int _Prop_clean = 2; + /// + /// 3:PayBox + /// + public int _Prop_PayBox = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs.meta new file mode 100644 index 0000000..c2b6898 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 829c258d318b4a043bff24221419c4e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs new file mode 100644 index 0000000..e8471fd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class com_prop + { + /// + /// 0:add + /// + public const int Prop_add = 0; + /// + /// 1:merge + /// + public const int Prop_merge = 1; + /// + /// 2:clean + /// + public const int Prop_clean = 2; + /// + /// 3:PayBox + /// + public const int Prop_PayBox = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs.meta new file mode 100644 index 0000000..f4d13f6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/com_prop_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9526e64ede7c3e2498576754e6999f02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs new file mode 100644 index 0000000..feb26ea --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G003_play +{ + public partial class new_topgold + { + /// + /// 0:0 + /// + public int _State_0 = 0; + /// + /// 1:1 + /// + public int _State_1 = 1; + /// + /// 2:2 + /// + public int _State_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs.meta new file mode 100644 index 0000000..c383760 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1099e256ea11f1f47bdafe7146aec474 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs new file mode 100644 index 0000000..c58cd77 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G003_play +{ + public partial class new_topgold + { + /// + /// 0:0 + /// + public const int State_0 = 0; + /// + /// 1:1 + /// + public const int State_1 = 1; + /// + /// 2:2 + /// + public const int State_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs.meta new file mode 100644 index 0000000..bbd4001 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/new_topgold_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca4a0ed5f8302a144b08f3eee9b61f96 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs new file mode 100644 index 0000000..d9d95c0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class sheep_buyitem + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs.meta new file mode 100644 index 0000000..864ec37 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 267b3211cd8849545b0321217da26db8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs new file mode 100644 index 0000000..fc8b3f1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G003_play +{ + public partial class sheep_buyitem + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs.meta new file mode 100644 index 0000000..a59a407 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G003_play/sheep_buyitem_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0c2c3cc5456af7e489dc3f6d6af1520a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview.meta new file mode 100644 index 0000000..de143f9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7a6b6d0f36a113341b66c882c598aa0b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs new file mode 100644 index 0000000..ba8b580 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_cashout + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs.meta new file mode 100644 index 0000000..a138c27 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cadccfd36289a9f44b390bd33f39bcfe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs new file mode 100644 index 0000000..999fd7d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_cashout + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs.meta new file mode 100644 index 0000000..694a125 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_cashout_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 265571fddbee2cb4fa602786204603f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs new file mode 100644 index 0000000..d360247 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_icon + { + /// + /// 0:none + /// + public int _State_none = 0; + /// + /// 1:ready + /// + public int _State_ready = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs.meta new file mode 100644 index 0000000..5620d8a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba08aa58f08b69c4d81bf4cbc97f431f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs new file mode 100644 index 0000000..c33a68d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_icon + { + /// + /// 0:none + /// + public const int State_none = 0; + /// + /// 1:ready + /// + public const int State_ready = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs.meta new file mode 100644 index 0000000..469f2d0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_icon_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 683a98b8b5df000489390cdcf38ea91a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs new file mode 100644 index 0000000..ac74bbb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_type + { + /// + /// 0:news + /// + public int _Type_news = 0; + /// + /// 1:games + /// + public int _Type_games = 1; + /// + /// 2:hot + /// + public int _Type_hot = 2; + /// + /// 0:none + /// + public int _Tab_none = 0; + /// + /// 1:tab + /// + public int _Tab_tab = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs.meta new file mode 100644 index 0000000..b8fdb52 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4454e6871a66df143be601a3e1aa25b1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs new file mode 100644 index 0000000..b7e2cd7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G004_webview +{ + public partial class btn_type + { + /// + /// 0:news + /// + public const int Type_news = 0; + /// + /// 1:games + /// + public const int Type_games = 1; + /// + /// 2:hot + /// + public const int Type_hot = 2; + /// + /// 0:none + /// + public const int Tab_none = 0; + /// + /// 1:tab + /// + public const int Tab_tab = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs.meta new file mode 100644 index 0000000..70fcae2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G004_webview/btn_type_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 548ecb1edff2dc140bd211d97817b0ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu.meta new file mode 100644 index 0000000..fae02b0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f50e39612693bc9419b93ca89e9bf9c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs new file mode 100644 index 0000000..b3cf84a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_edit + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs.meta new file mode 100644 index 0000000..a25ca84 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 56ffb3618a9eab847b54a574a01b31ed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs new file mode 100644 index 0000000..e59713e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_edit + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs.meta new file mode 100644 index 0000000..43797f1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_edit_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3efca85a7c725c4f8a0ca23e9d2b974 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs new file mode 100644 index 0000000..6513d18 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_img + { + /// + /// 0:none + /// + public int _Select_none = 0; + /// + /// 1:select + /// + public int _Select_select = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs.meta new file mode 100644 index 0000000..ab58c36 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e895ce6f74e67cb41abeef8b40c22238 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs new file mode 100644 index 0000000..d13f88e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_img + { + /// + /// 0:none + /// + public const int Select_none = 0; + /// + /// 1:select + /// + public const int Select_select = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs.meta new file mode 100644 index 0000000..8db086c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_img_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca4eac9574c6e564083aacfb4c74909f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs new file mode 100644 index 0000000..df99417 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_lang + { + /// + /// 0:none + /// + public int _Btn_none = 0; + /// + /// 1:select + /// + public int _Btn_select = 1; + /// + /// 0:_0 + /// + public int _Btn_state__0 = 0; + /// + /// 1:_1 + /// + public int _Btn_state__1 = 1; + /// + /// 2:_2 + /// + public int _Btn_state__2 = 2; + /// + /// 3:_3 + /// + public int _Btn_state__3 = 3; + /// + /// 4:_4 + /// + public int _Btn_state__4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs.meta new file mode 100644 index 0000000..f60be7d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0cd1b320d7a701d44a6636a463818e63 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs new file mode 100644 index 0000000..9278fd4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_lang + { + /// + /// 0:none + /// + public const int Btn_none = 0; + /// + /// 1:select + /// + public const int Btn_select = 1; + /// + /// 0:_0 + /// + public const int Btn_state__0 = 0; + /// + /// 1:_1 + /// + public const int Btn_state__1 = 1; + /// + /// 2:_2 + /// + public const int Btn_state__2 = 2; + /// + /// 3:_3 + /// + public const int Btn_state__3 = 3; + /// + /// 4:_4 + /// + public const int Btn_state__4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs.meta new file mode 100644 index 0000000..76e71d6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_lang_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fac91c1f821b3fc47899fb5eeed9644c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs new file mode 100644 index 0000000..d1be8d1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_switch_music + { + /// + /// 0:off + /// + public int _Button_off = 0; + /// + /// 1:on + /// + public int _Button_on = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs.meta new file mode 100644 index 0000000..28c4ce3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ab864807560606b4f84b9c87aa835603 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs new file mode 100644 index 0000000..018cb86 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_switch_music + { + /// + /// 0:off + /// + public const int Button_off = 0; + /// + /// 1:on + /// + public const int Button_on = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs.meta new file mode 100644 index 0000000..d5f8192 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_music_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 56b031483376bf54aa754efa6e195c67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs new file mode 100644 index 0000000..e87e677 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_switch_sound + { + /// + /// 0:off + /// + public int _Button_off = 0; + /// + /// 1:on + /// + public int _Button_on = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs.meta new file mode 100644 index 0000000..2dc14ce --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 085fcd65c7533e84da760ca266b8007c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs new file mode 100644 index 0000000..dee6cf5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class btn_switch_sound + { + /// + /// 0:off + /// + public const int Button_off = 0; + /// + /// 1:on + /// + public const int Button_on = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs.meta new file mode 100644 index 0000000..8138113 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/btn_switch_sound_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0c8b553a4c95cce4d9c6752715927b01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs new file mode 100644 index 0000000..d765221 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class com_menu + { + /// + /// 0:a + /// + public int _Switchgift_a = 0; + /// + /// 1:b + /// + public int _Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs.meta new file mode 100644 index 0000000..0d8a83c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31f44214ebfe506458ce4e9cea16f569 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs new file mode 100644 index 0000000..56fbc35 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G006_menu +{ + public partial class com_menu + { + /// + /// 0:a + /// + public const int Switchgift_a = 0; + /// + /// 1:b + /// + public const int Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs.meta new file mode 100644 index 0000000..6ec45c4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G006_menu/com_menu_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9f5093d1cee520045907a11d8007eb7b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup.meta new file mode 100644 index 0000000..9fc1335 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a614f9b90d57152439b67efdc32e9369 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs new file mode 100644 index 0000000..dcff183 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_comfirmar + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs.meta new file mode 100644 index 0000000..2944570 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ba207a2307a83d48befe222c59ed888 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs new file mode 100644 index 0000000..8fa1e59 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_comfirmar + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs.meta new file mode 100644 index 0000000..fcad1e8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_comfirmar_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9792584ef0c45824db17bdee798ed93c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs new file mode 100644 index 0000000..ee2994b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_confirm + { + /// + /// 0:default + /// + public int _Country_default = 0; + /// + /// 1:ru + /// + public int _Country_ru = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs.meta new file mode 100644 index 0000000..e19c967 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 492e9628855d20645918cefb8a174950 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs new file mode 100644 index 0000000..1113789 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_confirm + { + /// + /// 0:default + /// + public const int Country_default = 0; + /// + /// 1:ru + /// + public const int Country_ru = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs.meta new file mode 100644 index 0000000..c19bd86 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_confirm_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 144cc923d047c684ebfe115aeb0443f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs new file mode 100644 index 0000000..8bbd203 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_pay + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs.meta new file mode 100644 index 0000000..40144e3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 076f3462497d5fb43935a4dcd64252b1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs new file mode 100644 index 0000000..a00e1d5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_pay + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs.meta new file mode 100644 index 0000000..4ce4dd8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_pay_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0582526a6b459bd42aa94ec47f76a55a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs new file mode 100644 index 0000000..a112520 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_watch + { + /// + /// 0:none + /// + public int _Show_cd_none = 0; + /// + /// 1:cd + /// + public int _Show_cd_cd = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs.meta new file mode 100644 index 0000000..97db210 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e920aed18d8f2348a224c0ecce633ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs new file mode 100644 index 0000000..b33e27a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class btn_watch + { + /// + /// 0:none + /// + public const int Show_cd_none = 0; + /// + /// 1:cd + /// + public const int Show_cd_cd = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs.meta new file mode 100644 index 0000000..a305920 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/btn_watch_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4470e00f5263b3e4690cff65bbc7ae0c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs new file mode 100644 index 0000000..41092fe --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs @@ -0,0 +1,55 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_confirm + { + /// + /// 0:enter + /// + public int _State_enter = 0; + /// + /// 1:confirm + /// + public int _State_confirm = 1; + /// + /// 2:task + /// + public int _State_task = 2; + /// + /// 3:query + /// + public int _State_query = 3; + /// + /// 4:step + /// + public int _State_step = 4; + /// + /// 5:level + /// + public int _State_level = 5; + /// + /// 0:ready + /// + public int _Confirm_ready = 0; + /// + /// 1:none + /// + public int _Confirm_none = 1; + /// + /// 0:pt + /// + public int _Lang_pt = 0; + /// + /// 1:en + /// + public int _Lang_en = 1; + /// + /// 0:false + /// + public int _Show_pay_false = 0; + /// + /// 1:true + /// + public int _Show_pay_true = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs.meta new file mode 100644 index 0000000..cbd8a24 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abdce4b34dafab14dbd4657bd6875e5d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs new file mode 100644 index 0000000..0ef9c9e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs @@ -0,0 +1,55 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_confirm + { + /// + /// 0:enter + /// + public const int State_enter = 0; + /// + /// 1:confirm + /// + public const int State_confirm = 1; + /// + /// 2:task + /// + public const int State_task = 2; + /// + /// 3:query + /// + public const int State_query = 3; + /// + /// 4:step + /// + public const int State_step = 4; + /// + /// 5:level + /// + public const int State_level = 5; + /// + /// 0:ready + /// + public const int Confirm_ready = 0; + /// + /// 1:none + /// + public const int Confirm_none = 1; + /// + /// 0:pt + /// + public const int Lang_pt = 0; + /// + /// 1:en + /// + public const int Lang_en = 1; + /// + /// 0:false + /// + public const int Show_pay_false = 0; + /// + /// 1:true + /// + public const int Show_pay_true = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs.meta new file mode 100644 index 0000000..03cea65 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_confirm_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0989d43f6b801644b4fab681fde243d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs new file mode 100644 index 0000000..8c5ed38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_enter + { + /// + /// 0:email + /// + public int _Type_email = 0; + /// + /// 1:phone + /// + public int _Type_phone = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs.meta new file mode 100644 index 0000000..28f562e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4dff365aec8785944b277a61539aef52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs new file mode 100644 index 0000000..29c279c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_enter + { + /// + /// 0:email + /// + public const int Type_email = 0; + /// + /// 1:phone + /// + public const int Type_phone = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs.meta new file mode 100644 index 0000000..fde4888 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_enter_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 200a99e54dc9d8444a1f804b63a5aa76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs new file mode 100644 index 0000000..8631d92 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_info + { + /// + /// 0:default + /// + public int _Counrty_default = 0; + /// + /// 1:ru + /// + public int _Counrty_ru = 1; + /// + /// 2:pt + /// + public int _Counrty_pt = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs.meta new file mode 100644 index 0000000..413292d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4aa8215f9ac970e42bb48131f09c2354 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs new file mode 100644 index 0000000..cf429f9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_info + { + /// + /// 0:default + /// + public const int Counrty_default = 0; + /// + /// 1:ru + /// + public const int Counrty_ru = 1; + /// + /// 2:pt + /// + public const int Counrty_pt = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs.meta new file mode 100644 index 0000000..be46913 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_info_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3932f4ef24fc3214f83a0565e883584f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs new file mode 100644 index 0000000..61fe5e2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs @@ -0,0 +1,31 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_rank + { + /// + /// 0:speeding + /// + public int _Content1_speeding = 0; + /// + /// 1:complete + /// + public int _Content1_complete = 1; + /// + /// 0:speeding + /// + public int _Content2_speeding = 0; + /// + /// 1:complete + /// + public int _Content2_complete = 1; + /// + /// 0:speeding + /// + public int _Content3_speeding = 0; + /// + /// 1:complete + /// + public int _Content3_complete = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs.meta new file mode 100644 index 0000000..d207109 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d724978ca257984ebfdf90e28bffb6a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs new file mode 100644 index 0000000..3000125 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs @@ -0,0 +1,31 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_rank + { + /// + /// 0:speeding + /// + public const int Content1_speeding = 0; + /// + /// 1:complete + /// + public const int Content1_complete = 1; + /// + /// 0:speeding + /// + public const int Content2_speeding = 0; + /// + /// 1:complete + /// + public const int Content2_complete = 1; + /// + /// 0:speeding + /// + public const int Content3_speeding = 0; + /// + /// 1:complete + /// + public const int Content3_complete = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs.meta new file mode 100644 index 0000000..c44da49 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_rank_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2117ccc2e61757e438cdec3d710de3cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs new file mode 100644 index 0000000..94829b3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_record + { + /// + /// 0:none + /// + public int _Show_none = 0; + /// + /// 1:list + /// + public int _Show_list = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs.meta new file mode 100644 index 0000000..49d6127 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac4c13b67c3852743980b7c1a9296a23 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs new file mode 100644 index 0000000..33b258a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_record + { + /// + /// 0:none + /// + public const int Show_none = 0; + /// + /// 1:list + /// + public const int Show_list = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs.meta new file mode 100644 index 0000000..083775c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_record_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3afa20ba6333fc74688a4a3b47b1876a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs new file mode 100644 index 0000000..7348d31 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_step + { + /// + /// 0:en + /// + public int _Lang_en = 0; + /// + /// 1:pt + /// + public int _Lang_pt = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs.meta new file mode 100644 index 0000000..0e64712 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 754c442da09d87640959bc350f87c5aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs new file mode 100644 index 0000000..075ef40 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_step + { + /// + /// 0:en + /// + public const int Lang_en = 0; + /// + /// 1:pt + /// + public const int Lang_pt = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs.meta new file mode 100644 index 0000000..96c9fdd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_step_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1e102d5edfe14aa42abd43096f361a80 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs new file mode 100644 index 0000000..bc86af8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_task + { + /// + /// 0:con_1 + /// + public int _Process_con_1 = 0; + /// + /// 1:con_2 + /// + public int _Process_con_2 = 1; + /// + /// 0:pt + /// + public int _Lang_pt = 0; + /// + /// 1:en + /// + public int _Lang_en = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs.meta new file mode 100644 index 0000000..b0a7488 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa25ddb27fda45445ac5630679c9a7a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs new file mode 100644 index 0000000..5095807 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_task + { + /// + /// 0:con_1 + /// + public const int Process_con_1 = 0; + /// + /// 1:con_2 + /// + public const int Process_con_2 = 1; + /// + /// 0:pt + /// + public const int Lang_pt = 0; + /// + /// 1:en + /// + public const int Lang_en = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs.meta new file mode 100644 index 0000000..2e747f2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_task_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5126838a692d394585ba7688ca91970 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs new file mode 100644 index 0000000..534fe43 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_trans + { + /// + /// 0:default + /// + public int _Country_default = 0; + /// + /// 1:ru + /// + public int _Country_ru = 1; + /// + /// 2:pt + /// + public int _Country_pt = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs.meta new file mode 100644 index 0000000..7dda3e7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed873b762c1e0c949ad8765c9db4cd59 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs new file mode 100644 index 0000000..e21de35 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class com_trans + { + /// + /// 0:default + /// + public const int Country_default = 0; + /// + /// 1:ru + /// + public const int Country_ru = 1; + /// + /// 2:pt + /// + public const int Country_pt = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs.meta new file mode 100644 index 0000000..fca1229 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/com_trans_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 25c59ad20e980bd4d97b12932c7e67ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs new file mode 100644 index 0000000..a1bf0aa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class level_btn + { + /// + /// 0:0 + /// + public int _Btn_state_0 = 0; + /// + /// 1:1 + /// + public int _Btn_state_1 = 1; + /// + /// 2:2 + /// + public int _Btn_state_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs.meta new file mode 100644 index 0000000..2a767f4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0fb1d90937cc7c6429f135f3ee520b85 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs new file mode 100644 index 0000000..a19e22f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G007_makeup +{ + public partial class level_btn + { + /// + /// 0:0 + /// + public const int Btn_state_0 = 0; + /// + /// 1:1 + /// + public const int Btn_state_1 = 1; + /// + /// 2:2 + /// + public const int Btn_state_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs.meta new file mode 100644 index 0000000..22c2420 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G007_makeup/level_btn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b134915025d907b439071251e0822dd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward.meta new file mode 100644 index 0000000..516d646 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ed4e7dd6ee5fd254b961f776d1b98bfc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs new file mode 100644 index 0000000..c0af32e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class btn_buypack + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs.meta new file mode 100644 index 0000000..9ef1b50 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21cc4b378fe7b13499e8f0a8a746eb3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs new file mode 100644 index 0000000..71eb7c3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class btn_buypack + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs.meta new file mode 100644 index 0000000..15c587c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_buypack_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 013105ded1f76a4448726ab6c6c78894 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs new file mode 100644 index 0000000..52e959c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class btn_cash_1 + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs.meta new file mode 100644 index 0000000..389c8fa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b508927376c84e84e8fbb303abf771d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs new file mode 100644 index 0000000..9985f2c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class btn_cash_1 + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs.meta new file mode 100644 index 0000000..d49476e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/btn_cash_1_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0f214c06f75f24244bade83b74f59ff8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs new file mode 100644 index 0000000..11a801c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class com_lvsuccess + { + /// + /// 0:win + /// + public int _State_win = 0; + /// + /// 1:lose + /// + public int _State_lose = 1; + /// + /// 0:a + /// + public int _Switchgift_a = 0; + /// + /// 1:b + /// + public int _Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs.meta new file mode 100644 index 0000000..0f6719e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 575ee64bcacedff4a835fc605f7894c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs new file mode 100644 index 0000000..eabc838 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class com_lvsuccess + { + /// + /// 0:win + /// + public const int State_win = 0; + /// + /// 1:lose + /// + public const int State_lose = 1; + /// + /// 0:a + /// + public const int Switchgift_a = 0; + /// + /// 1:b + /// + public const int Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs.meta new file mode 100644 index 0000000..7a286ac --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_lvsuccess_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15f356bfdf9a7f94b801949086a24b7f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs new file mode 100644 index 0000000..4f7b6e2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G008_reward +{ + public partial class com_revive + { + /// + /// 0:none + /// + public int _Iswacth_none = 0; + /// + /// 1:watchAd + /// + public int _Iswacth_watchAd = 1; + /// + /// 2:UseCoin + /// + public int _Iswacth_UseCoin = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs.meta new file mode 100644 index 0000000..44a5fd6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bbb510e9936fec44aa5b3fbe5aead8a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs new file mode 100644 index 0000000..a1067e6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G008_reward +{ + public partial class com_revive + { + /// + /// 0:none + /// + public const int Iswacth_none = 0; + /// + /// 1:watchAd + /// + public const int Iswacth_watchAd = 1; + /// + /// 2:UseCoin + /// + public const int Iswacth_UseCoin = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs.meta new file mode 100644 index 0000000..f7b99fd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_revive_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f96888e894d491449dd681ba442ea17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs new file mode 100644 index 0000000..4dbaba7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class com_reward + { + /// + /// 0:ad + /// + public int _Collect_ad = 0; + /// + /// 1:none + /// + public int _Collect_none = 1; + /// + /// 0:none + /// + public int _White_none = 0; + /// + /// 1:white + /// + public int _White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs.meta new file mode 100644 index 0000000..d0a4ccb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21bd4218361432c4a80ce731ed3f56a2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs new file mode 100644 index 0000000..4908a82 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G008_reward +{ + public partial class com_reward + { + /// + /// 0:ad + /// + public const int Collect_ad = 0; + /// + /// 1:none + /// + public const int Collect_none = 1; + /// + /// 0:none + /// + public const int White_none = 0; + /// + /// 1:white + /// + public const int White_white = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs.meta new file mode 100644 index 0000000..8a0c43f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_reward_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fef56069e2132a0488ffd244d876b4c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs new file mode 100644 index 0000000..0980c15 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G008_reward +{ + public partial class com_rewardbox + { + /// + /// 0:a + /// + public int _Switchgift_a = 0; + /// + /// 1:b + /// + public int _Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs.meta new file mode 100644 index 0000000..d7b10ec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f8532d18637ee634e9d032499486da62 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs new file mode 100644 index 0000000..4845454 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G008_reward +{ + public partial class com_rewardbox + { + /// + /// 0:a + /// + public const int Switchgift_a = 0; + /// + /// 1:b + /// + public const int Switchgift_b = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs.meta new file mode 100644 index 0000000..a5470f2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G008_reward/com_rewardbox_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4f31d44636c02147860685d95076743 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video.meta new file mode 100644 index 0000000..9101a90 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aa9def61dd93e134093399d17fcf9d55 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs new file mode 100644 index 0000000..fb147e5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_AdRevive + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs.meta new file mode 100644 index 0000000..06ccc6e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8f976247011d7743add80fb841d3309 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs new file mode 100644 index 0000000..12dc4d3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_AdRevive + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs.meta new file mode 100644 index 0000000..7c73d96 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_AdRevive_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 72e08da6475312b499b6d4f52c02ea56 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs new file mode 100644 index 0000000..65f8da8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_buypass + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs.meta new file mode 100644 index 0000000..c6fef78 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 985edce5285cb26418a075f903c7bb7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs new file mode 100644 index 0000000..3c99816 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_buypass + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs.meta new file mode 100644 index 0000000..0ba101e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_buypass_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 02185f918b41b25489caaa9f39e5ca93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs new file mode 100644 index 0000000..43d9f3f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_null + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs.meta new file mode 100644 index 0000000..a30f06a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0032ec5a4dd5e64b92a213d226fd2ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs new file mode 100644 index 0000000..32f6ed0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_null + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs.meta new file mode 100644 index 0000000..387400c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_null_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1011473398af3f844bdf84fca04d736d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs new file mode 100644 index 0000000..d04177a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_showtips + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs.meta new file mode 100644 index 0000000..49c2e72 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5745a0c21f709584d813652efb472072 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs new file mode 100644 index 0000000..498426f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G009_video +{ + public partial class btn_showtips + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs.meta new file mode 100644 index 0000000..7b771f2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_showtips_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c94382b432f03f4cb01306df2383927 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs new file mode 100644 index 0000000..13cb197 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G009_video +{ + public partial class btn_task + { + /// + /// 0:0 + /// + public int _State_0 = 0; + /// + /// 1:1 + /// + public int _State_1 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs.meta new file mode 100644 index 0000000..71589d7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 788918a155d42584cb10cf2f65d4480d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs new file mode 100644 index 0000000..ed47c02 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G009_video +{ + public partial class btn_task + { + /// + /// 0:0 + /// + public const int State_0 = 0; + /// + /// 1:1 + /// + public const int State_1 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs.meta new file mode 100644 index 0000000..3ed104a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/btn_task_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c1aef7903fdd9244b523aac2a6ed596 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs new file mode 100644 index 0000000..5ae9531 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G009_video +{ + public partial class com_gettaskreward + { + /// + /// 0:A + /// + public int _Switchgift_A = 0; + /// + /// 1:B + /// + public int _Switchgift_B = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs.meta new file mode 100644 index 0000000..67675e1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b433b01b9dd5f44686cfc942e04521d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs new file mode 100644 index 0000000..d02353e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G009_video +{ + public partial class com_gettaskreward + { + /// + /// 0:A + /// + public const int Switchgift_A = 0; + /// + /// 1:B + /// + public const int Switchgift_B = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs.meta new file mode 100644 index 0000000..5940bd0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_gettaskreward_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3bcb1517b96de9f43b5a5dd930686f7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs new file mode 100644 index 0000000..965191e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G009_video +{ + public partial class com_passitem + { + /// + /// 0:0 + /// + public int _State_0 = 0; + /// + /// 1:1 + /// + public int _State_1 = 1; + /// + /// 2:2 + /// + public int _State_2 = 2; + /// + /// 3:3 + /// + public int _State_3 = 3; + /// + /// 0:empty + /// + public int _Full_empty = 0; + /// + /// 1:half + /// + public int _Full_half = 1; + /// + /// 2:full + /// + public int _Full_full = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs.meta new file mode 100644 index 0000000..3695a4a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03c24b3e360d00b4587ffad44532ea0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs new file mode 100644 index 0000000..525fb38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G009_video +{ + public partial class com_passitem + { + /// + /// 0:0 + /// + public const int State_0 = 0; + /// + /// 1:1 + /// + public const int State_1 = 1; + /// + /// 2:2 + /// + public const int State_2 = 2; + /// + /// 3:3 + /// + public const int State_3 = 3; + /// + /// 0:empty + /// + public const int Full_empty = 0; + /// + /// 1:half + /// + public const int Full_half = 1; + /// + /// 2:full + /// + public const int Full_full = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs.meta new file mode 100644 index 0000000..d4331ae --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passitem_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45f77632da809bf4b85f286d2bc6237f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs new file mode 100644 index 0000000..807c0bf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G009_video +{ + public partial class com_passreward + { + /// + /// 0:0 + /// + public int _Type_0 = 0; + /// + /// 1:1 + /// + public int _Type_1 = 1; + /// + /// 0:0 + /// + public int _State_0 = 0; + /// + /// 1:1 + /// + public int _State_1 = 1; + /// + /// 2:2 + /// + public int _State_2 = 2; + /// + /// 3:3 + /// + public int _State_3 = 3; + /// + /// 4:4 + /// + public int _State_4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs.meta new file mode 100644 index 0000000..4191d0a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b0ccfeb7ce5e77488f676d06c517a88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs new file mode 100644 index 0000000..8abb896 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs @@ -0,0 +1,35 @@ + +namespace FGUI.G009_video +{ + public partial class com_passreward + { + /// + /// 0:0 + /// + public const int Type_0 = 0; + /// + /// 1:1 + /// + public const int Type_1 = 1; + /// + /// 0:0 + /// + public const int State_0 = 0; + /// + /// 1:1 + /// + public const int State_1 = 1; + /// + /// 2:2 + /// + public const int State_2 = 2; + /// + /// 3:3 + /// + public const int State_3 = 3; + /// + /// 4:4 + /// + public const int State_4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs.meta new file mode 100644 index 0000000..f9f8c1b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_passreward_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c9e34cc31463354faef2d33fd6ed1d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs new file mode 100644 index 0000000..f20b4f1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G009_video +{ + public partial class com_toptab + { + /// + /// 0:0 + /// + public int _Tab_0 = 0; + /// + /// 1:1 + /// + public int _Tab_1 = 1; + /// + /// 2:2 + /// + public int _Tab_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs.meta new file mode 100644 index 0000000..865297e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c232d33da3297554384a46fe429e8981 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs new file mode 100644 index 0000000..679c34b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G009_video +{ + public partial class com_toptab + { + /// + /// 0:0 + /// + public const int Tab_0 = 0; + /// + /// 1:1 + /// + public const int Tab_1 = 1; + /// + /// 2:2 + /// + public const int Tab_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs.meta new file mode 100644 index 0000000..c991989 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G009_video/com_toptab_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd4201f8ceed56f4091107193ef26316 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward.meta new file mode 100644 index 0000000..be43542 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c760ff0586bae794bb043f9dcbce54e6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs new file mode 100644 index 0000000..9d0d6c8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G012_openReward +{ + public partial class btn_buy + { + /// + /// 0:0 + /// + public int _Can_buy_0 = 0; + /// + /// 1:1 + /// + public int _Can_buy_1 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs.meta new file mode 100644 index 0000000..6fe5f46 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d98efd16fd9aeab4daa9f5320f88a85a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs new file mode 100644 index 0000000..99281e3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G012_openReward +{ + public partial class btn_buy + { + /// + /// 0:0 + /// + public const int Can_buy_0 = 0; + /// + /// 1:1 + /// + public const int Can_buy_1 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs.meta new file mode 100644 index 0000000..0c0cd3f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/btn_buy_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3bb25eee95eb4ff40949cd74c221d45f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs new file mode 100644 index 0000000..20add19 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G012_openReward +{ + public partial class buygold_item + { + /// + /// 0:0 + /// + public int _Index_0 = 0; + /// + /// 1:1 + /// + public int _Index_1 = 1; + /// + /// 2:2 + /// + public int _Index_2 = 2; + /// + /// 3:3 + /// + public int _Index_3 = 3; + /// + /// 4:4 + /// + public int _Index_4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs.meta new file mode 100644 index 0000000..5e00785 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3a74cc9a122b3824f9a89ff6f10dcd22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs new file mode 100644 index 0000000..e5b681a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G012_openReward +{ + public partial class buygold_item + { + /// + /// 0:0 + /// + public const int Index_0 = 0; + /// + /// 1:1 + /// + public const int Index_1 = 1; + /// + /// 2:2 + /// + public const int Index_2 = 2; + /// + /// 3:3 + /// + public const int Index_3 = 3; + /// + /// 4:4 + /// + public const int Index_4 = 4; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs.meta new file mode 100644 index 0000000..e34e3c7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/buygold_item_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22c69350636007a4fa617ece3576fa7e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs new file mode 100644 index 0000000..249ecee --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G012_openReward +{ + public partial class com_card + { + /// + /// 0:default + /// + public int _Country_default = 0; + /// + /// 1:ru + /// + public int _Country_ru = 1; + /// + /// 0:en + /// + public int _Lang_en = 0; + /// + /// 1:pt + /// + public int _Lang_pt = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs.meta new file mode 100644 index 0000000..f782fe6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3d912c1a32840a4ab01fbd9931ca8a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs new file mode 100644 index 0000000..743fc04 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G012_openReward +{ + public partial class com_card + { + /// + /// 0:default + /// + public const int Country_default = 0; + /// + /// 1:ru + /// + public const int Country_ru = 1; + /// + /// 0:en + /// + public const int Lang_en = 0; + /// + /// 1:pt + /// + public const int Lang_pt = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs.meta new file mode 100644 index 0000000..0e3256f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G012_openReward/com_card_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97809b5fa15a59b4c95fbf1ed8345264 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn.meta new file mode 100644 index 0000000..86ef583 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f9f153bc6f2ebc047994b793d7d5ad3d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs new file mode 100644 index 0000000..14f0ef7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G014_SignIn +{ + public partial class btn_sign + { + /// + /// 0:Received + /// + public int _State_Received = 0; + /// + /// 1:Current + /// + public int _State_Current = 1; + /// + /// 2:Unreceived + /// + public int _State_Unreceived = 2; + /// + /// 0:1 + /// + public int _Style_1 = 0; + /// + /// 1:2 + /// + public int _Style_2 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs.meta new file mode 100644 index 0000000..002d8d8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95bfd39f101cd954190de56209de8e4d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs new file mode 100644 index 0000000..05ba94a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs @@ -0,0 +1,27 @@ + +namespace FGUI.G014_SignIn +{ + public partial class btn_sign + { + /// + /// 0:Received + /// + public const int State_Received = 0; + /// + /// 1:Current + /// + public const int State_Current = 1; + /// + /// 2:Unreceived + /// + public const int State_Unreceived = 2; + /// + /// 0:1 + /// + public const int Style_1 = 0; + /// + /// 1:2 + /// + public const int Style_2 = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs.meta new file mode 100644 index 0000000..3473434 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G014_SignIn/btn_sign_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6b0773ee0845fa4cb87d7614aa8afb5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome.meta new file mode 100644 index 0000000..bb0db29 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a5360bfb40444f74aa78cc80f5f60689 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs new file mode 100644 index 0000000..262124b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G018_GameHome +{ + public partial class GameHome + { + /// + /// 0:simple + /// + public int _Mode_simple = 0; + /// + /// 1:difficult + /// + public int _Mode_difficult = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs.meta new file mode 100644 index 0000000..06b9d25 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f41c3e3bf6d47884aa48cd544e133974 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs new file mode 100644 index 0000000..b50ebf5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G018_GameHome +{ + public partial class GameHome + { + /// + /// 0:simple + /// + public const int Mode_simple = 0; + /// + /// 1:difficult + /// + public const int Mode_difficult = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs.meta new file mode 100644 index 0000000..26f6150 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/GameHome_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f8822f96127324e4fad2ae136fec3799 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs new file mode 100644 index 0000000..7ab4e53 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class LeftBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..de3679d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37a07c37d2be37b46bc1cb08b2dedfd1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs new file mode 100644 index 0000000..7c3dcec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class LeftBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs.meta new file mode 100644 index 0000000..b7ac235 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LeftBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bbbeb67e6e350e149ade5ea59746afe7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs new file mode 100644 index 0000000..3edb7d6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class LevelBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..e6759e9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0449adfc4bef9a40b3ecebdd7ff4a9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs new file mode 100644 index 0000000..0a2b9c0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class LevelBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs.meta new file mode 100644 index 0000000..f749257 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/LevelBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 736141ed0b0504b41bc631a73b85279c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs new file mode 100644 index 0000000..1f5064f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class PlayBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..b107d47 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e6026175b5f21964d916eb7b4440fa48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs new file mode 100644 index 0000000..654693e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class PlayBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs.meta new file mode 100644 index 0000000..b27fe8f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PlayBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69b140eb64512d1468194f1e11dfaef1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs new file mode 100644 index 0000000..358487c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class PrizeWheelBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..68080af --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f30e3bed32357904d9c541717a2cbb62 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs new file mode 100644 index 0000000..1ab7133 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class PrizeWheelBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs.meta new file mode 100644 index 0000000..36fb9b8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/PrizeWheelBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa8e70dfb08241d418219893d7d50df2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs new file mode 100644 index 0000000..8150686 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class RankBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..9880807 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 08d94b45ae9cbcd498cbae72ac4123d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs new file mode 100644 index 0000000..7b014c6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class RankBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs.meta new file mode 100644 index 0000000..a5403fe --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RankBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 422ba7e7b7090d84e896cecce5a5b313 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs new file mode 100644 index 0000000..aa83ec9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class RightBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..8d9e115 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 146bb6425a471944ea4351c30f57f0ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs new file mode 100644 index 0000000..6052af2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class RightBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs.meta new file mode 100644 index 0000000..df822d0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/RightBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fea37dcdd03a63459a62708e00668f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs new file mode 100644 index 0000000..a3660af --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class SignInBtn + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs.meta new file mode 100644 index 0000000..ce7583b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e50c828403a19f40a2b05fac01119cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs new file mode 100644 index 0000000..4aa5014 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class SignInBtn + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs.meta new file mode 100644 index 0000000..bba8bdf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/SignInBtn_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 59a9aca645fa57d4a9980e2c89164f1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs new file mode 100644 index 0000000..92efb23 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class btn_battle + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs.meta new file mode 100644 index 0000000..2c845c0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e0372b1dcd9358d41b0e97f58df3f120 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs new file mode 100644 index 0000000..1e448d8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G018_GameHome +{ + public partial class btn_battle + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs.meta new file mode 100644 index 0000000..993b584 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/btn_battle_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18b47cffad44bdc45b5ffa52872ce5dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs new file mode 100644 index 0000000..c2864fa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G018_GameHome +{ + public partial class new_topgold + { + /// + /// 0:0 + /// + public int _State_0 = 0; + /// + /// 1:1 + /// + public int _State_1 = 1; + /// + /// 2:2 + /// + public int _State_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs.meta new file mode 100644 index 0000000..caf22e7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 795a6e9785a58e048850aefd360eee9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs new file mode 100644 index 0000000..6471f0e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs @@ -0,0 +1,19 @@ + +namespace FGUI.G018_GameHome +{ + public partial class new_topgold + { + /// + /// 0:0 + /// + public const int State_0 = 0; + /// + /// 1:1 + /// + public const int State_1 = 1; + /// + /// 2:2 + /// + public const int State_2 = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs.meta new file mode 100644 index 0000000..bbb5983 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G018_GameHome/new_topgold_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b8562a7028b23f4186677847b17ad74 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel.meta new file mode 100644 index 0000000..174e12e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d0b8b96d447173a48a81d9be3930a4e4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs new file mode 100644 index 0000000..7b6c1f6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G020_PrizeWheel +{ + public partial class CloseButton + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs.meta new file mode 100644 index 0000000..6d257ec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 704595653a4a9da4e943200b9f142e47 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs new file mode 100644 index 0000000..2f122c5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G020_PrizeWheel +{ + public partial class CloseButton + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs.meta new file mode 100644 index 0000000..d7dd83b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/CloseButton_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70bfa2f167f7c9841b58535fe1f4b5f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs new file mode 100644 index 0000000..742a70c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G020_PrizeWheel +{ + public partial class StartSpinButton + { + /// + /// 0:up + /// + public int _Button_up = 0; + /// + /// 1:down + /// + public int _Button_down = 1; + /// + /// 2:over + /// + public int _Button_over = 2; + /// + /// 3:selectedOver + /// + public int _Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs.meta new file mode 100644 index 0000000..92463d6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa3c2e65588b2154fab97fbd021c8913 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs new file mode 100644 index 0000000..55e3e5b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs @@ -0,0 +1,23 @@ + +namespace FGUI.G020_PrizeWheel +{ + public partial class StartSpinButton + { + /// + /// 0:up + /// + public const int Button_up = 0; + /// + /// 1:down + /// + public const int Button_down = 1; + /// + /// 2:over + /// + public const int Button_over = 2; + /// + /// 3:selectedOver + /// + public const int Button_selectedOver = 3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs.meta new file mode 100644 index 0000000..50bb40b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G020_PrizeWheel/StartSpinButton_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3bcc832a663a5d4193189927cd76569 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin.meta new file mode 100644 index 0000000..236ea20 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 41ab8266bd0c4ca418901668097838ca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs new file mode 100644 index 0000000..31b3067 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G601_Coin +{ + public partial class com_Coins + { + /// + /// 0:more + /// + public int _Coin_more = 0; + /// + /// 1:single + /// + public int _Coin_single = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs.meta new file mode 100644 index 0000000..89b26ec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe00ac81c33eafa46a8f1413e14bd8e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs new file mode 100644 index 0000000..93a9d73 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.G601_Coin +{ + public partial class com_Coins + { + /// + /// 0:more + /// + public const int Coin_more = 0; + /// + /// 1:single + /// + public const int Coin_single = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs.meta new file mode 100644 index 0000000..12901e7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/G601_Coin/com_Coins_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28d12774b3702a644a03292eac709e88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle.meta new file mode 100644 index 0000000..bcded9a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bf51a80f81f29b241a1f2865f8da820f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs new file mode 100644 index 0000000..f4b87b3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs @@ -0,0 +1,15 @@ + +namespace FGUI.SC005_NetIdle +{ + public partial class com_Netidle + { + /// + /// 0:none + /// + public int _State_none = 0; + /// + /// 1:enterRoom + /// + public int _State_enterRoom = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs.meta new file mode 100644 index 0000000..80b5419 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 715a4b42b36334a49b95575e45c95483 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs new file mode 100644 index 0000000..29e6c69 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs @@ -0,0 +1,15 @@ + +namespace FGUI.SC005_NetIdle +{ + public partial class com_Netidle + { + /// + /// 0:none + /// + public const int State_none = 0; + /// + /// 1:enterRoom + /// + public const int State_enterRoom = 1; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs.meta b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs.meta new file mode 100644 index 0000000..7fdb85d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/ControlDefine/Project/SC005_NetIdle/com_Netidle_Const.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae9e6d924df66ab438777e7e58343119 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package.meta b/Assets/CrazyZoo/FGUI/Package.meta new file mode 100644 index 0000000..7024d80 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1ce3273f233b2d64c82c9f67245fd15c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common.meta b/Assets/CrazyZoo/FGUI/Package/A000_common.meta new file mode 100644 index 0000000..084a442 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c275e2419df042645aba911c450dd446 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs new file mode 100644 index 0000000..43b8052 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs @@ -0,0 +1,32 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.A000_common +{ + public class A000_commonBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_success_cash.URL, typeof(com_success_cash)); + UIObjectFactory.SetPackageItemExtension(cash_broad.URL, typeof(cash_broad)); + UIObjectFactory.SetPackageItemExtension(com_broadcast1.URL, typeof(com_broadcast1)); + UIObjectFactory.SetPackageItemExtension(com_broadcast_text1.URL, typeof(com_broadcast_text1)); + UIObjectFactory.SetPackageItemExtension(btn_tabad.URL, typeof(btn_tabad)); + UIObjectFactory.SetPackageItemExtension(btn_tabwhite.URL, typeof(btn_tabwhite)); + UIObjectFactory.SetPackageItemExtension(btn_tabblue.URL, typeof(btn_tabblue)); + UIObjectFactory.SetPackageItemExtension(head_loader.URL, typeof(head_loader)); + UIObjectFactory.SetPackageItemExtension(btn_revive.URL, typeof(btn_revive)); + UIObjectFactory.SetPackageItemExtension(btn_AdRevive.URL, typeof(btn_AdRevive)); + UIObjectFactory.SetPackageItemExtension(btn_noads.URL, typeof(btn_noads)); + UIObjectFactory.SetPackageItemExtension(btn_three.URL, typeof(btn_three)); + UIObjectFactory.SetPackageItemExtension(btn_currency.URL, typeof(btn_currency)); + UIObjectFactory.SetPackageItemExtension(btn_cash_out.URL, typeof(btn_cash_out)); + UIObjectFactory.SetPackageItemExtension(btn_tab_record.URL, typeof(btn_tab_record)); + UIObjectFactory.SetPackageItemExtension(btn_failpack.URL, typeof(btn_failpack)); + UIObjectFactory.SetPackageItemExtension(btn_saveingpot.URL, typeof(btn_saveingpot)); + UIObjectFactory.SetPackageItemExtension(btn_menu.URL, typeof(btn_menu)); + UIObjectFactory.SetPackageItemExtension(com_loadingBlacklist.URL, typeof(com_loadingBlacklist)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs.meta new file mode 100644 index 0000000..371b8f1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/A000_commonBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6322b2cb4061a554ebbaa2bc7aa03c21 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs new file mode 100644 index 0000000..ca534ab --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_AdRevive : GButton + { + public GTextField text_cooldown; + public GImage img_saveingpot; + public const string URL = "ui://pmf3wbjigxpr35"; + + public static btn_AdRevive CreateInstance() + { + return (btn_AdRevive)UIPackage.CreateObject("A000_common", "btn_AdRevive"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_cooldown = (GTextField)GetChildAt(3); + img_saveingpot = (GImage)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs.meta new file mode 100644 index 0000000..96bef7f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_AdRevive.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 700780f52602d8942bca82669b6cde92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs new file mode 100644 index 0000000..7a92d1d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_cash_out : GButton + { + public GTextField text_read; + public const string URL = "ui://pmf3wbjin691mk"; + + public static btn_cash_out CreateInstance() + { + return (btn_cash_out)UIPackage.CreateObject("A000_common", "btn_cash_out"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_read = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs.meta new file mode 100644 index 0000000..0e7d81c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_cash_out.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8694aafad3d94684989bd415865af8fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs new file mode 100644 index 0000000..f65962f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_currency : GButton + { + public GTextField text_value; + public const string URL = "ui://pmf3wbjijq5ikm"; + + public static btn_currency CreateInstance() + { + return (btn_currency)UIPackage.CreateObject("A000_common", "btn_currency"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_value = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs.meta new file mode 100644 index 0000000..c1820c9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_currency.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0b8cc4a0779d91642b9ab147056e28d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs new file mode 100644 index 0000000..fc41d75 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_failpack : GButton + { + public GTextField lab_time; + public const string URL = "ui://pmf3wbjiosgy2i"; + + public static btn_failpack CreateInstance() + { + return (btn_failpack)UIPackage.CreateObject("A000_common", "btn_failpack"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + lab_time = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs.meta new file mode 100644 index 0000000..670e059 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_failpack.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29e63c55121724be89699749a50466c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs new file mode 100644 index 0000000..4e2af54 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_menu : GButton + { + public head_loader loader_avatar; + public GLoader loader_flag; + public GTextField text_name; + public const string URL = "ui://pmf3wbjirezmd"; + + public static btn_menu CreateInstance() + { + return (btn_menu)UIPackage.CreateObject("A000_common", "btn_menu"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + loader_avatar = (head_loader)GetChildAt(0); + loader_flag = (GLoader)GetChildAt(1); + text_name = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs.meta new file mode 100644 index 0000000..022feb7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_menu.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9465bd944a6c7240bce197973765808 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs new file mode 100644 index 0000000..92e37d5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_noads : GButton + { + public Controller state; + public GImage img_ad; + public GImage img_pack; + public Transition t0; + public Transition t1; + public const string URL = "ui://pmf3wbjii98k1h"; + + public static btn_noads CreateInstance() + { + return (btn_noads)UIPackage.CreateObject("A000_common", "btn_noads"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + img_ad = (GImage)GetChildAt(0); + img_pack = (GImage)GetChildAt(1); + t0 = GetTransitionAt(0); + t1 = GetTransitionAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs.meta new file mode 100644 index 0000000..706ccb7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_noads.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3425d576b7426fc44acaa3661b860ecf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs new file mode 100644 index 0000000..0f16384 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_revive : GButton + { + public GTextField txt_coin; + public const string URL = "ui://pmf3wbjigxpr34"; + + public static btn_revive CreateInstance() + { + return (btn_revive)UIPackage.CreateObject("A000_common", "btn_revive"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + txt_coin = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs.meta new file mode 100644 index 0000000..6954045 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_revive.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: acd02d840b563924c9f330ccdc004a84 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs new file mode 100644 index 0000000..19e2c03 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_saveingpot : GButton + { + public GGraph ani_parent; + public GTextField text_nowcash; + public const string URL = "ui://pmf3wbjiosgy4m"; + + public static btn_saveingpot CreateInstance() + { + return (btn_saveingpot)UIPackage.CreateObject("A000_common", "btn_saveingpot"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + ani_parent = (GGraph)GetChildAt(0); + text_nowcash = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs.meta new file mode 100644 index 0000000..f77d13f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_saveingpot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a320654c30c0a4636bf545b6f8426449 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs new file mode 100644 index 0000000..65ed34b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_tab_record : GButton + { + public Controller cont_tab; + public const string URL = "ui://pmf3wbjin691mp"; + + public static btn_tab_record CreateInstance() + { + return (btn_tab_record)UIPackage.CreateObject("A000_common", "btn_tab_record"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_tab = GetControllerAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs.meta new file mode 100644 index 0000000..88566ab --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tab_record.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b9b72fbfe293a244bba5459f1db541b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs new file mode 100644 index 0000000..6ad6b24 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_tabad : GButton + { + public GImage img_saveingpot; + public const string URL = "ui://pmf3wbjifd7ska"; + + public static btn_tabad CreateInstance() + { + return (btn_tabad)UIPackage.CreateObject("A000_common", "btn_tabad"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + img_saveingpot = (GImage)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs.meta new file mode 100644 index 0000000..a1b62ca --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabad.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24db54e62aace844084e3c24c25ecc9f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs new file mode 100644 index 0000000..cb5678a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_tabblue : GButton + { + public Controller state; + public GImage img_saveingpot; + public const string URL = "ui://pmf3wbjifd7so"; + + public static btn_tabblue CreateInstance() + { + return (btn_tabblue)UIPackage.CreateObject("A000_common", "btn_tabblue"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + img_saveingpot = (GImage)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs.meta new file mode 100644 index 0000000..5930cdd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabblue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 506bcc9ceb9f04cd0b09bdf37543039d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs new file mode 100644 index 0000000..059322f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_tabwhite : GButton + { + public Controller btn_state; + public GTextField number_text; + public GTextField buy_text; + public const string URL = "ui://pmf3wbjifd7sn"; + + public static btn_tabwhite CreateInstance() + { + return (btn_tabwhite)UIPackage.CreateObject("A000_common", "btn_tabwhite"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_state = GetControllerAt(0); + number_text = (GTextField)GetChildAt(1); + buy_text = (GTextField)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs.meta new file mode 100644 index 0000000..8412898 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_tabwhite.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11cd0d5615cebaf4c846fa54b84dfc67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs new file mode 100644 index 0000000..529f654 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class btn_three : GButton + { + public GImage red; + public const string URL = "ui://pmf3wbjijq3iob"; + + public static btn_three CreateInstance() + { + return (btn_three)UIPackage.CreateObject("A000_common", "btn_three"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + red = (GImage)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs.meta new file mode 100644 index 0000000..6dbea0a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/btn_three.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9492e60889d547958b639cf30369f05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs new file mode 100644 index 0000000..fa9563d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class cash_broad : GComponent + { + public GRichTextField cast_text; + public Transition t0; + public Transition t1; + public const string URL = "ui://pmf3wbjiagfu14"; + + public static cash_broad CreateInstance() + { + return (cash_broad)UIPackage.CreateObject("A000_common", "cash_broad"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cast_text = (GRichTextField)GetChildAt(1); + t0 = GetTransitionAt(0); + t1 = GetTransitionAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs.meta new file mode 100644 index 0000000..aa55fad --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/cash_broad.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d94332ccde464814d84cec90fd5a958a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs new file mode 100644 index 0000000..069cfbc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class com_broadcast1 : GComponent + { + public GButton btn_record; + public com_broadcast_text1 broad_cast_text; + public GGroup broad; + public GGroup group_; + public Transition t0; + public Transition t1; + public const string URL = "ui://pmf3wbjiez6k21"; + + public static com_broadcast1 CreateInstance() + { + return (com_broadcast1)UIPackage.CreateObject("A000_common", "com_broadcast1"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_record = (GButton)GetChildAt(0); + broad_cast_text = (com_broadcast_text1)GetChildAt(1); + broad = (GGroup)GetChildAt(2); + group_ = (GGroup)GetChildAt(3); + t0 = GetTransitionAt(0); + t1 = GetTransitionAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs.meta new file mode 100644 index 0000000..e93fd8a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1773150c792aecf408ddf1f19af3eaa0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs new file mode 100644 index 0000000..ad028f9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class com_broadcast_text1 : GComponent + { + public GGraph bg_panel; + public GRichTextField cast_text; + public GRichTextField hide_text; + public GButton btn_broad; + public const string URL = "ui://pmf3wbjiez6k22"; + + public static com_broadcast_text1 CreateInstance() + { + return (com_broadcast_text1)UIPackage.CreateObject("A000_common", "com_broadcast_text1"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + bg_panel = (GGraph)GetChildAt(0); + cast_text = (GRichTextField)GetChildAt(1); + hide_text = (GRichTextField)GetChildAt(2); + btn_broad = (GButton)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs.meta new file mode 100644 index 0000000..039d6a2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_broadcast_text1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a938af635d5a8e348956774b9c4029d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs new file mode 100644 index 0000000..1e0ed01 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class com_loadingBlacklist : GComponent + { + public GRichTextField text_privacy; + public const string URL = "ui://pmf3wbjisv84j"; + + public static com_loadingBlacklist CreateInstance() + { + return (com_loadingBlacklist)UIPackage.CreateObject("A000_common", "com_loadingBlacklist"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_privacy = (GRichTextField)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs.meta new file mode 100644 index 0000000..80a4c72 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_loadingBlacklist.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8de226cc9b4ca4d44bceb94288610422 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs new file mode 100644 index 0000000..ba19d1b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class com_success_cash : GComponent + { + public cash_broad broad; + public GTextField cash_text; + public GImage progress; + public GTextField progress_text; + public GButton btn_cash; + public const string URL = "ui://pmf3wbjiagfu11"; + + public static com_success_cash CreateInstance() + { + return (com_success_cash)UIPackage.CreateObject("A000_common", "com_success_cash"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + broad = (cash_broad)GetChildAt(1); + cash_text = (GTextField)GetChildAt(2); + progress = (GImage)GetChildAt(4); + progress_text = (GTextField)GetChildAt(5); + btn_cash = (GButton)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs.meta new file mode 100644 index 0000000..93fe5a4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/com_success_cash.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a520b884c4b0a24aac11bf9dc9c13c1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs b/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs new file mode 100644 index 0000000..3662779 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A000_common +{ + public partial class head_loader : GComponent + { + public GLoader loader_avatar; + public const string URL = "ui://pmf3wbjifyhin7"; + + public static head_loader CreateInstance() + { + return (head_loader)UIPackage.CreateObject("A000_common", "head_loader"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + loader_avatar = (GLoader)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs.meta b/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs.meta new file mode 100644 index 0000000..773faea --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A000_common/head_loader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d40fa89c470456c4bbdc0c92dbc406e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A001_bigImg.meta b/Assets/CrazyZoo/FGUI/Package/A001_bigImg.meta new file mode 100644 index 0000000..c3fa746 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A001_bigImg.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 78ce8f94f7cf7e34fa017f6c0ea314b0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs new file mode 100644 index 0000000..0401ca5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs @@ -0,0 +1,14 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.A001_bigImg +{ + public class A001_bigImgBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_loadingbg.URL, typeof(com_loadingbg)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs.meta new file mode 100644 index 0000000..15590e4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/A001_bigImgBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70bd1019e4ede0a46a4084f57c37a355 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs new file mode 100644 index 0000000..ca21cbb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.A001_bigImg +{ + public partial class com_loadingbg : GComponent + { + public GGraph bg_parent; + public GGraph light_parent; + public const string URL = "ui://4lkrp0l7xgqvkf"; + + public static com_loadingbg CreateInstance() + { + return (com_loadingbg)UIPackage.CreateObject("A001_bigImg", "com_loadingbg"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + bg_parent = (GGraph)GetChildAt(3); + light_parent = (GGraph)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs.meta b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs.meta new file mode 100644 index 0000000..5feb4e2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/A001_bigImg/com_loadingbg.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aea28dba111d4c24dacabe50bd14c282 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G001_login.meta b/Assets/CrazyZoo/FGUI/Package/G001_login.meta new file mode 100644 index 0000000..d966417 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G001_login.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 708f1b0936cbcec46ad4dafcdd214030 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs b/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs new file mode 100644 index 0000000..9cdfafc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs @@ -0,0 +1,14 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G001_login +{ + public class G001_loginBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_login.URL, typeof(com_login)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs.meta new file mode 100644 index 0000000..046776e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G001_login/G001_loginBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d51fa69d46fe974c834ecf3c0fc39f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs b/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs new file mode 100644 index 0000000..c04c3e6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G001_login +{ + public partial class com_login : GComponent + { + public GGraph Title_parent; + public GGraph logo_parent; + public GButton btn_login; + public GComponent com_blklist1; + public GButton btn_debug0; + public const string URL = "ui://bw2zghfmfd7s0"; + + public static com_login CreateInstance() + { + return (com_login)UIPackage.CreateObject("G001_login", "com_login"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + Title_parent = (GGraph)GetChildAt(0); + logo_parent = (GGraph)GetChildAt(1); + btn_login = (GButton)GetChildAt(2); + com_blklist1 = (GComponent)GetChildAt(3); + btn_debug0 = (GButton)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs.meta b/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs.meta new file mode 100644 index 0000000..3af936e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G001_login/com_login.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8dd44f6cee0b62445ab17930e647c0af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main.meta b/Assets/CrazyZoo/FGUI/Package/G002_main.meta new file mode 100644 index 0000000..6d82886 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea347105d7eaf0a43ba5e3608b2cf189 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs new file mode 100644 index 0000000..292ac38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs @@ -0,0 +1,23 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G002_main +{ + public class G002_mainBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_box.URL, typeof(com_box)); + UIObjectFactory.SetPackageItemExtension(btn_quiz.URL, typeof(btn_quiz)); + UIObjectFactory.SetPackageItemExtension(btn_refresh.URL, typeof(btn_refresh)); + UIObjectFactory.SetPackageItemExtension(com_mainPop.URL, typeof(com_mainPop)); + UIObjectFactory.SetPackageItemExtension(com_main.URL, typeof(com_main)); + UIObjectFactory.SetPackageItemExtension(btn_question.URL, typeof(btn_question)); + UIObjectFactory.SetPackageItemExtension(com_faq.URL, typeof(com_faq)); + UIObjectFactory.SetPackageItemExtension(com_list_main.URL, typeof(com_list_main)); + UIObjectFactory.SetPackageItemExtension(com_firstreward.URL, typeof(com_firstreward)); + UIObjectFactory.SetPackageItemExtension(btn_look_ad.URL, typeof(btn_look_ad)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs.meta new file mode 100644 index 0000000..0d38033 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/G002_mainBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0de18100946e1f442a24e5107d444e97 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs new file mode 100644 index 0000000..0ac105e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class btn_look_ad : GButton + { + public Controller cool_down; + public GTextField cool_down_time; + public GGraph gp; + public const string URL = "ui://b55ys1yyozwz2q"; + + public static btn_look_ad CreateInstance() + { + return (btn_look_ad)UIPackage.CreateObject("G002_main", "btn_look_ad"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cool_down = GetControllerAt(0); + cool_down_time = (GTextField)GetChildAt(2); + gp = (GGraph)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs.meta new file mode 100644 index 0000000..1e78ebb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_look_ad.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: adbead9a10c69ab479949dac9f01c727 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs new file mode 100644 index 0000000..d02a65b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class btn_question : GButton + { + public Controller btn_name; + public const string URL = "ui://b55ys1yyheqb2w"; + + public static btn_question CreateInstance() + { + return (btn_question)UIPackage.CreateObject("G002_main", "btn_question"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_name = GetControllerAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs.meta new file mode 100644 index 0000000..c2dbcaf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_question.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0aee8bce8c198664eac75d28ca4dffe8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs new file mode 100644 index 0000000..e59393c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class btn_quiz : GButton + { + public Controller cont_color; + public Controller cont_white; + public GLoader loader_logo; + public GTextField text_name; + public GTextField text_quiz; + public const string URL = "ui://b55ys1yyf1i47"; + + public static btn_quiz CreateInstance() + { + return (btn_quiz)UIPackage.CreateObject("G002_main", "btn_quiz"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_color = GetControllerAt(0); + cont_white = GetControllerAt(1); + loader_logo = (GLoader)GetChildAt(6); + text_name = (GTextField)GetChildAt(8); + text_quiz = (GTextField)GetChildAt(9); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs.meta new file mode 100644 index 0000000..d88edb4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_quiz.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3dfe6dadc35691945952f87d9222aad6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs new file mode 100644 index 0000000..8a35eb6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class btn_refresh : GButton + { + public GTextField text_name; + public const string URL = "ui://b55ys1yyf1i4b"; + + public static btn_refresh CreateInstance() + { + return (btn_refresh)UIPackage.CreateObject("G002_main", "btn_refresh"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_name = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs.meta new file mode 100644 index 0000000..c123b0f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/btn_refresh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 67a8dd97067f1f840ac46537d549841e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs new file mode 100644 index 0000000..58a0b09 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_box : GComponent + { + public Controller cont_white; + public GTextField text_num; + public GTextField text_more; + public GProgressBar pb_num; + public GButton btn_menu; + public GGraph finger_place; + public GTextField t12; + public GButton btn_out; + public const string URL = "ui://b55ys1yyf1i46"; + + public static com_box CreateInstance() + { + return (com_box)UIPackage.CreateObject("G002_main", "com_box"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_white = GetControllerAt(0); + text_num = (GTextField)GetChildAt(2); + text_more = (GTextField)GetChildAt(3); + pb_num = (GProgressBar)GetChildAt(4); + btn_menu = (GButton)GetChildAt(5); + finger_place = (GGraph)GetChildAt(6); + t12 = (GTextField)GetChildAt(7); + btn_out = (GButton)GetChildAt(9); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs.meta new file mode 100644 index 0000000..69a110e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_box.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca62d09f31b85ac4192a8c126ffee95c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs new file mode 100644 index 0000000..3345a6e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_faq : GComponent + { + public GTextField title; + public GButton btn_close; + public GList list_; + public const string URL = "ui://b55ys1yyheqb2x"; + + public static com_faq CreateInstance() + { + return (com_faq)UIPackage.CreateObject("G002_main", "com_faq"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + title = (GTextField)GetChildAt(1); + btn_close = (GButton)GetChildAt(2); + list_ = (GList)GetChildAt(27); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs.meta new file mode 100644 index 0000000..339209c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_faq.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6ac318fc50889b94d86fd3c54e8bae66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs new file mode 100644 index 0000000..c6df904 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs @@ -0,0 +1,47 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_firstreward : GComponent + { + public Controller state; + public GGraph spine_parent; + public GButton btn_getreward; + public GTextField end_point; + public GGraph bg_parent; + public GGraph fx_place; + public GComponent money; + public GLabel title0; + public GButton btn_close; + public GImage img_cash; + public GTextField text_num; + public GButton btn_get; + public const string URL = "ui://b55ys1yyngxz38"; + + public static com_firstreward CreateInstance() + { + return (com_firstreward)UIPackage.CreateObject("G002_main", "com_firstreward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + spine_parent = (GGraph)GetChildAt(0); + btn_getreward = (GButton)GetChildAt(1); + end_point = (GTextField)GetChildAt(2); + bg_parent = (GGraph)GetChildAt(3); + fx_place = (GGraph)GetChildAt(4); + money = (GComponent)GetChildAt(5); + title0 = (GLabel)GetChildAt(6); + btn_close = (GButton)GetChildAt(7); + img_cash = (GImage)GetChildAt(8); + text_num = (GTextField)GetChildAt(9); + btn_get = (GButton)GetChildAt(10); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs.meta new file mode 100644 index 0000000..5a9fa9a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_firstreward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a111f8081ced53546ace401947fd685d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs new file mode 100644 index 0000000..63ece0e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_list_main : GComponent + { + public GTextField name_; + public GTextField money; + public GTextField time1; + public GTextField time2; + public const string URL = "ui://b55ys1yyheqb2z"; + + public static com_list_main CreateInstance() + { + return (com_list_main)UIPackage.CreateObject("G002_main", "com_list_main"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + name_ = (GTextField)GetChildAt(0); + money = (GTextField)GetChildAt(1); + time1 = (GTextField)GetChildAt(2); + time2 = (GTextField)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs.meta new file mode 100644 index 0000000..d35bb01 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_list_main.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5eef1af7528431b4e9d459f56ce79174 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs new file mode 100644 index 0000000..254ff41 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs @@ -0,0 +1,61 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_main : GComponent + { + public Controller cont_white; + public com_box com_box; + public btn_refresh btn_refresh; + public GGraph finger_place; + public GButton btn_playnow; + public GTextField text_uid; + public GComponent com_infoBar; + public btn_look_ad btn_look_ad; + public btn_question btn_faq; + public btn_question btn_setting; + public btn_question btn_sign; + public btn_quiz btn_quiz_0; + public btn_quiz btn_quiz_1; + public btn_quiz btn_quiz_2; + public btn_quiz btn_quiz_3; + public btn_quiz btn_quiz_4; + public btn_quiz btn_quiz_5; + public GGroup btn_group; + public Transition t0; + public const string URL = "ui://b55ys1yyfd7s0"; + + public static com_main CreateInstance() + { + return (com_main)UIPackage.CreateObject("G002_main", "com_main"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_white = GetControllerAt(0); + com_box = (com_box)GetChildAt(2); + btn_refresh = (btn_refresh)GetChildAt(4); + finger_place = (GGraph)GetChildAt(6); + btn_playnow = (GButton)GetChildAt(7); + text_uid = (GTextField)GetChildAt(9); + com_infoBar = (GComponent)GetChildAt(10); + btn_look_ad = (btn_look_ad)GetChildAt(11); + btn_faq = (btn_question)GetChildAt(12); + btn_setting = (btn_question)GetChildAt(13); + btn_sign = (btn_question)GetChildAt(14); + btn_quiz_0 = (btn_quiz)GetChildAt(15); + btn_quiz_1 = (btn_quiz)GetChildAt(16); + btn_quiz_2 = (btn_quiz)GetChildAt(17); + btn_quiz_3 = (btn_quiz)GetChildAt(18); + btn_quiz_4 = (btn_quiz)GetChildAt(19); + btn_quiz_5 = (btn_quiz)GetChildAt(20); + btn_group = (GGroup)GetChildAt(21); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs.meta new file mode 100644 index 0000000..4add83a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_main.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8ef62ad36606e741b911d16aa43b064 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs b/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs new file mode 100644 index 0000000..d748118 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G002_main +{ + public partial class com_mainPop : GComponent + { + public GTextField text_name; + public GLoader loader_logo; + public GTextField t1; + public GButton btn_start; + public GButton btn_back; + public GGraph finger_place; + public const string URL = "ui://b55ys1yyf1i4c"; + + public static com_mainPop CreateInstance() + { + return (com_mainPop)UIPackage.CreateObject("G002_main", "com_mainPop"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_name = (GTextField)GetChildAt(1); + loader_logo = (GLoader)GetChildAt(2); + t1 = (GTextField)GetChildAt(3); + btn_start = (GButton)GetChildAt(4); + btn_back = (GButton)GetChildAt(5); + finger_place = (GGraph)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs.meta b/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs.meta new file mode 100644 index 0000000..3266aca --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G002_main/com_mainPop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f55cbc5519ea2884aa5300f92792835e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play.meta b/Assets/CrazyZoo/FGUI/Package/G003_play.meta new file mode 100644 index 0000000..7a844f9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c2d8cbe493c3a8b49ba2397565dcf64f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs new file mode 100644 index 0000000..aa45792 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class Com_LoginFailurePopup : GComponent + { + public GTextField txt_Title; + public GButton btn_close; + public GButton btn_Login; + public const string URL = "ui://zfuthrzhr7rw2h"; + + public static Com_LoginFailurePopup CreateInstance() + { + return (Com_LoginFailurePopup)UIPackage.CreateObject("G003_play", "Com_LoginFailurePopup"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + txt_Title = (GTextField)GetChildAt(1); + btn_close = (GButton)GetChildAt(2); + btn_Login = (GButton)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs.meta new file mode 100644 index 0000000..622c8e9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/Com_LoginFailurePopup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 461d1b4401157fe41b210c8e81f3dad9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs new file mode 100644 index 0000000..acc621f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs @@ -0,0 +1,22 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G003_play +{ + public class G003_playBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_prop.URL, typeof(com_prop)); + UIObjectFactory.SetPackageItemExtension(sheep_play.URL, typeof(sheep_play)); + UIObjectFactory.SetPackageItemExtension(new_topmoney.URL, typeof(new_topmoney)); + UIObjectFactory.SetPackageItemExtension(new_topgold.URL, typeof(new_topgold)); + UIObjectFactory.SetPackageItemExtension(btn_battle.URL, typeof(btn_battle)); + UIObjectFactory.SetPackageItemExtension(btn_hall.URL, typeof(btn_hall)); + UIObjectFactory.SetPackageItemExtension(btn_look_ad.URL, typeof(btn_look_ad)); + UIObjectFactory.SetPackageItemExtension(com_opengame.URL, typeof(com_opengame)); + UIObjectFactory.SetPackageItemExtension(Com_LoginFailurePopup.URL, typeof(Com_LoginFailurePopup)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs.meta new file mode 100644 index 0000000..b78a1a8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/G003_playBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 600947f7e894d4a429c2d74cfd8f0321 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs new file mode 100644 index 0000000..59962df --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class btn_battle : GButton + { + public GImage red; + public GImage progress; + public GTextField number_text; + public const string URL = "ui://zfuthrzhi98k1i"; + + public static btn_battle CreateInstance() + { + return (btn_battle)UIPackage.CreateObject("G003_play", "btn_battle"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + red = (GImage)GetChildAt(1); + progress = (GImage)GetChildAt(3); + number_text = (GTextField)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs.meta new file mode 100644 index 0000000..46e32c9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_battle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b53b7428363087c44928981b556119dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs new file mode 100644 index 0000000..499c039 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class btn_hall : GButton + { + public GTextField number_text1; + public GTextField number_text; + public Transition t0; + public const string URL = "ui://zfuthrzhi98k1k"; + + public static btn_hall CreateInstance() + { + return (btn_hall)UIPackage.CreateObject("G003_play", "btn_hall"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + number_text1 = (GTextField)GetChildAt(3); + number_text = (GTextField)GetChildAt(4); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs.meta new file mode 100644 index 0000000..9477822 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_hall.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 449c2deb6bd2b1d40928e13f74a5bd0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs new file mode 100644 index 0000000..30715c1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class btn_look_ad : GButton + { + public Controller cool_down; + public GTextField cool_down_time; + public GGraph gp; + public const string URL = "ui://zfuthrzhi98k1m"; + + public static btn_look_ad CreateInstance() + { + return (btn_look_ad)UIPackage.CreateObject("G003_play", "btn_look_ad"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cool_down = GetControllerAt(0); + cool_down_time = (GTextField)GetChildAt(0); + gp = (GGraph)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs.meta new file mode 100644 index 0000000..1247e5d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/btn_look_ad.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b91e32ccd707d574f8148d3ac147f9c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs new file mode 100644 index 0000000..92b7309 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class com_opengame : GComponent + { + public GImage LevelWordart; + public GRichTextField lv_text; + public GImage GoWordart; + public GGraph tips_node; + public Transition t0; + public const string URL = "ui://zfuthrzhi98k1r"; + + public static com_opengame CreateInstance() + { + return (com_opengame)UIPackage.CreateObject("G003_play", "com_opengame"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + LevelWordart = (GImage)GetChildAt(5); + lv_text = (GRichTextField)GetChildAt(6); + GoWordart = (GImage)GetChildAt(7); + tips_node = (GGraph)GetChildAt(10); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs.meta new file mode 100644 index 0000000..c8dce21 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/com_opengame.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba44c42a6e2553c489926e0bd1c269db +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs new file mode 100644 index 0000000..96eb592 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs @@ -0,0 +1,47 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class com_prop : GComponent + { + public Controller cont_prop; + public Controller pay_type; + public GTextField txt_Title; + public GButton btn_close; + public GTextField txt_content; + public GButton btn_clean; + public GButton btn_add; + public GButton btn_merge; + public GButton btn_PayBox; + public GTextField text_NeedAds; + public GTextField text_hasADsCount; + public GButton btn_max_pay; + public const string URL = "ui://zfuthrzhgxpr28"; + + public static com_prop CreateInstance() + { + return (com_prop)UIPackage.CreateObject("G003_play", "com_prop"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_prop = GetControllerAt(0); + pay_type = GetControllerAt(1); + txt_Title = (GTextField)GetChildAt(1); + btn_close = (GButton)GetChildAt(2); + txt_content = (GTextField)GetChildAt(7); + btn_clean = (GButton)GetChildAt(8); + btn_add = (GButton)GetChildAt(9); + btn_merge = (GButton)GetChildAt(10); + btn_PayBox = (GButton)GetChildAt(15); + text_NeedAds = (GTextField)GetChildAt(18); + text_hasADsCount = (GTextField)GetChildAt(19); + btn_max_pay = (GButton)GetChildAt(20); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs.meta new file mode 100644 index 0000000..465560b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/com_prop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a5590478d79fdd4a8fcfedd2fc62660 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs new file mode 100644 index 0000000..21c2970 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class new_topgold : GComponent + { + public Controller state; + public GTextField number_text; + public GImage red; + public GTextField tips_text; + public GButton btn_buygold; + public Transition t0; + public const string URL = "ui://zfuthrzhi98k1f"; + + public static new_topgold CreateInstance() + { + return (new_topgold)UIPackage.CreateObject("G003_play", "new_topgold"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + number_text = (GTextField)GetChildAt(2); + red = (GImage)GetChildAt(3); + tips_text = (GTextField)GetChildAt(5); + btn_buygold = (GButton)GetChildAt(6); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs.meta new file mode 100644 index 0000000..5c6444c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topgold.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 760b485481fd4dd4ba82a6111b4e3ee8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs new file mode 100644 index 0000000..92157d9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class new_topmoney : GComponent + { + public GTextField number_text; + public GButton btn_cashout; + public const string URL = "ui://zfuthrzhi98k1d"; + + public static new_topmoney CreateInstance() + { + return (new_topmoney)UIPackage.CreateObject("G003_play", "new_topmoney"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + number_text = (GTextField)GetChildAt(1); + btn_cashout = (GButton)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs.meta new file mode 100644 index 0000000..68a538d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/new_topmoney.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a35ff097b86b9d4d8f441210e6631b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs b/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs new file mode 100644 index 0000000..3fed6f1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs @@ -0,0 +1,53 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G003_play +{ + public partial class sheep_play : GComponent + { + public GTextField level_text; + public GButton btn_failpack; + public GComponent broadcast; + public new_topmoney money; + public new_topgold gold; + public GButton btn_setting; + public GButton btn_noads; + public btn_battle btn_task; + public GButton btn_menu; + public GButton btn_saveingpot; + public GButton Btn_SignIn; + public GGroup TopBox; + public btn_look_ad btn_look_ad; + public btn_battle btn_clear; + public GButton btn_three_day; + public const string URL = "ui://zfuthrzhi98k0"; + + public static sheep_play CreateInstance() + { + return (sheep_play)UIPackage.CreateObject("G003_play", "sheep_play"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + level_text = (GTextField)GetChildAt(0); + btn_failpack = (GButton)GetChildAt(1); + broadcast = (GComponent)GetChildAt(2); + money = (new_topmoney)GetChildAt(3); + gold = (new_topgold)GetChildAt(4); + btn_setting = (GButton)GetChildAt(5); + btn_noads = (GButton)GetChildAt(6); + btn_task = (btn_battle)GetChildAt(7); + btn_menu = (GButton)GetChildAt(8); + btn_saveingpot = (GButton)GetChildAt(9); + Btn_SignIn = (GButton)GetChildAt(10); + TopBox = (GGroup)GetChildAt(11); + btn_look_ad = (btn_look_ad)GetChildAt(12); + btn_clear = (btn_battle)GetChildAt(13); + btn_three_day = (GButton)GetChildAt(14); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs.meta b/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs.meta new file mode 100644 index 0000000..5184487 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G003_play/sheep_play.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1d22dba0866d2a241867e888812703d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview.meta new file mode 100644 index 0000000..c366f17 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: afdff04b74ee7dd45a754c1fccaa12c4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs new file mode 100644 index 0000000..26aee6d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs @@ -0,0 +1,18 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G004_webview +{ + public class G004_webviewBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(btn_type.URL, typeof(btn_type)); + UIObjectFactory.SetPackageItemExtension(com_webtop.URL, typeof(com_webtop)); + UIObjectFactory.SetPackageItemExtension(com_webview.URL, typeof(com_webview)); + UIObjectFactory.SetPackageItemExtension(btn_fly.URL, typeof(btn_fly)); + UIObjectFactory.SetPackageItemExtension(btn_icon.URL, typeof(btn_icon)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs.meta new file mode 100644 index 0000000..843c08b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/G004_webviewBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 74dfbe5fdc6f8e64bae7972d7fe1de77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs new file mode 100644 index 0000000..3773e0e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G004_webview +{ + public partial class btn_fly : GButton + { + public GImage light; + public Transition t0; + public Transition t1; + public const string URL = "ui://bfkmhq3qym5rf"; + + public static btn_fly CreateInstance() + { + return (btn_fly)UIPackage.CreateObject("G004_webview", "btn_fly"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + light = (GImage)GetChildAt(2); + t0 = GetTransitionAt(0); + t1 = GetTransitionAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs.meta new file mode 100644 index 0000000..227e57b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_fly.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb7b78f2379c8ab418f8f50bc16c751e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs new file mode 100644 index 0000000..551e996 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G004_webview +{ + public partial class btn_icon : GButton + { + public Controller cont_state; + public GImage pb_time; + public Transition fx_ready; + public const string URL = "ui://bfkmhq3qym5rg"; + + public static btn_icon CreateInstance() + { + return (btn_icon)UIPackage.CreateObject("G004_webview", "btn_icon"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_state = GetControllerAt(0); + pb_time = (GImage)GetChildAt(2); + fx_ready = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs.meta new file mode 100644 index 0000000..7fad6d3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_icon.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42b50821c281a6648b005f229defca2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs new file mode 100644 index 0000000..1492a85 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G004_webview +{ + public partial class btn_type : GButton + { + public Controller cont_type; + public Controller cont_tab; + public GTextField text_type; + public const string URL = "ui://bfkmhq3qfbkwd"; + + public static btn_type CreateInstance() + { + return (btn_type)UIPackage.CreateObject("G004_webview", "btn_type"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_type = GetControllerAt(0); + cont_tab = GetControllerAt(1); + text_type = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs.meta new file mode 100644 index 0000000..2c8974a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/btn_type.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5ddbbd2e8bbf9474c82e036a16df78ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs new file mode 100644 index 0000000..6da8bdd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G004_webview +{ + public partial class com_webtop : GComponent + { + public GTextField text_num; + public GProgressBar pb_num; + public GTextField text_more; + public GImage icon_101; + public GGroup ContentBox; + public const string URL = "ui://bfkmhq3qfbkwe"; + + public static com_webtop CreateInstance() + { + return (com_webtop)UIPackage.CreateObject("G004_webview", "com_webtop"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_num = (GTextField)GetChildAt(1); + pb_num = (GProgressBar)GetChildAt(2); + text_more = (GTextField)GetChildAt(3); + icon_101 = (GImage)GetChildAt(4); + ContentBox = (GGroup)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs.meta new file mode 100644 index 0000000..dc3e0a9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webtop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2703e7bdf40fe93428fbdecd2d4253aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs new file mode 100644 index 0000000..63d963f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G004_webview +{ + public partial class com_webview : GComponent + { + public GButton btn_close; + public GTextField money_text; + public GGroup TopBox; + public com_webtop com_top; + public GButton btn_out; + public btn_icon btn_icon; + public GGraph fly_area; + public GComponent com_fly; + public const string URL = "ui://bfkmhq3qfd7s0"; + + public static com_webview CreateInstance() + { + return (com_webview)UIPackage.CreateObject("G004_webview", "com_webview"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_close = (GButton)GetChildAt(1); + money_text = (GTextField)GetChildAt(2); + TopBox = (GGroup)GetChildAt(3); + com_top = (com_webtop)GetChildAt(4); + btn_out = (GButton)GetChildAt(5); + btn_icon = (btn_icon)GetChildAt(7); + fly_area = (GGraph)GetChildAt(8); + com_fly = (GComponent)GetChildAt(9); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs.meta b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs.meta new file mode 100644 index 0000000..2d153fd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G004_webview/com_webview.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 934680ba314be3c4282810082dc7e69d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu.meta new file mode 100644 index 0000000..7fc1f33 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 61f393ff894eb7944aae3187dc969e45 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs new file mode 100644 index 0000000..2782eeb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs @@ -0,0 +1,20 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G006_menu +{ + public class G006_menuBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(btn_switch_sound.URL, typeof(btn_switch_sound)); + UIObjectFactory.SetPackageItemExtension(btn_img.URL, typeof(btn_img)); + UIObjectFactory.SetPackageItemExtension(btn_lang.URL, typeof(btn_lang)); + UIObjectFactory.SetPackageItemExtension(btn_switch_music.URL, typeof(btn_switch_music)); + UIObjectFactory.SetPackageItemExtension(com_edit.URL, typeof(com_edit)); + UIObjectFactory.SetPackageItemExtension(btn_lang_red.URL, typeof(btn_lang_red)); + UIObjectFactory.SetPackageItemExtension(com_menu.URL, typeof(com_menu)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs.meta new file mode 100644 index 0000000..f753230 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/G006_menuBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f53a5e4ada23a3e468eda86dd147bc77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs new file mode 100644 index 0000000..902f713 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class btn_img : GButton + { + public Controller cont_select; + public GComponent head_loader; + public const string URL = "ui://mqs6max7rezm1d"; + + public static btn_img CreateInstance() + { + return (btn_img)UIPackage.CreateObject("G006_menu", "btn_img"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_select = GetControllerAt(0); + head_loader = (GComponent)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs.meta new file mode 100644 index 0000000..8e7d876 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_img.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d752b437da88a714e8d696efaefdf46c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs new file mode 100644 index 0000000..c4ff91b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class btn_lang : GButton + { + public Controller cont_btn; + public Controller btn_state; + public GTextField text_lang; + public const string URL = "ui://mqs6max7rezm1e"; + + public static btn_lang CreateInstance() + { + return (btn_lang)UIPackage.CreateObject("G006_menu", "btn_lang"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_btn = GetControllerAt(0); + btn_state = GetControllerAt(1); + text_lang = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs.meta new file mode 100644 index 0000000..605846a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 041462d95ab821d44984eeb45c72ce1e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs new file mode 100644 index 0000000..7916998 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class btn_lang_red : GButton + { + public GTextField text_lang; + public const string URL = "ui://mqs6max7trht4m"; + + public static btn_lang_red CreateInstance() + { + return (btn_lang_red)UIPackage.CreateObject("G006_menu", "btn_lang_red"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_lang = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs.meta new file mode 100644 index 0000000..ce8332d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_lang_red.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a7e77f8ae8c61d47b0f19bbc4f43dd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs new file mode 100644 index 0000000..2c1e07c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class btn_switch_music : GButton + { + public Controller cont_button; + public const string URL = "ui://mqs6max7rezm1f"; + + public static btn_switch_music CreateInstance() + { + return (btn_switch_music)UIPackage.CreateObject("G006_menu", "btn_switch_music"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_button = GetControllerAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs.meta new file mode 100644 index 0000000..adc6731 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_music.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54a2025b4d70b2045bd9ff2422b661b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs new file mode 100644 index 0000000..9201e6a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class btn_switch_sound : GButton + { + public Controller cont_button; + public const string URL = "ui://mqs6max7ahbj22"; + + public static btn_switch_sound CreateInstance() + { + return (btn_switch_sound)UIPackage.CreateObject("G006_menu", "btn_switch_sound"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_button = GetControllerAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs.meta new file mode 100644 index 0000000..ce589a4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/btn_switch_sound.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b54386d4681fbc940a564dbf1d94c291 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs new file mode 100644 index 0000000..fbedc54 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class com_edit : GComponent + { + public GTextField t2; + public GGraph img_cheat; + public GList list_avatar; + public GTextInput textp_name; + public GButton btn_ok; + public GButton closeButton; + public const string URL = "ui://mqs6max7si1f0"; + + public static com_edit CreateInstance() + { + return (com_edit)UIPackage.CreateObject("G006_menu", "com_edit"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + t2 = (GTextField)GetChildAt(4); + img_cheat = (GGraph)GetChildAt(5); + list_avatar = (GList)GetChildAt(10); + textp_name = (GTextInput)GetChildAt(11); + btn_ok = (GButton)GetChildAt(12); + closeButton = (GButton)GetChildAt(14); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs.meta new file mode 100644 index 0000000..715f6a7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_edit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 144eba9fab6b7e04080f216db5137724 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs new file mode 100644 index 0000000..32ffc3f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs @@ -0,0 +1,53 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G006_menu +{ + public partial class com_menu : GComponent + { + public Controller switchgift; + public GTextField title0; + public GButton btn_close; + public GTextField text_uid; + public GTextField text_version; + public GTextField title3; + public btn_switch_sound btn_music; + public GTextField title1; + public btn_switch_sound btn_sound; + public btn_lang btn_record; + public btn_lang btn_contact; + public btn_lang btn_pri; + public btn_lang btn_terms; + public btn_lang_red ExitBtn; + public btn_lang btn_restore; + public const string URL = "ui://mqs6max7u6tn12"; + + public static com_menu CreateInstance() + { + return (com_menu)UIPackage.CreateObject("G006_menu", "com_menu"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + switchgift = GetControllerAt(0); + title0 = (GTextField)GetChildAt(2); + btn_close = (GButton)GetChildAt(3); + text_uid = (GTextField)GetChildAt(5); + text_version = (GTextField)GetChildAt(6); + title3 = (GTextField)GetChildAt(8); + btn_music = (btn_switch_sound)GetChildAt(9); + title1 = (GTextField)GetChildAt(11); + btn_sound = (btn_switch_sound)GetChildAt(12); + btn_record = (btn_lang)GetChildAt(14); + btn_contact = (btn_lang)GetChildAt(15); + btn_pri = (btn_lang)GetChildAt(16); + btn_terms = (btn_lang)GetChildAt(17); + ExitBtn = (btn_lang_red)GetChildAt(18); + btn_restore = (btn_lang)GetChildAt(19); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs.meta b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs.meta new file mode 100644 index 0000000..4f633ef --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G006_menu/com_menu.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 593f063e25f563f47afd9fb09fc18c1a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup.meta new file mode 100644 index 0000000..f996493 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5982cd2443380764e8ce6821dad6a09e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs new file mode 100644 index 0000000..fab2f50 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs @@ -0,0 +1,32 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G007_makeup +{ + public class G007_makeupBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_lastname.URL, typeof(com_lastname)); + UIObjectFactory.SetPackageItemExtension(com_firstname.URL, typeof(com_firstname)); + UIObjectFactory.SetPackageItemExtension(com_enter.URL, typeof(com_enter)); + UIObjectFactory.SetPackageItemExtension(btn_edit.URL, typeof(btn_edit)); + UIObjectFactory.SetPackageItemExtension(com_task.URL, typeof(com_task)); + UIObjectFactory.SetPackageItemExtension(cash_levelcom.URL, typeof(cash_levelcom)); + UIObjectFactory.SetPackageItemExtension(level_btn.URL, typeof(level_btn)); + UIObjectFactory.SetPackageItemExtension(com_regulation.URL, typeof(com_regulation)); + UIObjectFactory.SetPackageItemExtension(com_PixPay.URL, typeof(com_PixPay)); + UIObjectFactory.SetPackageItemExtension(btn_confirm.URL, typeof(btn_confirm)); + UIObjectFactory.SetPackageItemExtension(com_trans.URL, typeof(com_trans)); + UIObjectFactory.SetPackageItemExtension(com_info.URL, typeof(com_info)); + UIObjectFactory.SetPackageItemExtension(com_cord.URL, typeof(com_cord)); + UIObjectFactory.SetPackageItemExtension(com_rank.URL, typeof(com_rank)); + UIObjectFactory.SetPackageItemExtension(com_newRecord.URL, typeof(com_newRecord)); + UIObjectFactory.SetPackageItemExtension(btn_watch.URL, typeof(btn_watch)); + UIObjectFactory.SetPackageItemExtension(com_step.URL, typeof(com_step)); + UIObjectFactory.SetPackageItemExtension(com_confirm.URL, typeof(com_confirm)); + UIObjectFactory.SetPackageItemExtension(com_record.URL, typeof(com_record)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs.meta new file mode 100644 index 0000000..5a42c2e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/G007_makeupBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c2ad6f203e4e15742b66472393c7d707 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs new file mode 100644 index 0000000..eb5dee7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class btn_confirm : GButton + { + public Controller country; + public GTextField con; + public const string URL = "ui://dgtrojo7if1e7"; + + public static btn_confirm CreateInstance() + { + return (btn_confirm)UIPackage.CreateObject("G007_makeup", "btn_confirm"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + country = GetControllerAt(0); + con = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs.meta new file mode 100644 index 0000000..5255b9d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_confirm.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9be30cde23215534ea07f4e906ad6913 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs new file mode 100644 index 0000000..e5d93c5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class btn_edit : GButton + { + public GTextField text_title; + public const string URL = "ui://dgtrojo7deiw1s"; + + public static btn_edit CreateInstance() + { + return (btn_edit)UIPackage.CreateObject("G007_makeup", "btn_edit"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_title = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs.meta new file mode 100644 index 0000000..8247092 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_edit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ce8ed5fd8a40ee418ded4af1c9075f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs new file mode 100644 index 0000000..5f20369 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class btn_watch : GButton + { + public Controller show_cd; + public GTextField text_cd; + public const string URL = "ui://dgtrojo7qgv24n"; + + public static btn_watch CreateInstance() + { + return (btn_watch)UIPackage.CreateObject("G007_makeup", "btn_watch"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + show_cd = GetControllerAt(0); + text_cd = (GTextField)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs.meta new file mode 100644 index 0000000..c32c6b3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/btn_watch.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fbe383c895da9cb44bbd18b5f3c7bdcb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs new file mode 100644 index 0000000..c26da48 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class cash_levelcom : GComponent + { + public level_btn btn_0; + public level_btn btn_1; + public level_btn btn_2; + public const string URL = "ui://dgtrojo7fzz842"; + + public static cash_levelcom CreateInstance() + { + return (cash_levelcom)UIPackage.CreateObject("G007_makeup", "cash_levelcom"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_0 = (level_btn)GetChildAt(0); + btn_1 = (level_btn)GetChildAt(1); + btn_2 = (level_btn)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs.meta new file mode 100644 index 0000000..369f3b0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/cash_levelcom.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f1580e1bf2d82b489793b40687f0fdb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs new file mode 100644 index 0000000..40ccc40 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_PixPay : GComponent + { + public GButton btn_close; + public GTextInput input_1; + public GButton btn_comfirmar; + public GTextInput input_2; + public GTextInput input_3; + public GButton btn_close_view; + public const string URL = "ui://dgtrojo7heqb2o"; + + public static com_PixPay CreateInstance() + { + return (com_PixPay)UIPackage.CreateObject("G007_makeup", "com_PixPay"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_close = (GButton)GetChildAt(1); + input_1 = (GTextInput)GetChildAt(7); + btn_comfirmar = (GButton)GetChildAt(8); + input_2 = (GTextInput)GetChildAt(10); + input_3 = (GTextInput)GetChildAt(12); + btn_close_view = (GButton)GetChildAt(13); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs.meta new file mode 100644 index 0000000..c3622fb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_PixPay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c5a7cb61def6a1e468c8880a91445ab1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs new file mode 100644 index 0000000..7889673 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs @@ -0,0 +1,119 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_confirm : GComponent + { + public Controller cont_state; + public Controller cont_confirm; + public Controller lang; + public Controller show_pay; + public GButton btn_back; + public GTextField Text_Title; + public cash_levelcom com_cashlevel; + public GGroup TopBox; + public GTextField text_cashdate; + public GTextField text_cashdate_2; + public GTextField text_number0; + public GTextField text_cashdate_3; + public GTextField text_number1; + public GTextField text_cashdate_4; + public GTextField text_number2; + public GTextField text_smaill_title; + public com_enter com_info; + public com_firstname com_fname; + public com_lastname com_lname; + public GButton btn_tab; + public GButton btn_earn; + public GTextField text_condi1; + public GProgressBar pb_condi1; + public GTextField text_wallet; + public GTextField text_cash; + public GTextField text_account; + public GButton btn_cashout; + public com_task com_task; + public com_newRecord com_newRecord; + public btn_watch btn_watch; + public GTextField text_payhint; + public GTextField text_payhint_2; + public GTextField text_query; + public com_info com_pay; + public GButton btn_confirm; + public GTextField text_smaill_title_2; + public GTextField text_cashneedlv; + public GTextField text_nowcash; + public GButton btn_check_level; + public GButton btn_record; + public GTextField nrules; + public GTextField nrules_2; + public GRichTextField pay_text1; + public GButton btn_pay1; + public GButton btn_close; + public GTextField text_condi2; + public GProgressBar pb_condi2; + public Transition t0; + public const string URL = "ui://dgtrojo7ut66d"; + + public static com_confirm CreateInstance() + { + return (com_confirm)UIPackage.CreateObject("G007_makeup", "com_confirm"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_state = GetControllerAt(0); + cont_confirm = GetControllerAt(1); + lang = GetControllerAt(2); + show_pay = GetControllerAt(3); + btn_back = (GButton)GetChildAt(0); + Text_Title = (GTextField)GetChildAt(2); + com_cashlevel = (cash_levelcom)GetChildAt(5); + TopBox = (GGroup)GetChildAt(6); + text_cashdate = (GTextField)GetChildAt(8); + text_cashdate_2 = (GTextField)GetChildAt(10); + text_number0 = (GTextField)GetChildAt(11); + text_cashdate_3 = (GTextField)GetChildAt(14); + text_number1 = (GTextField)GetChildAt(15); + text_cashdate_4 = (GTextField)GetChildAt(18); + text_number2 = (GTextField)GetChildAt(19); + text_smaill_title = (GTextField)GetChildAt(22); + com_info = (com_enter)GetChildAt(23); + com_fname = (com_firstname)GetChildAt(24); + com_lname = (com_lastname)GetChildAt(25); + btn_tab = (GButton)GetChildAt(26); + btn_earn = (GButton)GetChildAt(27); + text_condi1 = (GTextField)GetChildAt(30); + pb_condi1 = (GProgressBar)GetChildAt(31); + text_wallet = (GTextField)GetChildAt(34); + text_cash = (GTextField)GetChildAt(36); + text_account = (GTextField)GetChildAt(37); + btn_cashout = (GButton)GetChildAt(42); + com_task = (com_task)GetChildAt(43); + com_newRecord = (com_newRecord)GetChildAt(44); + btn_watch = (btn_watch)GetChildAt(45); + text_payhint = (GTextField)GetChildAt(46); + text_payhint_2 = (GTextField)GetChildAt(47); + text_query = (GTextField)GetChildAt(48); + com_pay = (com_info)GetChildAt(50); + btn_confirm = (GButton)GetChildAt(51); + text_smaill_title_2 = (GTextField)GetChildAt(53); + text_cashneedlv = (GTextField)GetChildAt(54); + text_nowcash = (GTextField)GetChildAt(57); + btn_check_level = (GButton)GetChildAt(58); + btn_record = (GButton)GetChildAt(59); + nrules = (GTextField)GetChildAt(60); + nrules_2 = (GTextField)GetChildAt(61); + pay_text1 = (GRichTextField)GetChildAt(63); + btn_pay1 = (GButton)GetChildAt(64); + btn_close = (GButton)GetChildAt(66); + text_condi2 = (GTextField)GetChildAt(67); + pb_condi2 = (GProgressBar)GetChildAt(68); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs.meta new file mode 100644 index 0000000..d55094a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_confirm.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a1efdb9261eb66c469663812353dc8d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs new file mode 100644 index 0000000..7a813cb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_cord : GComponent + { + public GTextField text_payer; + public GTextField text_amt; + public GLoader loader_logo; + public GTextField status_text_1; + public GTextField email_text; + public GTextField time_text; + public GTextField status_text_0; + public GTextField text_name; + public GTextField number_text; + public const string URL = "ui://dgtrojo7meh8c"; + + public static com_cord CreateInstance() + { + return (com_cord)UIPackage.CreateObject("G007_makeup", "com_cord"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_payer = (GTextField)GetChildAt(1); + text_amt = (GTextField)GetChildAt(3); + loader_logo = (GLoader)GetChildAt(4); + status_text_1 = (GTextField)GetChildAt(5); + email_text = (GTextField)GetChildAt(7); + time_text = (GTextField)GetChildAt(9); + status_text_0 = (GTextField)GetChildAt(12); + text_name = (GTextField)GetChildAt(13); + number_text = (GTextField)GetChildAt(14); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs.meta new file mode 100644 index 0000000..75eda1f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_cord.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79cc21e753879d14ea0be33aec82ac35 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs new file mode 100644 index 0000000..a0b5904 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_enter : GComponent + { + public Controller cont_type; + public GTextInput enter_email; + public GTextInput enter_phone; + public GTextField ph_7; + public const string URL = "ui://dgtrojo7deiw1k"; + + public static com_enter CreateInstance() + { + return (com_enter)UIPackage.CreateObject("G007_makeup", "com_enter"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_type = GetControllerAt(0); + enter_email = (GTextInput)GetChildAt(3); + enter_phone = (GTextInput)GetChildAt(4); + ph_7 = (GTextField)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs.meta new file mode 100644 index 0000000..4348c6c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_enter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aabb1bafc4c0d3147b5ab63847860847 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs new file mode 100644 index 0000000..d0cce56 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_firstname : GComponent + { + public GTextInput enter_fname; + public const string URL = "ui://dgtrojo7deiw1j"; + + public static com_firstname CreateInstance() + { + return (com_firstname)UIPackage.CreateObject("G007_makeup", "com_firstname"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + enter_fname = (GTextInput)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs.meta new file mode 100644 index 0000000..951f642 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_firstname.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c486d2625d916dd4d960a344bac81d3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs new file mode 100644 index 0000000..043184b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_info : GComponent + { + public Controller cont_counrty; + public GTextField text_name; + public GTextField text_email; + public GButton btn_change; + public GButton btn_menu; + public const string URL = "ui://dgtrojo7if1eb"; + + public static com_info CreateInstance() + { + return (com_info)UIPackage.CreateObject("G007_makeup", "com_info"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_counrty = GetControllerAt(0); + text_name = (GTextField)GetChildAt(0); + text_email = (GTextField)GetChildAt(1); + btn_change = (GButton)GetChildAt(2); + btn_menu = (GButton)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs.meta new file mode 100644 index 0000000..debf1e9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_info.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f77a1085a48aa7a409a990bb2ba4718a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs new file mode 100644 index 0000000..e3a4e17 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_lastname : GComponent + { + public GTextInput enter_lname; + public const string URL = "ui://dgtrojo7deiw1i"; + + public static com_lastname CreateInstance() + { + return (com_lastname)UIPackage.CreateObject("G007_makeup", "com_lastname"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + enter_lname = (GTextInput)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs.meta new file mode 100644 index 0000000..d6c616c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_lastname.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ec32ce1accc5c344b94a7133accf901 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs new file mode 100644 index 0000000..ea2e9d8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_newRecord : GComponent + { + public com_cord com_cord; + public com_rank com_rank; + public const string URL = "ui://dgtrojo7qgv24k"; + + public static com_newRecord CreateInstance() + { + return (com_newRecord)UIPackage.CreateObject("G007_makeup", "com_newRecord"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + com_cord = (com_cord)GetChildAt(0); + com_rank = (com_rank)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs.meta new file mode 100644 index 0000000..009f209 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_newRecord.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b63a6ca28c346844af41b9bc1e0eb0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs new file mode 100644 index 0000000..d4c261e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs @@ -0,0 +1,43 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_rank : GComponent + { + public Controller content1; + public Controller content2; + public Controller content3; + public GTextField text_ranks; + public GTextField text_rank1; + public GTextField text_rank2; + public GTextField text_rank3; + public GImage img_gou1; + public GImage img_gou2; + public GImage img_gou3; + public const string URL = "ui://dgtrojo7qgv24f"; + + public static com_rank CreateInstance() + { + return (com_rank)UIPackage.CreateObject("G007_makeup", "com_rank"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + content1 = GetControllerAt(0); + content2 = GetControllerAt(1); + content3 = GetControllerAt(2); + text_ranks = (GTextField)GetChildAt(3); + text_rank1 = (GTextField)GetChildAt(5); + text_rank2 = (GTextField)GetChildAt(6); + text_rank3 = (GTextField)GetChildAt(7); + img_gou1 = (GImage)GetChildAt(8); + img_gou2 = (GImage)GetChildAt(9); + img_gou3 = (GImage)GetChildAt(10); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs.meta new file mode 100644 index 0000000..69b993b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_rank.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1fbc965b17bae6e409d9eae1ee5042a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs new file mode 100644 index 0000000..3aba29e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_record : GComponent + { + public Controller cont_show; + public GList list_record; + public GButton btn_help; + public GButton closeButton; + public const string URL = "ui://dgtrojo7w3axa"; + + public static com_record CreateInstance() + { + return (com_record)UIPackage.CreateObject("G007_makeup", "com_record"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_show = GetControllerAt(0); + list_record = (GList)GetChildAt(3); + btn_help = (GButton)GetChildAt(4); + closeButton = (GButton)GetChildAt(7); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs.meta new file mode 100644 index 0000000..7465b7c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_record.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37adff47f17732f499bab28413135a88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs new file mode 100644 index 0000000..030905e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_regulation : GComponent + { + public GButton closeButton; + public GTextField title0; + public const string URL = "ui://dgtrojo7ghqt2"; + + public static com_regulation CreateInstance() + { + return (com_regulation)UIPackage.CreateObject("G007_makeup", "com_regulation"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + closeButton = (GButton)GetChildAt(3); + title0 = (GTextField)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs.meta new file mode 100644 index 0000000..8b6f20d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_regulation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a1f2149ace158f4c8e52bed0977465d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs new file mode 100644 index 0000000..9dfacbf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs @@ -0,0 +1,37 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_step : GComponent + { + public Controller lang; + public com_info com_info; + public btn_confirm btn_confirm; + public com_trans com_trans; + public GTextField text_warn; + public GLoader loader_payer; + public Transition fx_in; + public const string URL = "ui://dgtrojo7rezm0"; + + public static com_step CreateInstance() + { + return (com_step)UIPackage.CreateObject("G007_makeup", "com_step"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + lang = GetControllerAt(0); + com_info = (com_info)GetChildAt(1); + btn_confirm = (btn_confirm)GetChildAt(2); + com_trans = (com_trans)GetChildAt(4); + text_warn = (GTextField)GetChildAt(5); + loader_payer = (GLoader)GetChildAt(6); + fx_in = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs.meta new file mode 100644 index 0000000..645c3e0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_step.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41ee54cb2124a9f4782c56092e83f4bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs new file mode 100644 index 0000000..8217ab6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs @@ -0,0 +1,43 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_task : GComponent + { + public Controller cont_process; + public Controller lang; + public GTextField text_orderid; + public GTextField text_task_title; + public GTextField text_ads; + public GRichTextField pay_text1; + public GButton btn_pay2; + public GTextField title; + public GTextField title_2; + public GTextField text_payer; + public const string URL = "ui://dgtrojo7es171x"; + + public static com_task CreateInstance() + { + return (com_task)UIPackage.CreateObject("G007_makeup", "com_task"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_process = GetControllerAt(0); + lang = GetControllerAt(1); + text_orderid = (GTextField)GetChildAt(3); + text_task_title = (GTextField)GetChildAt(9); + text_ads = (GTextField)GetChildAt(10); + pay_text1 = (GRichTextField)GetChildAt(11); + btn_pay2 = (GButton)GetChildAt(12); + title = (GTextField)GetChildAt(13); + title_2 = (GTextField)GetChildAt(14); + text_payer = (GTextField)GetChildAt(20); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs.meta new file mode 100644 index 0000000..5619ab8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_task.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d699efde1e51cf4bbe4512ae3912eef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs new file mode 100644 index 0000000..e0b4d29 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class com_trans : GComponent + { + public Controller cont_country; + public GLoader loader_payer; + public const string URL = "ui://dgtrojo7if1e9"; + + public static com_trans CreateInstance() + { + return (com_trans)UIPackage.CreateObject("G007_makeup", "com_trans"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_country = GetControllerAt(0); + loader_payer = (GLoader)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs.meta new file mode 100644 index 0000000..3717337 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/com_trans.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea3fb1c9d57360e42a396662ff8e5133 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs b/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs new file mode 100644 index 0000000..1790fa8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G007_makeup +{ + public partial class level_btn : GButton + { + public Controller btn_state; + public GTextField text_Level0; + public GTextField text_Level1; + public GTextField text_Level2; + public GImage img_check; + public GTextField text_level1; + public const string URL = "ui://dgtrojo7fzz843"; + + public static level_btn CreateInstance() + { + return (level_btn)UIPackage.CreateObject("G007_makeup", "level_btn"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_state = GetControllerAt(0); + text_Level0 = (GTextField)GetChildAt(3); + text_Level1 = (GTextField)GetChildAt(4); + text_Level2 = (GTextField)GetChildAt(5); + img_check = (GImage)GetChildAt(6); + text_level1 = (GTextField)GetChildAt(8); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs.meta b/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs.meta new file mode 100644 index 0000000..0cd0931 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G007_makeup/level_btn.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bf739ac503ea4fa43ac7076030e6b6b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward.meta new file mode 100644 index 0000000..db12ffc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 49f107581e939a84cb98caea04c4bba2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs new file mode 100644 index 0000000..301ffa3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs @@ -0,0 +1,22 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G008_reward +{ + public class G008_rewardBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_packreward.URL, typeof(com_packreward)); + UIObjectFactory.SetPackageItemExtension(com_adcoming.URL, typeof(com_adcoming)); + UIObjectFactory.SetPackageItemExtension(com_lvsuccess.URL, typeof(com_lvsuccess)); + UIObjectFactory.SetPackageItemExtension(com_rewardbox.URL, typeof(com_rewardbox)); + UIObjectFactory.SetPackageItemExtension(com_revive.URL, typeof(com_revive)); + UIObjectFactory.SetPackageItemExtension(com_reward.URL, typeof(com_reward)); + UIObjectFactory.SetPackageItemExtension(pack_panel.URL, typeof(pack_panel)); + UIObjectFactory.SetPackageItemExtension(com_payloading.URL, typeof(com_payloading)); + UIObjectFactory.SetPackageItemExtension(pack_panelparent.URL, typeof(pack_panelparent)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs.meta new file mode 100644 index 0000000..8d8e4f8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/G008_rewardBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 882fd69cfb391f94c8bdccdab2fd595c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs new file mode 100644 index 0000000..cd16ebf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_adcoming : GComponent + { + public GTextField money_text; + public GButton btn_removead; + public GTextField time_text; + public Transition t0; + public const string URL = "ui://1x1w9cxnagfu1q"; + + public static com_adcoming CreateInstance() + { + return (com_adcoming)UIPackage.CreateObject("G008_reward", "com_adcoming"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + money_text = (GTextField)GetChildAt(2); + btn_removead = (GButton)GetChildAt(3); + time_text = (GTextField)GetChildAt(4); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs.meta new file mode 100644 index 0000000..403611f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_adcoming.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d1e4b010b9ffcd47ba53b3be873b08e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs new file mode 100644 index 0000000..8e29726 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs @@ -0,0 +1,51 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_lvsuccess : GComponent + { + public Controller state; + public Controller switchgift; + public GGraph bg_parent; + public GComponent top_money; + public GImage tips_bg; + public GTextField tips_text; + public GTextField money_text; + public GButton btn_adclaim; + public GButton btn_claim; + public GButton btn_restart; + public GComponent com_cash; + public GComponent gold; + public GButton btn_revive; + public Transition t0; + public const string URL = "ui://1x1w9cxnagfue"; + + public static com_lvsuccess CreateInstance() + { + return (com_lvsuccess)UIPackage.CreateObject("G008_reward", "com_lvsuccess"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + switchgift = GetControllerAt(1); + bg_parent = (GGraph)GetChildAt(0); + top_money = (GComponent)GetChildAt(3); + tips_bg = (GImage)GetChildAt(4); + tips_text = (GTextField)GetChildAt(5); + money_text = (GTextField)GetChildAt(7); + btn_adclaim = (GButton)GetChildAt(8); + btn_claim = (GButton)GetChildAt(9); + btn_restart = (GButton)GetChildAt(11); + com_cash = (GComponent)GetChildAt(12); + gold = (GComponent)GetChildAt(16); + btn_revive = (GButton)GetChildAt(19); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs.meta new file mode 100644 index 0000000..bf74fa7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_lvsuccess.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d2c12761a732fc54697c115c55792a14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs new file mode 100644 index 0000000..53236cb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_packreward : GComponent + { + public pack_panelparent panel_parent; + public GComponent gold; + public const string URL = "ui://1x1w9cxnagfu17"; + + public static com_packreward CreateInstance() + { + return (com_packreward)UIPackage.CreateObject("G008_reward", "com_packreward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + panel_parent = (pack_panelparent)GetChildAt(0); + gold = (GComponent)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs.meta new file mode 100644 index 0000000..ac3e189 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_packreward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e846338b6975384783726365a031d00 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs new file mode 100644 index 0000000..36a96da --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_payloading : GComponent + { + public Transition t0; + public const string URL = "ui://1x1w9cxnttbj1w"; + + public static com_payloading CreateInstance() + { + return (com_payloading)UIPackage.CreateObject("G008_reward", "com_payloading"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs.meta new file mode 100644 index 0000000..f1aa1e6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_payloading.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69aa05561b722e5499162584c5aee747 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs new file mode 100644 index 0000000..08ef251 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_revive : GComponent + { + public Controller cont_iswacth; + public GButton btn_close; + public GButton btn_revive; + public GButton btn_AdRevive; + public GButton btn_back; + public const string URL = "ui://1x1w9cxngxpr2z"; + + public static com_revive CreateInstance() + { + return (com_revive)UIPackage.CreateObject("G008_reward", "com_revive"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_iswacth = GetControllerAt(0); + btn_close = (GButton)GetChildAt(2); + btn_revive = (GButton)GetChildAt(7); + btn_AdRevive = (GButton)GetChildAt(8); + btn_back = (GButton)GetChildAt(9); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs.meta new file mode 100644 index 0000000..b046040 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_revive.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b60fd650fee32842856ddf36d083329 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs new file mode 100644 index 0000000..4f84278 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_reward : GComponent + { + public Controller cont_collect; + public Controller cont_white; + public GComponent com_playbox; + public GComponent btn_nor; + public GGraph fx_place; + public GTextField text_num; + public GButton btn_multi; + public GButton btn_collect; + public Transition t0; + public const string URL = "ui://1x1w9cxnkj3h1"; + + public static com_reward CreateInstance() + { + return (com_reward)UIPackage.CreateObject("G008_reward", "com_reward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_collect = GetControllerAt(0); + cont_white = GetControllerAt(1); + com_playbox = (GComponent)GetChildAt(0); + btn_nor = (GComponent)GetChildAt(4); + fx_place = (GGraph)GetChildAt(5); + text_num = (GTextField)GetChildAt(8); + btn_multi = (GButton)GetChildAt(9); + btn_collect = (GButton)GetChildAt(10); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs.meta new file mode 100644 index 0000000..8d54363 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_reward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b684a589887a47a4787131de0ef2b15c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs new file mode 100644 index 0000000..df5c8df --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class com_rewardbox : GComponent + { + public Controller switchgift; + public GTextField gold_text; + public GButton btn_lookad; + public GButton btn_close; + public const string URL = "ui://1x1w9cxnagfuk"; + + public static com_rewardbox CreateInstance() + { + return (com_rewardbox)UIPackage.CreateObject("G008_reward", "com_rewardbox"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + switchgift = GetControllerAt(0); + gold_text = (GTextField)GetChildAt(3); + btn_lookad = (GButton)GetChildAt(4); + btn_close = (GButton)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs.meta new file mode 100644 index 0000000..7be121e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/com_rewardbox.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a229c7248e1a51e43a13c27cb47f4328 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs new file mode 100644 index 0000000..60fd3b3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs @@ -0,0 +1,61 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class pack_panel : GComponent + { + public Controller pay_type; + public GButton btn_close0; + public GTextField text_hasAdCount; + public GTextField text_goldnum; + public GTextField text_outnum; + public GImage text_backnum; + public GTextField text_backnum1; + public GTextField text_refreshnum; + public GButton btn_buypack; + public GTextField text_needAdCount1; + public GButton btn_buyPackClaim; + public GButton btn_close1; + public GTextField title1; + public GTextField text_goldnum2; + public GButton btn_buyremovead; + public GTextField text_needAdCount2; + public GButton btn_RemoveAdClaim; + public GButton btn_max_pack; + public GButton btn_max_remove; + public const string URL = "ui://1x1w9cxnttbj1v"; + + public static pack_panel CreateInstance() + { + return (pack_panel)UIPackage.CreateObject("G008_reward", "pack_panel"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + pay_type = GetControllerAt(0); + btn_close0 = (GButton)GetChildAt(3); + text_hasAdCount = (GTextField)GetChildAt(5); + text_goldnum = (GTextField)GetChildAt(8); + text_outnum = (GTextField)GetChildAt(12); + text_backnum = (GImage)GetChildAt(13); + text_backnum1 = (GTextField)GetChildAt(14); + text_refreshnum = (GTextField)GetChildAt(16); + btn_buypack = (GButton)GetChildAt(17); + text_needAdCount1 = (GTextField)GetChildAt(18); + btn_buyPackClaim = (GButton)GetChildAt(19); + btn_close1 = (GButton)GetChildAt(24); + title1 = (GTextField)GetChildAt(26); + text_goldnum2 = (GTextField)GetChildAt(28); + btn_buyremovead = (GButton)GetChildAt(31); + text_needAdCount2 = (GTextField)GetChildAt(32); + btn_RemoveAdClaim = (GButton)GetChildAt(33); + btn_max_pack = (GButton)GetChildAt(34); + btn_max_remove = (GButton)GetChildAt(35); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs.meta new file mode 100644 index 0000000..6addb41 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 25daa1ee20a8d2941ba9f44c586d30dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs new file mode 100644 index 0000000..2090e50 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G008_reward +{ + public partial class pack_panelparent : GComponent + { + public pack_panel panel; + public const string URL = "ui://1x1w9cxnttbj1x"; + + public static pack_panelparent CreateInstance() + { + return (pack_panelparent)UIPackage.CreateObject("G008_reward", "pack_panelparent"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + panel = (pack_panel)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs.meta b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs.meta new file mode 100644 index 0000000..9979a68 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G008_reward/pack_panelparent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 84c451ad942545a49b65fd394f81a70b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video.meta b/Assets/CrazyZoo/FGUI/Package/G009_video.meta new file mode 100644 index 0000000..57b54b0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0d2133705ec907f45924af8a3f727740 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs new file mode 100644 index 0000000..37df9c3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs @@ -0,0 +1,22 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G009_video +{ + public class G009_videoBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_battlepass.URL, typeof(com_battlepass)); + UIObjectFactory.SetPackageItemExtension(com_passitem.URL, typeof(com_passitem)); + UIObjectFactory.SetPackageItemExtension(com_passreward.URL, typeof(com_passreward)); + UIObjectFactory.SetPackageItemExtension(com_gettaskreward.URL, typeof(com_gettaskreward)); + UIObjectFactory.SetPackageItemExtension(com_newtask.URL, typeof(com_newtask)); + UIObjectFactory.SetPackageItemExtension(com_toptab.URL, typeof(com_toptab)); + UIObjectFactory.SetPackageItemExtension(task_item.URL, typeof(task_item)); + UIObjectFactory.SetPackageItemExtension(btn_task.URL, typeof(btn_task)); + UIObjectFactory.SetPackageItemExtension(com_passunlock.URL, typeof(com_passunlock)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs.meta new file mode 100644 index 0000000..2ed59b0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/G009_videoBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17d0d2a790ddefe43b480d64c9254a53 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs new file mode 100644 index 0000000..74f47e3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class btn_task : GButton + { + public Controller state; + public GTextField progress_text; + public const string URL = "ui://y6hi0pcjagfuz"; + + public static btn_task CreateInstance() + { + return (btn_task)UIPackage.CreateObject("G009_video", "btn_task"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + progress_text = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs.meta new file mode 100644 index 0000000..8d93549 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/btn_task.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 175cf6dda1dbd064e82a9493a3c040d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs new file mode 100644 index 0000000..14a5e30 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs @@ -0,0 +1,47 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_battlepass : GComponent + { + public GTextField remain_time; + public GImage progress; + public GTextField now_exp; + public GImage TipTextBg; + public GTextField TipText; + public GComponent listTitle; + public GButton btn_pay; + public GTextField now_level; + public GButton btn_showtips; + public GGroup TopBox; + public GList pass_list; + public Transition t0; + public const string URL = "ui://y6hi0pcjagfu1t"; + + public static com_battlepass CreateInstance() + { + return (com_battlepass)UIPackage.CreateObject("G009_video", "com_battlepass"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + remain_time = (GTextField)GetChildAt(3); + progress = (GImage)GetChildAt(5); + now_exp = (GTextField)GetChildAt(7); + TipTextBg = (GImage)GetChildAt(8); + TipText = (GTextField)GetChildAt(10); + listTitle = (GComponent)GetChildAt(12); + btn_pay = (GButton)GetChildAt(13); + now_level = (GTextField)GetChildAt(14); + btn_showtips = (GButton)GetChildAt(15); + TopBox = (GGroup)GetChildAt(16); + pass_list = (GList)GetChildAt(17); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs.meta new file mode 100644 index 0000000..4075222 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_battlepass.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1fbde327a58a64a43ac1b16914ad9f77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs new file mode 100644 index 0000000..03a94df --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs @@ -0,0 +1,45 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_gettaskreward : GComponent + { + public Controller switchgift; + public GGraph bg_parent; + public GTextField money_text; + public GButton btn_adclaim; + public GButton btn_claim; + public GComponent com_cash; + public GComponent top_money; + public GImage tips_bg; + public GComponent gold; + public GTextField tips_text; + public Transition t0; + public const string URL = "ui://y6hi0pcjagfu1z"; + + public static com_gettaskreward CreateInstance() + { + return (com_gettaskreward)UIPackage.CreateObject("G009_video", "com_gettaskreward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + switchgift = GetControllerAt(0); + bg_parent = (GGraph)GetChildAt(0); + money_text = (GTextField)GetChildAt(4); + btn_adclaim = (GButton)GetChildAt(6); + btn_claim = (GButton)GetChildAt(7); + com_cash = (GComponent)GetChildAt(8); + top_money = (GComponent)GetChildAt(9); + tips_bg = (GImage)GetChildAt(10); + gold = (GComponent)GetChildAt(11); + tips_text = (GTextField)GetChildAt(12); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs.meta new file mode 100644 index 0000000..eb3e45a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_gettaskreward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7276dc1621b942d45b0ab33ffb9b4fb4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs new file mode 100644 index 0000000..ebd4101 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_newtask : GComponent + { + public GImage TopBg; + public GImage MiddleBg; + public GList task_list; + public com_battlepass pass_com; + public com_toptab com_toptab; + public GComponent gold; + public GComponent money; + public GButton btn_close; + public GGroup TopBox; + public const string URL = "ui://y6hi0pcjagfue"; + + public static com_newtask CreateInstance() + { + return (com_newtask)UIPackage.CreateObject("G009_video", "com_newtask"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + TopBg = (GImage)GetChildAt(3); + MiddleBg = (GImage)GetChildAt(4); + task_list = (GList)GetChildAt(5); + pass_com = (com_battlepass)GetChildAt(6); + com_toptab = (com_toptab)GetChildAt(7); + gold = (GComponent)GetChildAt(8); + money = (GComponent)GetChildAt(9); + btn_close = (GButton)GetChildAt(10); + TopBox = (GGroup)GetChildAt(11); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs.meta new file mode 100644 index 0000000..b4562f4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_newtask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b52565c38ac9f4c4dac7f0728941dee7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs new file mode 100644 index 0000000..add5e19 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs @@ -0,0 +1,43 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_passitem : GComponent + { + public Controller state; + public Controller full; + public GImage progress_0_top; + public GImage progress_0_down; + public GImage progress_1_top; + public GImage progress_1_down; + public GImage progress_2_top; + public GTextField index_text; + public com_passreward free_item; + public com_passreward pay_item; + public const string URL = "ui://y6hi0pcjagfu1v"; + + public static com_passitem CreateInstance() + { + return (com_passitem)UIPackage.CreateObject("G009_video", "com_passitem"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + full = GetControllerAt(1); + progress_0_top = (GImage)GetChildAt(14); + progress_0_down = (GImage)GetChildAt(15); + progress_1_top = (GImage)GetChildAt(16); + progress_1_down = (GImage)GetChildAt(17); + progress_2_top = (GImage)GetChildAt(18); + index_text = (GTextField)GetChildAt(20); + free_item = (com_passreward)GetChildAt(21); + pay_item = (com_passreward)GetChildAt(22); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs.meta new file mode 100644 index 0000000..47dbf38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passitem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b3f9e1c757ab34b4a842d2258f45d95a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs new file mode 100644 index 0000000..9c32f28 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_passreward : GButton + { + public Controller type; + public Controller state; + public GLoader item_loader; + public GTextField number_text; + public GImage Tick; + public GImage Lock; + public const string URL = "ui://y6hi0pcjagfu1w"; + + public static com_passreward CreateInstance() + { + return (com_passreward)UIPackage.CreateObject("G009_video", "com_passreward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + type = GetControllerAt(0); + state = GetControllerAt(1); + item_loader = (GLoader)GetChildAt(3); + number_text = (GTextField)GetChildAt(4); + Tick = (GImage)GetChildAt(5); + Lock = (GImage)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs.meta new file mode 100644 index 0000000..f6e5b26 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passreward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d22b12fdc46740e45b8e527061836533 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs new file mode 100644 index 0000000..495c62b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_passunlock : GComponent + { + public Controller pay_type; + public GTextField text_YourHaveAds; + public GButton btn_close; + public GTextField text_allgold; + public GTextField text_NeedAds; + public GButton btn_buypass; + public GButton btn_Claim; + public GButton btn_max_pay; + public const string URL = "ui://y6hi0pcjttbj2b"; + + public static com_passunlock CreateInstance() + { + return (com_passunlock)UIPackage.CreateObject("G009_video", "com_passunlock"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + pay_type = GetControllerAt(0); + text_YourHaveAds = (GTextField)GetChildAt(2); + btn_close = (GButton)GetChildAt(3); + text_allgold = (GTextField)GetChildAt(6); + text_NeedAds = (GTextField)GetChildAt(9); + btn_buypass = (GButton)GetChildAt(10); + btn_Claim = (GButton)GetChildAt(11); + btn_max_pay = (GButton)GetChildAt(12); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs.meta new file mode 100644 index 0000000..a87b2c4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_passunlock.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca14d48ecfae0ad448c7f31979eb0809 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs new file mode 100644 index 0000000..97dc0f4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs @@ -0,0 +1,37 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class com_toptab : GComponent + { + public Controller tab; + public GButton btn_battle; + public GButton btn_pass; + public GButton btn_time; + public GImage red_0; + public GImage red_1; + public GImage red_2; + public const string URL = "ui://y6hi0pcjagfux"; + + public static com_toptab CreateInstance() + { + return (com_toptab)UIPackage.CreateObject("G009_video", "com_toptab"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + tab = GetControllerAt(0); + btn_battle = (GButton)GetChildAt(13); + btn_pass = (GButton)GetChildAt(14); + btn_time = (GButton)GetChildAt(15); + red_0 = (GImage)GetChildAt(16); + red_1 = (GImage)GetChildAt(17); + red_2 = (GImage)GetChildAt(18); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs.meta new file mode 100644 index 0000000..fad1529 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/com_toptab.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a865913b51185c644a68e113dd1ccd21 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs b/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs new file mode 100644 index 0000000..272ac19 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs @@ -0,0 +1,45 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G009_video +{ + public partial class task_item : GComponent + { + public GImage gold_img; + public GImage ez_img; + public GImage diff_img; + public GImage progress; + public GImage progress_2; + public GTextField content_text; + public GTextField progress_text; + public GTextField number_text; + public GTextField text_ez; + public GTextField text_diff; + public btn_task btn_get; + public const string URL = "ui://y6hi0pcjagfuy"; + + public static task_item CreateInstance() + { + return (task_item)UIPackage.CreateObject("G009_video", "task_item"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + gold_img = (GImage)GetChildAt(1); + ez_img = (GImage)GetChildAt(2); + diff_img = (GImage)GetChildAt(3); + progress = (GImage)GetChildAt(5); + progress_2 = (GImage)GetChildAt(7); + content_text = (GTextField)GetChildAt(8); + progress_text = (GTextField)GetChildAt(9); + number_text = (GTextField)GetChildAt(10); + text_ez = (GTextField)GetChildAt(11); + text_diff = (GTextField)GetChildAt(12); + btn_get = (btn_task)GetChildAt(13); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs.meta b/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs.meta new file mode 100644 index 0000000..2d44a8d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G009_video/task_item.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b7e6b81632b3424a9490073b9eba396 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward.meta new file mode 100644 index 0000000..b71e0e9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bdc4f2fbb9346f340ab32293a938c98c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs new file mode 100644 index 0000000..14e3c18 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs @@ -0,0 +1,19 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G012_openReward +{ + public class G012_openRewardBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(buygold_item.URL, typeof(buygold_item)); + UIObjectFactory.SetPackageItemExtension(btn_buy.URL, typeof(btn_buy)); + UIObjectFactory.SetPackageItemExtension(com_buygold.URL, typeof(com_buygold)); + UIObjectFactory.SetPackageItemExtension(com_card.URL, typeof(com_card)); + UIObjectFactory.SetPackageItemExtension(com_realperson.URL, typeof(com_realperson)); + UIObjectFactory.SetPackageItemExtension(com_showBonus.URL, typeof(com_showBonus)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs.meta new file mode 100644 index 0000000..3e876e3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/G012_openRewardBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3314f72d7d931164981ca7ab786eef30 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs new file mode 100644 index 0000000..dc94505 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class btn_buy : GButton + { + public Controller can_buy; + public GTextField btn_text; + public GImage img_saveingpot; + public const string URL = "ui://ulg8pausagfu1b"; + + public static btn_buy CreateInstance() + { + return (btn_buy)UIPackage.CreateObject("G012_openReward", "btn_buy"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + can_buy = GetControllerAt(0); + btn_text = (GTextField)GetChildAt(2); + img_saveingpot = (GImage)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs.meta new file mode 100644 index 0000000..85574ed --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/btn_buy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 073eed58463b91147b1d86c9d431d8c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs new file mode 100644 index 0000000..bd1786a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class buygold_item : GComponent + { + public Controller index; + public Controller pay_type; + public Controller show_off; + public GTextField coin_text; + public btn_buy btn_buy; + public GTextField off_text; + public GTextField content_text; + public GTextField text_priceDescription; + public const string URL = "ui://ulg8pausagfu1a"; + + public static buygold_item CreateInstance() + { + return (buygold_item)UIPackage.CreateObject("G012_openReward", "buygold_item"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + index = GetControllerAt(0); + pay_type = GetControllerAt(1); + show_off = GetControllerAt(2); + coin_text = (GTextField)GetChildAt(6); + btn_buy = (btn_buy)GetChildAt(7); + off_text = (GTextField)GetChildAt(9); + content_text = (GTextField)GetChildAt(10); + text_priceDescription = (GTextField)GetChildAt(11); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs.meta new file mode 100644 index 0000000..ab2f4a4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/buygold_item.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0951d9e009d2a4c469ac9778f9963e32 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs new file mode 100644 index 0000000..805217a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class com_buygold : GComponent + { + public Controller pay_type; + public GComponent top_gold; + public GButton btn_close; + public GTextField text_hasADsCount; + public GList list_item; + public const string URL = "ui://ulg8pausagfus"; + + public static com_buygold CreateInstance() + { + return (com_buygold)UIPackage.CreateObject("G012_openReward", "com_buygold"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + pay_type = GetControllerAt(0); + top_gold = (GComponent)GetChildAt(0); + btn_close = (GButton)GetChildAt(3); + text_hasADsCount = (GTextField)GetChildAt(5); + list_item = (GList)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs.meta new file mode 100644 index 0000000..34509ec --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_buygold.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f10664bb8b3c5f848a403def74f45f38 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs new file mode 100644 index 0000000..5834138 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class com_card : GComponent + { + public Controller cont_country; + public Controller lang; + public GTextField text_cash; + public const string URL = "ui://ulg8pauskp7b7"; + + public static com_card CreateInstance() + { + return (com_card)UIPackage.CreateObject("G012_openReward", "com_card"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_country = GetControllerAt(0); + lang = GetControllerAt(1); + text_cash = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs.meta new file mode 100644 index 0000000..c675a11 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_card.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28891243d4853b1409c31f6611d5ab25 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs new file mode 100644 index 0000000..0547d76 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class com_realperson : GComponent + { + public GLoader loader_person; + public const string URL = "ui://ulg8pausphpc6"; + + public static com_realperson CreateInstance() + { + return (com_realperson)UIPackage.CreateObject("G012_openReward", "com_realperson"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + loader_person = (GLoader)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs.meta new file mode 100644 index 0000000..60729c4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_realperson.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6ee8b4eb778e8f498584a5646eebff3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs new file mode 100644 index 0000000..b78cc8e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G012_openReward +{ + public partial class com_showBonus : GComponent + { + public GList list_card; + public const string URL = "ui://ulg8pausz1ng4"; + + public static com_showBonus CreateInstance() + { + return (com_showBonus)UIPackage.CreateObject("G012_openReward", "com_showBonus"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + list_card = (GList)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs.meta b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs.meta new file mode 100644 index 0000000..8fadff5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G012_openReward/com_showBonus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2345bc579afd2bd44beee9b3b9d4c5ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn.meta b/Assets/CrazyZoo/FGUI/Package/G014_SignIn.meta new file mode 100644 index 0000000..599c217 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 452fb499a3e7e774a8e150702b25e3e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs new file mode 100644 index 0000000..20b8c79 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs @@ -0,0 +1,15 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G014_SignIn +{ + public class G014_SignInBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_sign_in.URL, typeof(com_sign_in)); + UIObjectFactory.SetPackageItemExtension(btn_sign.URL, typeof(btn_sign)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs.meta new file mode 100644 index 0000000..fba7b2f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/G014_SignInBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d89ddfe7619ed0945afc428f99960b95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs new file mode 100644 index 0000000..93fbb6e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G014_SignIn +{ + public partial class btn_sign : GButton + { + public Controller State; + public Controller Style; + public GTextField reward_num; + public GGraph fx_parent; + public GTextField TitleStyle_1; + public GTextField TitleStyle_2; + public const string URL = "ui://tx10e3imsebxc"; + + public static btn_sign CreateInstance() + { + return (btn_sign)UIPackage.CreateObject("G014_SignIn", "btn_sign"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + State = GetControllerAt(0); + Style = GetControllerAt(1); + reward_num = (GTextField)GetChildAt(5); + fx_parent = (GGraph)GetChildAt(6); + TitleStyle_1 = (GTextField)GetChildAt(10); + TitleStyle_2 = (GTextField)GetChildAt(11); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs.meta b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs.meta new file mode 100644 index 0000000..3aac8bf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/btn_sign.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: acd225ccc56869e4a9bfe42ec0562235 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs new file mode 100644 index 0000000..aa73ad2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs @@ -0,0 +1,45 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G014_SignIn +{ + public partial class com_sign_in : GComponent + { + public btn_sign day7; + public btn_sign day6; + public btn_sign day5; + public btn_sign day4; + public btn_sign day3; + public btn_sign day2; + public btn_sign day1; + public GButton close; + public GGraph point; + public GTextField TitleText; + public GComponent gold; + public const string URL = "ui://tx10e3imsebxa"; + + public static com_sign_in CreateInstance() + { + return (com_sign_in)UIPackage.CreateObject("G014_SignIn", "com_sign_in"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + day7 = (btn_sign)GetChildAt(2); + day6 = (btn_sign)GetChildAt(3); + day5 = (btn_sign)GetChildAt(4); + day4 = (btn_sign)GetChildAt(5); + day3 = (btn_sign)GetChildAt(6); + day2 = (btn_sign)GetChildAt(7); + day1 = (btn_sign)GetChildAt(8); + close = (GButton)GetChildAt(9); + point = (GGraph)GetChildAt(10); + TitleText = (GTextField)GetChildAt(11); + gold = (GComponent)GetChildAt(12); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs.meta b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs.meta new file mode 100644 index 0000000..b76e801 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G014_SignIn/com_sign_in.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11e1f7f35618ed9499f3491d1e00323b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome.meta new file mode 100644 index 0000000..85d0cce --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ef822de5e5bcd5c4fa8b5a73f1e7571b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs new file mode 100644 index 0000000..8b4c2d7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs @@ -0,0 +1,18 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G018_GameHome +{ + public class G018_GameHomeBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(btn_repur.URL, typeof(btn_repur)); + UIObjectFactory.SetPackageItemExtension(GameHome.URL, typeof(GameHome)); + UIObjectFactory.SetPackageItemExtension(SignInBtn.URL, typeof(SignInBtn)); + UIObjectFactory.SetPackageItemExtension(new_topgold.URL, typeof(new_topgold)); + UIObjectFactory.SetPackageItemExtension(btn_battle.URL, typeof(btn_battle)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs.meta new file mode 100644 index 0000000..358a232 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/G018_GameHomeBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd5edb9e560f7aa40a4a29b580c0d52c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs new file mode 100644 index 0000000..f6dfa73 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs @@ -0,0 +1,61 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G018_GameHome +{ + public partial class GameHome : GComponent + { + public Controller Mode; + public Controller switchgift; + public GButton btn_saveingpot; + public GButton btn_menu; + public GButton btn_setting; + public new_topgold gold; + public GComponent money; + public btn_battle BattleBtn; + public GButton btn_three_day; + public SignInBtn SignInBtn; + public GButton NoAdsBtn; + public GButton btn_failpack; + public btn_repur btn_restore; + public GGroup TopBox; + public GButton RightBtn; + public GButton LeftBtn; + public GButton PlayBtn; + public GButton LuckySpinBtn; + public GButton RankBtn; + public const string URL = "ui://dypufdsgtrht2i"; + + public static GameHome CreateInstance() + { + return (GameHome)UIPackage.CreateObject("G018_GameHome", "GameHome"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + Mode = GetControllerAt(0); + switchgift = GetControllerAt(1); + btn_saveingpot = (GButton)GetChildAt(1); + btn_menu = (GButton)GetChildAt(2); + btn_setting = (GButton)GetChildAt(3); + gold = (new_topgold)GetChildAt(4); + money = (GComponent)GetChildAt(5); + BattleBtn = (btn_battle)GetChildAt(6); + btn_three_day = (GButton)GetChildAt(7); + SignInBtn = (SignInBtn)GetChildAt(8); + NoAdsBtn = (GButton)GetChildAt(9); + btn_failpack = (GButton)GetChildAt(10); + btn_restore = (btn_repur)GetChildAt(11); + TopBox = (GGroup)GetChildAt(12); + RightBtn = (GButton)GetChildAt(14); + LeftBtn = (GButton)GetChildAt(15); + PlayBtn = (GButton)GetChildAt(18); + LuckySpinBtn = (GButton)GetChildAt(21); + RankBtn = (GButton)GetChildAt(22); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs.meta new file mode 100644 index 0000000..34a79cf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/GameHome.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ceafbfdde26797948b0421d6b3115ee0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs new file mode 100644 index 0000000..8abfa5c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G018_GameHome +{ + public partial class SignInBtn : GButton + { + public GImage red; + public const string URL = "ui://dypufdsgtrht5"; + + public static SignInBtn CreateInstance() + { + return (SignInBtn)UIPackage.CreateObject("G018_GameHome", "SignInBtn"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + red = (GImage)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs.meta new file mode 100644 index 0000000..7152ca8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/SignInBtn.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cde7568501c4b5b40a0e4e45f19e8cbd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs new file mode 100644 index 0000000..efba21c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G018_GameHome +{ + public partial class btn_battle : GButton + { + public GImage red; + public GImage progress; + public GTextField number_text; + public const string URL = "ui://dypufdsgtrht9"; + + public static btn_battle CreateInstance() + { + return (btn_battle)UIPackage.CreateObject("G018_GameHome", "btn_battle"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + red = (GImage)GetChildAt(1); + progress = (GImage)GetChildAt(3); + number_text = (GTextField)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs.meta new file mode 100644 index 0000000..b358c56 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_battle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ec267aab68cd8d4a96a5a7488c26342 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs new file mode 100644 index 0000000..a2b9b83 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G018_GameHome +{ + public partial class btn_repur : GButton + { + public GTextField number_text; + public const string URL = "ui://dypufdsgqzxe2u"; + + public static btn_repur CreateInstance() + { + return (btn_repur)UIPackage.CreateObject("G018_GameHome", "btn_repur"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + number_text = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs.meta new file mode 100644 index 0000000..234e809 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/btn_repur.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ebc6f572e79545169615c68e2645743 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs new file mode 100644 index 0000000..730824a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs @@ -0,0 +1,35 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G018_GameHome +{ + public partial class new_topgold : GComponent + { + public Controller state; + public GTextField number_text; + public GImage red; + public GTextField tips_text; + public GButton btn_buygold; + public Transition t0; + public const string URL = "ui://dypufdsgtrht8"; + + public static new_topgold CreateInstance() + { + return (new_topgold)UIPackage.CreateObject("G018_GameHome", "new_topgold"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + number_text = (GTextField)GetChildAt(2); + red = (GImage)GetChildAt(3); + tips_text = (GTextField)GetChildAt(5); + btn_buygold = (GButton)GetChildAt(6); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs.meta b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs.meta new file mode 100644 index 0000000..ae59fd3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G018_GameHome/new_topgold.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: faf8e1301d6d9004e8dc57b6f3cd2846 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G019_Rank.meta b/Assets/CrazyZoo/FGUI/Package/G019_Rank.meta new file mode 100644 index 0000000..e54d3cc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G019_Rank.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ef56f0cbf45307b49a083487d7d8872a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs b/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs new file mode 100644 index 0000000..943e3e6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs @@ -0,0 +1,14 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G019_Rank +{ + public class G019_RankBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(RankPanel.URL, typeof(RankPanel)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs.meta new file mode 100644 index 0000000..dc42ec4 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G019_Rank/G019_RankBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46c121a983276e74cbc6cc3b6a7ae6f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs b/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs new file mode 100644 index 0000000..f27dc69 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G019_Rank +{ + public partial class RankPanel : GComponent + { + public GButton CloseBtn; + public GTextField Title; + public GTextField Rank; + public GTextField Name; + public GTextField Level; + public GTextField Tips; + public GTextField PlayLevel; + public GButton PlayIcon; + public GTextField PlayName; + public const string URL = "ui://duer8yiptrht4"; + + public static RankPanel CreateInstance() + { + return (RankPanel)UIPackage.CreateObject("G019_Rank", "RankPanel"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + CloseBtn = (GButton)GetChildAt(2); + Title = (GTextField)GetChildAt(6); + Rank = (GTextField)GetChildAt(7); + Name = (GTextField)GetChildAt(8); + Level = (GTextField)GetChildAt(9); + Tips = (GTextField)GetChildAt(10); + PlayLevel = (GTextField)GetChildAt(13); + PlayIcon = (GButton)GetChildAt(14); + PlayName = (GTextField)GetChildAt(15); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs.meta b/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs.meta new file mode 100644 index 0000000..7453abf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G019_Rank/RankPanel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66afa50f750335548b8dbe104425aecc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel.meta new file mode 100644 index 0000000..1ab4676 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8467b849f586d2d4e9afb9bc71713e47 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs new file mode 100644 index 0000000..5d1dc95 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs @@ -0,0 +1,17 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G020_PrizeWheel +{ + public class G020_PrizeWheelBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(PrizeWheelPanel.URL, typeof(PrizeWheelPanel)); + UIObjectFactory.SetPackageItemExtension(StartSpinButton.URL, typeof(StartSpinButton)); + UIObjectFactory.SetPackageItemExtension(SpinWheelRewardItem.URL, typeof(SpinWheelRewardItem)); + UIObjectFactory.SetPackageItemExtension(PrizeWheel.URL, typeof(PrizeWheel)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs.meta new file mode 100644 index 0000000..6ef237c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/G020_PrizeWheelBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 61db8fa3baa65274785b2f61ad17af09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs new file mode 100644 index 0000000..35a8514 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G020_PrizeWheel +{ + public partial class PrizeWheel : GComponent + { + public SpinWheelRewardItem item_1; + public SpinWheelRewardItem item_2; + public SpinWheelRewardItem item_3; + public SpinWheelRewardItem item_4; + public SpinWheelRewardItem item_5; + public SpinWheelRewardItem item_6; + public SpinWheelRewardItem item_7; + public SpinWheelRewardItem item_8; + public const string URL = "ui://dd6xc38htrhta"; + + public static PrizeWheel CreateInstance() + { + return (PrizeWheel)UIPackage.CreateObject("G020_PrizeWheel", "PrizeWheel"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + item_1 = (SpinWheelRewardItem)GetChildAt(2); + item_2 = (SpinWheelRewardItem)GetChildAt(3); + item_3 = (SpinWheelRewardItem)GetChildAt(4); + item_4 = (SpinWheelRewardItem)GetChildAt(5); + item_5 = (SpinWheelRewardItem)GetChildAt(6); + item_6 = (SpinWheelRewardItem)GetChildAt(7); + item_7 = (SpinWheelRewardItem)GetChildAt(8); + item_8 = (SpinWheelRewardItem)GetChildAt(9); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs.meta new file mode 100644 index 0000000..cd37262 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d793f7875e8075d468ae314dda32b042 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs new file mode 100644 index 0000000..fe9a26a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs @@ -0,0 +1,51 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G020_PrizeWheel +{ + public partial class PrizeWheelPanel : GComponent + { + public PrizeWheel PrizeWheel; + public GImage Pointer; + public GGraph PrizeWheelAnimParent; + public GGroup MiddlePart; + public GImage TitleBg; + public GComponent gold; + public GButton CloseBtn; + public GTextField TitleText; + public GGroup TopBox; + public StartSpinButton StartSpinBtn; + public GRichTextField RemainingCountText; + public GGroup BottomBox; + public Transition Open; + public Transition Close; + public const string URL = "ui://dd6xc38htrht6"; + + public static PrizeWheelPanel CreateInstance() + { + return (PrizeWheelPanel)UIPackage.CreateObject("G020_PrizeWheel", "PrizeWheelPanel"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + PrizeWheel = (PrizeWheel)GetChildAt(0); + Pointer = (GImage)GetChildAt(1); + PrizeWheelAnimParent = (GGraph)GetChildAt(2); + MiddlePart = (GGroup)GetChildAt(3); + TitleBg = (GImage)GetChildAt(4); + gold = (GComponent)GetChildAt(5); + CloseBtn = (GButton)GetChildAt(6); + TitleText = (GTextField)GetChildAt(7); + TopBox = (GGroup)GetChildAt(8); + StartSpinBtn = (StartSpinButton)GetChildAt(9); + RemainingCountText = (GRichTextField)GetChildAt(10); + BottomBox = (GGroup)GetChildAt(11); + Open = GetTransitionAt(0); + Close = GetTransitionAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs.meta new file mode 100644 index 0000000..793cfc0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/PrizeWheelPanel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29846f6abcefe264ba4f21d32f4f6bfd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs new file mode 100644 index 0000000..24f8b41 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G020_PrizeWheel +{ + public partial class SpinWheelRewardItem : GComponent + { + public GImage icon; + public GTextField num; + public const string URL = "ui://dd6xc38htrht9"; + + public static SpinWheelRewardItem CreateInstance() + { + return (SpinWheelRewardItem)UIPackage.CreateObject("G020_PrizeWheel", "SpinWheelRewardItem"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + icon = (GImage)GetChildAt(0); + num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs.meta new file mode 100644 index 0000000..44f4929 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/SpinWheelRewardItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a6e8c29e08280fa4db1580ea282cc126 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs new file mode 100644 index 0000000..3ad8f85 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G020_PrizeWheel +{ + public partial class StartSpinButton : GButton + { + public GTextField BtnText; + public GImage BtnIcon; + public GGroup BtnTitleBox; + public GTextField CountdownText; + public GImage img_saveingpot; + public const string URL = "ui://dd6xc38htrht8"; + + public static StartSpinButton CreateInstance() + { + return (StartSpinButton)UIPackage.CreateObject("G020_PrizeWheel", "StartSpinButton"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + BtnText = (GTextField)GetChildAt(1); + BtnIcon = (GImage)GetChildAt(2); + BtnTitleBox = (GGroup)GetChildAt(3); + CountdownText = (GTextField)GetChildAt(4); + img_saveingpot = (GImage)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs.meta b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs.meta new file mode 100644 index 0000000..93abf9c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G020_PrizeWheel/StartSpinButton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99bb70624a38c94469114563af7d2e3f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G502_Fx.meta b/Assets/CrazyZoo/FGUI/Package/G502_Fx.meta new file mode 100644 index 0000000..956583b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G502_Fx.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e01cc775bedebfe4eb87fbbc091999b2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs b/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs new file mode 100644 index 0000000..24b6d99 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs @@ -0,0 +1,14 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G502_Fx +{ + public class G502_FxBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_FX.URL, typeof(com_FX)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs.meta new file mode 100644 index 0000000..e3f6a4c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G502_Fx/G502_FxBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ec64cbe672e66f747a2f63bff93d259c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs b/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs new file mode 100644 index 0000000..7ee8131 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G502_Fx +{ + public partial class com_FX : GComponent + { + public GGraph fx_Inis; + public const string URL = "ui://wjt0ioiopqqv0"; + + public static com_FX CreateInstance() + { + return (com_FX)UIPackage.CreateObject("G502_Fx", "com_FX"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + fx_Inis = (GGraph)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs.meta b/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs.meta new file mode 100644 index 0000000..60bcd6a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G502_Fx/com_FX.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f3a103d0e80e8f4387ca8c29dc65aae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin.meta new file mode 100644 index 0000000..0c247ba --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8a6a6695879cfa54782861bc3ee341d2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs new file mode 100644 index 0000000..4deda25 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G601_Coin +{ + public partial class Com_CoinWnd : GComponent + { + public GGraph fx_enter; + public com_Coins com_Coins; + public GTextField text_Add; + public Transition fx_addSum; + public const string URL = "ui://3z2akmm3kov20"; + + public static Com_CoinWnd CreateInstance() + { + return (Com_CoinWnd)UIPackage.CreateObject("G601_Coin", "Com_CoinWnd"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + fx_enter = (GGraph)GetChildAt(0); + com_Coins = (com_Coins)GetChildAt(1); + text_Add = (GTextField)GetChildAt(2); + fx_addSum = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs.meta new file mode 100644 index 0000000..1fe8f1c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b5a3ff1301f92f44a7e982e3d12c9ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs new file mode 100644 index 0000000..9dc972b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G601_Coin +{ + public partial class Com_CoinWnd_new : GComponent + { + public GGraph fx_enter; + public com_Coins com_Coins; + public GTextField text_Add; + public Transition fx_addSum; + public const string URL = "ui://3z2akmm3agfubq"; + + public static Com_CoinWnd_new CreateInstance() + { + return (Com_CoinWnd_new)UIPackage.CreateObject("G601_Coin", "Com_CoinWnd_new"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + fx_enter = (GGraph)GetChildAt(0); + com_Coins = (com_Coins)GetChildAt(1); + text_Add = (GTextField)GetChildAt(2); + fx_addSum = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs.meta new file mode 100644 index 0000000..841b61c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/Com_CoinWnd_new.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a004a3384cb07ec40a69757d0e84c747 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs b/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs new file mode 100644 index 0000000..d6540b6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs @@ -0,0 +1,17 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.G601_Coin +{ + public class G601_CoinBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(Com_CoinWnd_new.URL, typeof(Com_CoinWnd_new)); + UIObjectFactory.SetPackageItemExtension(com_Coin.URL, typeof(com_Coin)); + UIObjectFactory.SetPackageItemExtension(Com_CoinWnd.URL, typeof(Com_CoinWnd)); + UIObjectFactory.SetPackageItemExtension(com_Coins.URL, typeof(com_Coins)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs.meta new file mode 100644 index 0000000..4124ef3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/G601_CoinBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e22dbdbcd07b2049acaffc453437ef6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs new file mode 100644 index 0000000..23680c0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G601_Coin +{ + public partial class com_Coin : GComponent + { + public GLoader icon; + public GGraph lizhi; + public const string URL = "ui://3z2akmm3hybwbp"; + + public static com_Coin CreateInstance() + { + return (com_Coin)UIPackage.CreateObject("G601_Coin", "com_Coin"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + icon = (GLoader)GetChildAt(0); + lizhi = (GGraph)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs.meta new file mode 100644 index 0000000..74ca46f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3a0d6001cb32474992c95e78c9231a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs new file mode 100644 index 0000000..36af4c0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.G601_Coin +{ + public partial class com_Coins : GComponent + { + public Controller cont_coin; + public const string URL = "ui://3z2akmm3kov21"; + + public static com_Coins CreateInstance() + { + return (com_Coins)UIPackage.CreateObject("G601_Coin", "com_Coins"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_coin = GetControllerAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs.meta b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs.meta new file mode 100644 index 0000000..6d35ee2 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/G601_Coin/com_Coins.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8be25b752512d774cb6280ce9c5348ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips.meta b/Assets/CrazyZoo/FGUI/Package/SC001_Tips.meta new file mode 100644 index 0000000..ddc8dcb --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: da343db9bd5e86d4da0c958a36122a94 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs new file mode 100644 index 0000000..18cdb62 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs @@ -0,0 +1,15 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SC001_Tips +{ + public class SC001_TipsBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_Tips.URL, typeof(com_Tips)); + UIObjectFactory.SetPackageItemExtension(wnd_tips.URL, typeof(wnd_tips)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs.meta new file mode 100644 index 0000000..76cbda0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/SC001_TipsBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d34ae27c64f5954a83c2f4070eff1dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs new file mode 100644 index 0000000..1be2034 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC001_Tips +{ + public partial class com_Tips : GComponent + { + public wnd_tips wnd_tips; + public const string URL = "ui://wmeu09xzgmed0"; + + public static com_Tips CreateInstance() + { + return (com_Tips)UIPackage.CreateObject("SC001_Tips", "com_Tips"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + wnd_tips = (wnd_tips)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs.meta new file mode 100644 index 0000000..b11fe59 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/com_Tips.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b76e5e2d8c98e14e82255d2cab671f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs new file mode 100644 index 0000000..a4f166f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC001_Tips +{ + public partial class wnd_tips : GComponent + { + public GTextField text_tips; + public const string URL = "ui://wmeu09xzgmed1"; + + public static wnd_tips CreateInstance() + { + return (wnd_tips)UIPackage.CreateObject("SC001_Tips", "wnd_tips"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_tips = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs.meta new file mode 100644 index 0000000..b728a8d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC001_Tips/wnd_tips.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d5acde6d5e06494f9049d2943c001e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC004_Mask.meta b/Assets/CrazyZoo/FGUI/Package/SC004_Mask.meta new file mode 100644 index 0000000..0358b49 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC004_Mask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1da13c67304e9354ebaeb5b1b6ff3d4f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs new file mode 100644 index 0000000..c9e14da --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs @@ -0,0 +1,14 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SC004_Mask +{ + public class SC004_MaskBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_Mask.URL, typeof(com_Mask)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs.meta new file mode 100644 index 0000000..37d5725 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/SC004_MaskBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3b4fe16dee6a7a409bebd2ea58944ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs new file mode 100644 index 0000000..b72dadf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC004_Mask +{ + public partial class com_Mask : GComponent + { + public GGraph gp_mask; + public const string URL = "ui://qmqcbtp2dud70"; + + public static com_Mask CreateInstance() + { + return (com_Mask)UIPackage.CreateObject("SC004_Mask", "com_Mask"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + gp_mask = (GGraph)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs.meta new file mode 100644 index 0000000..fbb4104 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC004_Mask/com_Mask.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5ac1c47b79347f4880ae59b2cad07d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle.meta b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle.meta new file mode 100644 index 0000000..e2a0f0a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2662b8c5df3d7ae4a86338f05797f69c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs new file mode 100644 index 0000000..5b7808e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs @@ -0,0 +1,15 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SC005_NetIdle +{ + public class SC005_NetIdleBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_loading.URL, typeof(com_loading)); + UIObjectFactory.SetPackageItemExtension(com_Netidle.URL, typeof(com_Netidle)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs.meta new file mode 100644 index 0000000..c28a660 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/SC005_NetIdleBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea5167ddff3ae9c46aee97043b80e133 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs new file mode 100644 index 0000000..15512c6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC005_NetIdle +{ + public partial class com_Netidle : GComponent + { + public Controller cont_state; + public com_loading com_net_loading; + public GTextField text_loading; + public const string URL = "ui://x7vlnzzckhti0"; + + public static com_Netidle CreateInstance() + { + return (com_Netidle)UIPackage.CreateObject("SC005_NetIdle", "com_Netidle"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_state = GetControllerAt(0); + com_net_loading = (com_loading)GetChildAt(0); + text_loading = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs.meta new file mode 100644 index 0000000..6968dd7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_Netidle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21d64917f4db03d429e40d013f554479 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs new file mode 100644 index 0000000..36a0793 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC005_NetIdle +{ + public partial class com_loading : GComponent + { + public GLoader loader_gameicon; + public Transition t0; + public const string URL = "ui://x7vlnzzcjyke2"; + + public static com_loading CreateInstance() + { + return (com_loading)UIPackage.CreateObject("SC005_NetIdle", "com_loading"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + loader_gameicon = (GLoader)GetChildAt(1); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs.meta new file mode 100644 index 0000000..328bbb8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC005_NetIdle/com_loading.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e902cb2afda77c3418582ea36d9f07b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy.meta b/Assets/CrazyZoo/FGUI/Package/SC006_privacy.meta new file mode 100644 index 0000000..15c04dd --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f6e59b11a6b76a46a4513e3ba527c46 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs new file mode 100644 index 0000000..f36f0b1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs @@ -0,0 +1,15 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SC006_privacy +{ + public class SC006_privacyBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_text.URL, typeof(com_text)); + UIObjectFactory.SetPackageItemExtension(com_privacy.URL, typeof(com_privacy)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs.meta new file mode 100644 index 0000000..9b1ef75 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/SC006_privacyBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ec297e1d106df2478822a2b8d70cae8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs new file mode 100644 index 0000000..3761c45 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC006_privacy +{ + public partial class com_privacy : GComponent + { + public GButton closeButton; + public GList list_privacy; + public GTextField txt_title; + public const string URL = "ui://myud7i2wu3z10"; + + public static com_privacy CreateInstance() + { + return (com_privacy)UIPackage.CreateObject("SC006_privacy", "com_privacy"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + closeButton = (GButton)GetChildAt(2); + list_privacy = (GList)GetChildAt(3); + txt_title = (GTextField)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs.meta new file mode 100644 index 0000000..57ff2cf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_privacy.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6d3f5f43e2b4db4b978be79640855dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs new file mode 100644 index 0000000..bccb927 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SC006_privacy +{ + public partial class com_text : GComponent + { + public GTextField text_content; + public const string URL = "ui://myud7i2ws9b71"; + + public static com_text CreateInstance() + { + return (com_text)UIPackage.CreateObject("SC006_privacy", "com_text"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_content = (GTextField)GetChildAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs.meta b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs.meta new file mode 100644 index 0000000..fc6970b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SC006_privacy/com_text.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ddf10d493c477654987fdff71d363736 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading.meta b/Assets/CrazyZoo/FGUI/Package/SLoading.meta new file mode 100644 index 0000000..57ca84d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6dc8f1bf284d7544bad325fa94279fa0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs b/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs new file mode 100644 index 0000000..6548027 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs @@ -0,0 +1,15 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SLoading +{ + public class SLoadingBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(pb_bar.URL, typeof(pb_bar)); + UIObjectFactory.SetPackageItemExtension(com_loading.URL, typeof(com_loading)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs.meta new file mode 100644 index 0000000..5d8eac6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/SLoadingBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6ba8178c616674f429656639846491e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs b/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs new file mode 100644 index 0000000..85be8e0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SLoading +{ + public partial class com_loading : GComponent + { + public GGraph title_parent; + public GGraph logo_parent; + public pb_bar pb_loading; + public Transition t0; + public const string URL = "ui://pc0wa25bt268a"; + + public static com_loading CreateInstance() + { + return (com_loading)UIPackage.CreateObject("SLoading", "com_loading"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + title_parent = (GGraph)GetChildAt(0); + logo_parent = (GGraph)GetChildAt(1); + pb_loading = (pb_bar)GetChildAt(2); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs.meta b/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs.meta new file mode 100644 index 0000000..b43ed5f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/com_loading.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 40e1eebcf1b4f2c458a8f10e72654024 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs b/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs new file mode 100644 index 0000000..060ef0a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SLoading +{ + public partial class pb_bar : GProgressBar + { + public GImage Progress; + public GImage grip; + public GTextField text_status; + public const string URL = "ui://pc0wa25bk0fgk"; + + public static pb_bar CreateInstance() + { + return (pb_bar)UIPackage.CreateObject("SLoading", "pb_bar"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + Progress = (GImage)GetChildAt(2); + grip = (GImage)GetChildAt(3); + text_status = (GTextField)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs.meta b/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs.meta new file mode 100644 index 0000000..994ff4c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SLoading/pb_bar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46b07d16f1f3c9545920eaf0888c64c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot.meta new file mode 100644 index 0000000..f56c7cc --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8ff1111a073ae4ccfac8bd403372b742 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs new file mode 100644 index 0000000..0a10201 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.SaveingPot +{ + public class SaveingPotBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_firstname.URL, typeof(com_firstname)); + UIObjectFactory.SetPackageItemExtension(com_enter.URL, typeof(com_enter)); + UIObjectFactory.SetPackageItemExtension(com_task.URL, typeof(com_task)); + UIObjectFactory.SetPackageItemExtension(btn_pay.URL, typeof(btn_pay)); + UIObjectFactory.SetPackageItemExtension(com_info.URL, typeof(com_info)); + UIObjectFactory.SetPackageItemExtension(com_cord.URL, typeof(com_cord)); + UIObjectFactory.SetPackageItemExtension(com_rank.URL, typeof(com_rank)); + UIObjectFactory.SetPackageItemExtension(com_newRecord.URL, typeof(com_newRecord)); + UIObjectFactory.SetPackageItemExtension(com_saveingpot.URL, typeof(com_saveingpot)); + UIObjectFactory.SetPackageItemExtension(btn_top.URL, typeof(btn_top)); + UIObjectFactory.SetPackageItemExtension(com_broadcast.URL, typeof(com_broadcast)); + UIObjectFactory.SetPackageItemExtension(com_progress_item.URL, typeof(com_progress_item)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs.meta new file mode 100644 index 0000000..5a6af44 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/SaveingPotBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e97d260cf466a4223adbcaaefe84a63c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs new file mode 100644 index 0000000..8958b38 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class btn_pay : GButton + { + public Controller show_cd; + public GTextField text_cd; + public const string URL = "ui://3xypx0e8heqb2k"; + + public static btn_pay CreateInstance() + { + return (btn_pay)UIPackage.CreateObject("SaveingPot", "btn_pay"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + show_cd = GetControllerAt(0); + text_cd = (GTextField)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs.meta new file mode 100644 index 0000000..a3d406b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_pay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f0dcd2aa774554ef2ad0c852f88cd199 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs new file mode 100644 index 0000000..30f579b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class btn_top : GButton + { + public Controller index; + public Controller btn_state; + public GTextField text_type; + public GTextField text_cash; + public GImage img_outline; + public const string URL = "ui://3xypx0e8upx71r"; + + public static btn_top CreateInstance() + { + return (btn_top)UIPackage.CreateObject("SaveingPot", "btn_top"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + index = GetControllerAt(0); + btn_state = GetControllerAt(1); + text_type = (GTextField)GetChildAt(4); + text_cash = (GTextField)GetChildAt(5); + img_outline = (GImage)GetChildAt(6); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs.meta new file mode 100644 index 0000000..215e9c9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/btn_top.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b5cdef0b3e724274a99a0b8194cc5dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs new file mode 100644 index 0000000..f444c59 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_broadcast : GComponent + { + public GTextField text_0; + public GTextField text_1; + public GTextField text_2; + public GTextField text_3; + public Transition t1; + public const string URL = "ui://3xypx0e8upx71v"; + + public static com_broadcast CreateInstance() + { + return (com_broadcast)UIPackage.CreateObject("SaveingPot", "com_broadcast"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_0 = (GTextField)GetChildAt(1); + text_1 = (GTextField)GetChildAt(3); + text_2 = (GTextField)GetChildAt(5); + text_3 = (GTextField)GetChildAt(7); + t1 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs.meta new file mode 100644 index 0000000..cf041c5 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_broadcast.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07ab56a453fe24fa28ae7570da7f8e9c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs new file mode 100644 index 0000000..cd6287d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_cord : GComponent + { + public GTextField text_amt; + public GTextField text_payer; + public GTextField text_name; + public GLoader loader_logo; + public GTextField email_text; + public GTextField time_text; + public GTextField number_text; + public GTextField status_text_0; + public GTextField status_text_1; + public const string URL = "ui://3xypx0e8meh8c"; + + public static com_cord CreateInstance() + { + return (com_cord)UIPackage.CreateObject("SaveingPot", "com_cord"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_amt = (GTextField)GetChildAt(3); + text_payer = (GTextField)GetChildAt(4); + text_name = (GTextField)GetChildAt(5); + loader_logo = (GLoader)GetChildAt(6); + email_text = (GTextField)GetChildAt(10); + time_text = (GTextField)GetChildAt(11); + number_text = (GTextField)GetChildAt(12); + status_text_0 = (GTextField)GetChildAt(13); + status_text_1 = (GTextField)GetChildAt(14); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs.meta new file mode 100644 index 0000000..230c3f0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_cord.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b5b83ff3451e4b3aa41c284dd996565 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs new file mode 100644 index 0000000..c523108 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_enter : GComponent + { + public GTextInput enter_email; + public const string URL = "ui://3xypx0e8deiw1k"; + + public static com_enter CreateInstance() + { + return (com_enter)UIPackage.CreateObject("SaveingPot", "com_enter"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + enter_email = (GTextInput)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs.meta new file mode 100644 index 0000000..6e318e9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_enter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e641827da70334776bd41d984a388e2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs new file mode 100644 index 0000000..e0954ca --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_firstname : GComponent + { + public Controller type; + public GTextInput enter_fname; + public GTextInput enter_fname_1; + public const string URL = "ui://3xypx0e8deiw1j"; + + public static com_firstname CreateInstance() + { + return (com_firstname)UIPackage.CreateObject("SaveingPot", "com_firstname"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + type = GetControllerAt(0); + enter_fname = (GTextInput)GetChildAt(1); + enter_fname_1 = (GTextInput)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs.meta new file mode 100644 index 0000000..5ef9a5f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_firstname.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e25e3c2c668c84cc69dfe3735d21cc11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs new file mode 100644 index 0000000..551218b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs @@ -0,0 +1,31 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_info : GComponent + { + public GTextField text_name; + public GTextField text_email; + public GButton btn_change; + public GLoader load_avatar; + public const string URL = "ui://3xypx0e8if1eb"; + + public static com_info CreateInstance() + { + return (com_info)UIPackage.CreateObject("SaveingPot", "com_info"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_name = (GTextField)GetChildAt(0); + text_email = (GTextField)GetChildAt(1); + btn_change = (GButton)GetChildAt(2); + load_avatar = (GLoader)GetChildAt(3); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs.meta new file mode 100644 index 0000000..bc03de7 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_info.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41e7a6d8036c14b78b178b794d9b5d66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs new file mode 100644 index 0000000..1594172 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_newRecord : GComponent + { + public com_rank com_rank; + public com_cord com_cord; + public const string URL = "ui://3xypx0e8qgv24k"; + + public static com_newRecord CreateInstance() + { + return (com_newRecord)UIPackage.CreateObject("SaveingPot", "com_newRecord"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + com_rank = (com_rank)GetChildAt(0); + com_cord = (com_cord)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs.meta new file mode 100644 index 0000000..47fe412 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_newRecord.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66b09ef64cb1d4a89aaad3292721c2ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs new file mode 100644 index 0000000..dc03fb9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_progress_item : GComponent + { + public GTextField text_rank1; + public const string URL = "ui://3xypx0e8upx71w"; + + public static com_progress_item CreateInstance() + { + return (com_progress_item)UIPackage.CreateObject("SaveingPot", "com_progress_item"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_rank1 = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs.meta new file mode 100644 index 0000000..e7ce429 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_progress_item.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 74b438867b17e413fad2f04ccd624209 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs new file mode 100644 index 0000000..2ddbb09 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs @@ -0,0 +1,37 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_rank : GComponent + { + public Controller content1; + public Controller content2; + public Controller content3; + public GTextField text_ranks; + public GTextField text_rank1; + public GTextField text_rank2; + public GTextField text_rank3; + public const string URL = "ui://3xypx0e8qgv24f"; + + public static com_rank CreateInstance() + { + return (com_rank)UIPackage.CreateObject("SaveingPot", "com_rank"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + content1 = GetControllerAt(0); + content2 = GetControllerAt(1); + content3 = GetControllerAt(2); + text_ranks = (GTextField)GetChildAt(3); + text_rank1 = (GTextField)GetChildAt(5); + text_rank2 = (GTextField)GetChildAt(6); + text_rank3 = (GTextField)GetChildAt(7); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs.meta new file mode 100644 index 0000000..fd1064c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_rank.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2b7b19eb544c498aae19724b775c569 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs new file mode 100644 index 0000000..5e09c62 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs @@ -0,0 +1,97 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_saveingpot : GComponent + { + public Controller type; + public Controller cont_confirm; + public GGraph ani_potparent; + public GTextField text_remaintime; + public GButton btn_close; + public GProgressBar progress_cash; + public GTextField text_cashprogress; + public GTextField text_nowcash; + public GTextField text_ad; + public GTextField text_pay; + public GButton btn_cash; + public GTextField text_lose; + public com_broadcast broad; + public com_enter com_info; + public com_firstname com_fname; + public com_firstname com_lname; + public GTextField text_title; + public GTextField text_smaill_title; + public GButton btn_confirm; + public GTextField text_smaill_title_2; + public com_info com_pay; + public GTextField text_wallet; + public GTextField text_cash; + public GTextField text_account; + public com_task com_task; + public com_newRecord com_newRecord; + public btn_pay btn_watch; + public GTextField text_query; + public GTextField text_payhint; + public btn_top btn_level0; + public btn_top btn_level1; + public btn_top btn_level2; + public GGroup group_; + public GTextField txt_title; + public GButton btn_close1; + public GProgressBar pb_condi2; + public GTextField text_condi2; + public const string URL = "ui://3xypx0e8upx71p"; + + public static com_saveingpot CreateInstance() + { + return (com_saveingpot)UIPackage.CreateObject("SaveingPot", "com_saveingpot"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + type = GetControllerAt(0); + cont_confirm = GetControllerAt(1); + ani_potparent = (GGraph)GetChildAt(0); + text_remaintime = (GTextField)GetChildAt(6); + btn_close = (GButton)GetChildAt(7); + progress_cash = (GProgressBar)GetChildAt(8); + text_cashprogress = (GTextField)GetChildAt(9); + text_nowcash = (GTextField)GetChildAt(10); + text_ad = (GTextField)GetChildAt(12); + text_pay = (GTextField)GetChildAt(13); + btn_cash = (GButton)GetChildAt(14); + text_lose = (GTextField)GetChildAt(15); + broad = (com_broadcast)GetChildAt(16); + com_info = (com_enter)GetChildAt(19); + com_fname = (com_firstname)GetChildAt(20); + com_lname = (com_firstname)GetChildAt(21); + text_title = (GTextField)GetChildAt(22); + text_smaill_title = (GTextField)GetChildAt(23); + btn_confirm = (GButton)GetChildAt(24); + text_smaill_title_2 = (GTextField)GetChildAt(26); + com_pay = (com_info)GetChildAt(27); + text_wallet = (GTextField)GetChildAt(29); + text_cash = (GTextField)GetChildAt(30); + text_account = (GTextField)GetChildAt(31); + com_task = (com_task)GetChildAt(35); + com_newRecord = (com_newRecord)GetChildAt(36); + btn_watch = (btn_pay)GetChildAt(37); + text_query = (GTextField)GetChildAt(40); + text_payhint = (GTextField)GetChildAt(42); + btn_level0 = (btn_top)GetChildAt(43); + btn_level1 = (btn_top)GetChildAt(44); + btn_level2 = (btn_top)GetChildAt(45); + group_ = (GGroup)GetChildAt(46); + txt_title = (GTextField)GetChildAt(47); + btn_close1 = (GButton)GetChildAt(48); + pb_condi2 = (GProgressBar)GetChildAt(50); + text_condi2 = (GTextField)GetChildAt(52); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs.meta new file mode 100644 index 0000000..d1141c8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_saveingpot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83a0800ff000f4f859cb42184eb7a46e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs new file mode 100644 index 0000000..dbe5032 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs @@ -0,0 +1,33 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.SaveingPot +{ + public partial class com_task : GComponent + { + public Controller cont_process; + public GTextField text_orderid; + public GTextField text_task_title; + public GTextField text_ads; + public GTextField text_payer; + public const string URL = "ui://3xypx0e8es171x"; + + public static com_task CreateInstance() + { + return (com_task)UIPackage.CreateObject("SaveingPot", "com_task"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + cont_process = GetControllerAt(0); + text_orderid = (GTextField)GetChildAt(6); + text_task_title = (GTextField)GetChildAt(7); + text_ads = (GTextField)GetChildAt(8); + text_payer = (GTextField)GetChildAt(10); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs.meta b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs.meta new file mode 100644 index 0000000..7ca528a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/SaveingPot/com_task.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 855fb3bf313434d719b5b9557cb0f3a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu.meta b/Assets/CrazyZoo/FGUI/Package/bkg_jilu.meta new file mode 100644 index 0000000..6d3bf47 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 782e04a65ec9648e3b85cafc941f5b02 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs new file mode 100644 index 0000000..3fecba0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs @@ -0,0 +1,16 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.bkg_jilu +{ + public class bkg_jiluBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_jilu.URL, typeof(com_jilu)); + UIObjectFactory.SetPackageItemExtension(com_record_item.URL, typeof(com_record_item)); + UIObjectFactory.SetPackageItemExtension(com_panel.URL, typeof(com_panel)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs.meta new file mode 100644 index 0000000..dacd0ae --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/bkg_jiluBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e52e35aecfd924c199db4eec6e9528bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs new file mode 100644 index 0000000..8ed298e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_jilu +{ + public partial class com_jilu : GComponent + { + public GButton btn_close; + public com_panel panel; + public GTextField txt_title; + public const string URL = "ui://u5bqcwhxf6p00"; + + public static com_jilu CreateInstance() + { + return (com_jilu)UIPackage.CreateObject("bkg_jilu", "com_jilu"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + btn_close = (GButton)GetChildAt(2); + panel = (com_panel)GetChildAt(3); + txt_title = (GTextField)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs.meta new file mode 100644 index 0000000..db50536 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_jilu.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd4c95c8c765b4e6fbe1a0cc63ba807e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs new file mode 100644 index 0000000..36996f8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs @@ -0,0 +1,41 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_jilu +{ + public partial class com_panel : GComponent + { + public com_record_item item0; + public com_record_item item1; + public com_record_item item2; + public com_record_item item3; + public com_record_item item4; + public com_record_item item5; + public com_record_item item6; + public com_record_item item7; + public com_record_item item8; + public const string URL = "ui://u5bqcwhxf6p05"; + + public static com_panel CreateInstance() + { + return (com_panel)UIPackage.CreateObject("bkg_jilu", "com_panel"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + item0 = (com_record_item)GetChildAt(0); + item1 = (com_record_item)GetChildAt(1); + item2 = (com_record_item)GetChildAt(2); + item3 = (com_record_item)GetChildAt(3); + item4 = (com_record_item)GetChildAt(4); + item5 = (com_record_item)GetChildAt(5); + item6 = (com_record_item)GetChildAt(6); + item7 = (com_record_item)GetChildAt(7); + item8 = (com_record_item)GetChildAt(8); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs.meta new file mode 100644 index 0000000..fa15c0c --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_panel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db2b9ec2f78594d1ca0dee4c0d59f174 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs new file mode 100644 index 0000000..4b59bf9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_jilu +{ + public partial class com_record_item : GComponent + { + public GTextField name; + public GTextField num; + public GTextField time; + public const string URL = "ui://u5bqcwhxf6p04"; + + public static com_record_item CreateInstance() + { + return (com_record_item)UIPackage.CreateObject("bkg_jilu", "com_record_item"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + name = (GTextField)GetChildAt(2); + num = (GTextField)GetChildAt(4); + time = (GTextField)GetChildAt(5); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs.meta new file mode 100644 index 0000000..272ec19 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_jilu/com_record_item.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24fb6d718725f4f81b95df75c0ea032a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new.meta new file mode 100644 index 0000000..49bc68f --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c036d3edf0ee34e77bf9dc2f0bbf2cb7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs new file mode 100644 index 0000000..faaded3 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs @@ -0,0 +1,18 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.bkg_reward_new +{ + public class bkg_reward_newBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(com_reward_mul.URL, typeof(com_reward_mul)); + UIObjectFactory.SetPackageItemExtension(com_reward_coin.URL, typeof(com_reward_coin)); + UIObjectFactory.SetPackageItemExtension(com_reward_undo.URL, typeof(com_reward_undo)); + UIObjectFactory.SetPackageItemExtension(com_reward_moveout.URL, typeof(com_reward_moveout)); + UIObjectFactory.SetPackageItemExtension(com_reward_refresh.URL, typeof(com_reward_refresh)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs.meta new file mode 100644 index 0000000..0901244 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/bkg_reward_newBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 121ad67ddd5f24c79aefae4c846f2d44 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs new file mode 100644 index 0000000..06527d8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_reward_new +{ + public partial class com_reward_coin : GComponent + { + public GTextField lab_num; + public const string URL = "ui://xwnagx5bq6oz5"; + + public static com_reward_coin CreateInstance() + { + return (com_reward_coin)UIPackage.CreateObject("bkg_reward_new", "com_reward_coin"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + lab_num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs.meta new file mode 100644 index 0000000..486ed01 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_coin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c761f105b57946079de7744af1b8418 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs new file mode 100644 index 0000000..c192410 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_reward_new +{ + public partial class com_reward_moveout : GComponent + { + public Controller state; + public GTextField lab_num; + public const string URL = "ui://xwnagx5bq6oz9"; + + public static com_reward_moveout CreateInstance() + { + return (com_reward_moveout)UIPackage.CreateObject("bkg_reward_new", "com_reward_moveout"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + lab_num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs.meta new file mode 100644 index 0000000..5ea069b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_moveout.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 585a19b37d0e443348719df5349e0689 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs new file mode 100644 index 0000000..b3b42c9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs @@ -0,0 +1,51 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_reward_new +{ + public partial class com_reward_mul : GComponent + { + public GGraph ani_node; + public com_reward_coin node_coin; + public com_reward_undo node_undo; + public com_reward_moveout node_move_out; + public com_reward_refresh node_refresh; + public GGroup node_group; + public GGraph node_end; + public com_reward_undo add_undo; + public com_reward_moveout add_move_out; + public com_reward_refresh add_refresh; + public GGroup ani_group; + public GButton btn_mul; + public GButton btn_claim; + public Transition t0; + public const string URL = "ui://xwnagx5bq6oz0"; + + public static com_reward_mul CreateInstance() + { + return (com_reward_mul)UIPackage.CreateObject("bkg_reward_new", "com_reward_mul"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + ani_node = (GGraph)GetChildAt(0); + node_coin = (com_reward_coin)GetChildAt(2); + node_undo = (com_reward_undo)GetChildAt(3); + node_move_out = (com_reward_moveout)GetChildAt(4); + node_refresh = (com_reward_refresh)GetChildAt(5); + node_group = (GGroup)GetChildAt(6); + node_end = (GGraph)GetChildAt(8); + add_undo = (com_reward_undo)GetChildAt(9); + add_move_out = (com_reward_moveout)GetChildAt(10); + add_refresh = (com_reward_refresh)GetChildAt(11); + ani_group = (GGroup)GetChildAt(12); + btn_mul = (GButton)GetChildAt(13); + btn_claim = (GButton)GetChildAt(14); + t0 = GetTransitionAt(0); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs.meta new file mode 100644 index 0000000..29d1ae8 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_mul.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 975f298f6841f45efbb6cb30ae4910b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs new file mode 100644 index 0000000..847b61b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_reward_new +{ + public partial class com_reward_refresh : GComponent + { + public Controller state; + public GTextField lab_num; + public const string URL = "ui://xwnagx5bq6oza"; + + public static com_reward_refresh CreateInstance() + { + return (com_reward_refresh)UIPackage.CreateObject("bkg_reward_new", "com_reward_refresh"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + lab_num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs.meta new file mode 100644 index 0000000..fa4dfba --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_refresh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6733af3c75164f64b2bac855a70dc07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs new file mode 100644 index 0000000..d1ba99d --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.bkg_reward_new +{ + public partial class com_reward_undo : GComponent + { + public Controller state; + public GTextField lab_num; + public const string URL = "ui://xwnagx5bq6oz8"; + + public static com_reward_undo CreateInstance() + { + return (com_reward_undo)UIPackage.CreateObject("bkg_reward_new", "com_reward_undo"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + lab_num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs.meta b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs.meta new file mode 100644 index 0000000..f2715cf --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/bkg_reward_new/com_reward_undo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a516c5e6ca5dc47c5a70be7f55b0f6e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/failpack.meta b/Assets/CrazyZoo/FGUI/Package/failpack.meta new file mode 100644 index 0000000..3cec252 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 77902d730e94f4310a45cf4583ee36e2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs b/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs new file mode 100644 index 0000000..37f8fb6 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs @@ -0,0 +1,25 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.failpack +{ + public partial class btn_get_1 : GButton + { + public GImage img_saveingpot; + public const string URL = "ui://35wdsj8phrbwj"; + + public static btn_get_1 CreateInstance() + { + return (btn_get_1)UIPackage.CreateObject("failpack", "btn_get_1"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + img_saveingpot = (GImage)GetChildAt(2); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs.meta b/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs.meta new file mode 100644 index 0000000..dc99771 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/btn_get_1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64947fae3d09e4cedbac5807ce20cf4a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs b/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs new file mode 100644 index 0000000..bc03c7b --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.failpack +{ + public partial class btn_green_1 : GButton + { + public Controller state; + public Controller cooldown; + public GImage img_saveingpot; + public const string URL = "ui://35wdsj8phrbwl"; + + public static btn_green_1 CreateInstance() + { + return (btn_green_1)UIPackage.CreateObject("failpack", "btn_green_1"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + cooldown = GetControllerAt(1); + img_saveingpot = (GImage)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs.meta b/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs.meta new file mode 100644 index 0000000..f55b6ef --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/btn_green_1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9a456c63749844948a6cb1e47ce26c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs b/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs new file mode 100644 index 0000000..5ce9e21 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs @@ -0,0 +1,55 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.failpack +{ + public partial class com_resurgence : GComponent + { + public Controller pay_type; + public GImage bg; + public GProgressBar progress_1; + public GTextField text_have; + public GTextField need_text; + public GTextField text_remain; + public GTextField text_progress; + public GTextField text_refreshnum; + public GTextField text_outnum; + public GTextField text_backnum; + public GTextField text_goldnum; + public GTextField end_point; + public GButton btn_buy; + public GButton btn_buyPackClaim; + public GButton btn_back; + public GButton btn_max_pay; + public const string URL = "ui://35wdsj8pupx737"; + + public static com_resurgence CreateInstance() + { + return (com_resurgence)UIPackage.CreateObject("failpack", "com_resurgence"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + pay_type = GetControllerAt(0); + bg = (GImage)GetChildAt(2); + progress_1 = (GProgressBar)GetChildAt(3); + text_have = (GTextField)GetChildAt(4); + need_text = (GTextField)GetChildAt(5); + text_remain = (GTextField)GetChildAt(7); + text_progress = (GTextField)GetChildAt(9); + text_refreshnum = (GTextField)GetChildAt(10); + text_outnum = (GTextField)GetChildAt(11); + text_backnum = (GTextField)GetChildAt(12); + text_goldnum = (GTextField)GetChildAt(14); + end_point = (GTextField)GetChildAt(15); + btn_buy = (GButton)GetChildAt(16); + btn_buyPackClaim = (GButton)GetChildAt(17); + btn_back = (GButton)GetChildAt(18); + btn_max_pay = (GButton)GetChildAt(22); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs.meta b/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs.meta new file mode 100644 index 0000000..ab8fafa --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/com_resurgence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a544359f346f0442e8530c8d1fb2075e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs b/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs new file mode 100644 index 0000000..3a7a255 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs @@ -0,0 +1,16 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.failpack +{ + public class failpackBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(btn_get_1.URL, typeof(btn_get_1)); + UIObjectFactory.SetPackageItemExtension(btn_green_1.URL, typeof(btn_green_1)); + UIObjectFactory.SetPackageItemExtension(com_resurgence.URL, typeof(com_resurgence)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs.meta new file mode 100644 index 0000000..f253e35 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/failpack/failpackBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d695e55c80bd54f34948f8c15c10b35c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift.meta new file mode 100644 index 0000000..57c4c54 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea3613d31058141629be339e9e4307c0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs new file mode 100644 index 0000000..ce01685 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.threeDaysGift +{ + public partial class btn_AdRevive : GButton + { + public GTextField text_cooldown; + public GImage img_saveingpot; + public const string URL = "ui://knycs0rkjq3i11"; + + public static btn_AdRevive CreateInstance() + { + return (btn_AdRevive)UIPackage.CreateObject("threeDaysGift", "btn_AdRevive"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + text_cooldown = (GTextField)GetChildAt(3); + img_saveingpot = (GImage)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs.meta new file mode 100644 index 0000000..9685466 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_AdRevive.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7124eddc30cee4a378c49a3c4ce1e0cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs new file mode 100644 index 0000000..6da4e0e --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs @@ -0,0 +1,29 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.threeDaysGift +{ + public partial class btn_green : GButton + { + public Controller state; + public Controller cooldown; + public GImage img_saveingpot; + public const string URL = "ui://knycs0rkjq3i13"; + + public static btn_green CreateInstance() + { + return (btn_green)UIPackage.CreateObject("threeDaysGift", "btn_green"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + cooldown = GetControllerAt(1); + img_saveingpot = (GImage)GetChildAt(4); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs.meta new file mode 100644 index 0000000..eb23214 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/btn_green.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5266b534a84d745b5a88f008b5d6daa9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs new file mode 100644 index 0000000..b7c056a --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs @@ -0,0 +1,39 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.threeDaysGift +{ + public partial class com_item : GComponent + { + public Controller state; + public Controller day; + public item_reward item1; + public item_reward item2; + public item_reward item3; + public item_reward item4; + public GImage img_select; + public GImage img_select2; + public const string URL = "ui://knycs0rkke931"; + + public static com_item CreateInstance() + { + return (com_item)UIPackage.CreateObject("threeDaysGift", "com_item"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + state = GetControllerAt(0); + day = GetControllerAt(1); + item1 = (item_reward)GetChildAt(3); + item2 = (item_reward)GetChildAt(4); + item3 = (item_reward)GetChildAt(5); + item4 = (item_reward)GetChildAt(6); + img_select = (GImage)GetChildAt(7); + img_select2 = (GImage)GetChildAt(8); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs.meta new file mode 100644 index 0000000..9a2d406 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_item.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 832322d51e60e4a3f89bc368e534cd8d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs new file mode 100644 index 0000000..0d9ee01 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs @@ -0,0 +1,51 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.threeDaysGift +{ + public partial class com_three_days : GComponent + { + public Controller pay_type; + public GGraph ani_bg; + public GGraph node_end; + public com_item day1; + public com_item day2; + public com_item day3; + public GTextField text_have; + public GTextField need_text; + public GGraph ani_title; + public GButton btn_get; + public GButton btn_close; + public btn_green btn_buypack; + public GButton btn_max_pack; + public GGroup groups; + public const string URL = "ui://knycs0rkke930"; + + public static com_three_days CreateInstance() + { + return (com_three_days)UIPackage.CreateObject("threeDaysGift", "com_three_days"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + pay_type = GetControllerAt(0); + ani_bg = (GGraph)GetChildAt(0); + node_end = (GGraph)GetChildAt(1); + day1 = (com_item)GetChildAt(3); + day2 = (com_item)GetChildAt(4); + day3 = (com_item)GetChildAt(5); + text_have = (GTextField)GetChildAt(6); + need_text = (GTextField)GetChildAt(7); + ani_title = (GGraph)GetChildAt(9); + btn_get = (GButton)GetChildAt(10); + btn_close = (GButton)GetChildAt(11); + btn_buypack = (btn_green)GetChildAt(12); + btn_max_pack = (GButton)GetChildAt(13); + groups = (GGroup)GetChildAt(14); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs.meta new file mode 100644 index 0000000..e13f947 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/com_three_days.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 955dc40fab0a14f8c82edfd4b17b38be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs new file mode 100644 index 0000000..81ee309 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs @@ -0,0 +1,27 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; +using FairyGUI.Utils; + +namespace FGUI.threeDaysGift +{ + public partial class item_reward : GComponent + { + public GLoader loader_; + public GTextField lab_num; + public const string URL = "ui://knycs0rkke932"; + + public static item_reward CreateInstance() + { + return (item_reward)UIPackage.CreateObject("threeDaysGift", "item_reward"); + } + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + loader_ = (GLoader)GetChildAt(0); + lab_num = (GTextField)GetChildAt(1); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs.meta new file mode 100644 index 0000000..322dac9 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/item_reward.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45171a84d4607468d98f9c36fa91160e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs new file mode 100644 index 0000000..4e05ca0 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs @@ -0,0 +1,18 @@ +/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ + +using FairyGUI; + +namespace FGUI.threeDaysGift +{ + public class threeDaysGiftBinder + { + public static void BindAll() + { + UIObjectFactory.SetPackageItemExtension(btn_AdRevive.URL, typeof(btn_AdRevive)); + UIObjectFactory.SetPackageItemExtension(btn_green.URL, typeof(btn_green)); + UIObjectFactory.SetPackageItemExtension(com_three_days.URL, typeof(com_three_days)); + UIObjectFactory.SetPackageItemExtension(com_item.URL, typeof(com_item)); + UIObjectFactory.SetPackageItemExtension(item_reward.URL, typeof(item_reward)); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs.meta b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs.meta new file mode 100644 index 0000000..0cfe2a1 --- /dev/null +++ b/Assets/CrazyZoo/FGUI/Package/threeDaysGift/threeDaysGiftBinder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1716d7a0fa3354085ae6cd1f435e87b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/MVCBuildWindow.cs b/Assets/CrazyZoo/MVCBuildWindow.cs new file mode 100644 index 0000000..114761e --- /dev/null +++ b/Assets/CrazyZoo/MVCBuildWindow.cs @@ -0,0 +1,398 @@ +#if UNITY_EDITOR +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor; +using UnityEngine; + +namespace FutureEditor +{ + public class MVCBuildWindow : EditorWindow + { + private static string mvcClassName; //mvc 模块名 + private static string fguiPackageName; //FGUI 包名 + private static string fguiCompName; //FGUI 组建名 + private static string foldePath; + static string mvcRootPath = "/CrazyZoo/Runtime/Logic/ModuleUI/"; //创建MVC模块的目录 + + [MenuItem("Jarvis/MVC/创建MVC代码模板", false, 0)] + private static void ShowWindow() + { + MVCBuildWindow window = GetWindow(true, "创建MVC代码模板窗口"); + window.minSize = new Vector2(280f, 170f); + window.maxSize = window.minSize; + window.Show(); + } + + private void OnGUI() + { + EditorGUILayout.Space(); + EditorGUILayout.BeginVertical(); + + GUILayout.Space(5); + GUILayout.BeginHorizontal(); + GUILayout.Label("MVC模块名:"); + mvcClassName = EditorGUILayout.TextField(mvcClassName, GUILayout.Height(20)); + GUILayout.EndHorizontal(); + GUILayout.Space(10); + GUILayout.BeginHorizontal(); + GUILayout.Label("FGUI包名:"); + fguiPackageName = EditorGUILayout.TextField(fguiPackageName, GUILayout.Height(20)); + GUILayout.EndHorizontal(); + GUILayout.Space(10); + GUILayout.BeginHorizontal(); + GUILayout.Label("FGUI组件名:"); + fguiCompName = EditorGUILayout.TextField(fguiCompName, GUILayout.Height(20)); + GUILayout.EndHorizontal(); + GUILayout.Space(10); + if (GUILayout.Button("创建", GUILayout.Height(25))) + { + CreateMVC(mvcClassName); + } + EditorGUILayout.EndVertical(); + } + + private static void CreateMVC(string mvcName) + { + if (!string.IsNullOrEmpty(mvcName)) + { + string mvcPath = mvcRootPath + mvcName; + foldePath = Application.dataPath + mvcPath; + if (Directory.Exists(foldePath)) + { + Debug.LogError("[MVCBuildWindow]Folde is exist!!!: " + foldePath); + Debug.LogError("[MVCBuildWindow]Create MVC Fail:" + mvcName); + return; + } + Directory.CreateDirectory(foldePath); + + CreateModel(mvcName); + CreateUI(mvcName); + CreateCtrl(mvcName); + CreateUICtrl(mvcName); + RegisterModule(mvcName); + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + + SelectObject("Assets/" + mvcPath); + Debug.Log("[MVCBuildWindow]创建MVC代码模板完成"); + } + } + + private static void SelectObject(string path) + { + Object obj = AssetDatabase.LoadMainAssetAtPath(path); + if (obj == null) return; + + EditorGUIUtility.PingObject(obj); + Selection.activeObject = obj; + } + + private static void CreateModel(string className) + { + string modelClassStr = +@" + +namespace CrazyZoo +{ + public class #ClassName#Model : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +}"; + + string replaceClassName = "#ClassName#"; + modelClassStr = modelClassStr.Replace(replaceClassName, className); + string targetPath = foldePath + "/" + className + "Model.cs"; + File.WriteAllText(targetPath, modelClassStr, new UTF8Encoding(false)); + } + + private static void CreateUI(string className) + { + string uiClassStr = +@" +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; + +namespace CrazyZoo +{ + public class #ClassName#UI : BaseUI + { + private #ClassName#UICtrl ctrl; + private #ClassName#Model model; + private FGUI.#PackageName#.#CompName# ui; + + public #ClassName#UI(#ClassName#UICtrl ctrl) : base(ctrl) + { + uiName = UIConst.#ClassName#UI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = ""#PackageName#""; + uiInfo.assetName = ""#CompName#""; + uiInfo.layerType = UILayerType.Normal; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.#ClassName#Model) as #ClassName#Model; + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.#PackageName#.#CompName#; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + + } + } +}"; + string replacePackageName = "#PackageName#"; + uiClassStr = uiClassStr.Replace(replacePackageName, fguiPackageName); + string replaceCompName = "#CompName#"; + uiClassStr = uiClassStr.Replace(replaceCompName, fguiCompName); + string replaceClassName = "#ClassName#"; + uiClassStr = uiClassStr.Replace(replaceClassName, className); + string targetPath = foldePath + "/" + className + "UI.cs"; + File.WriteAllText(targetPath, uiClassStr, new UTF8Encoding(false)); + } + + private static void CreateCtrl(string className) + { + string ctrlClassStr = +@" + +namespace CrazyZoo +{ + public class #ClassName#Ctrl : BaseCtrl + { + public static #ClassName#Ctrl Instance { get; private set; } + + private #ClassName#Model model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.#ClassName#Model) as #ClassName#Model; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +}"; + + string replaceClassName = "#ClassName#"; + ctrlClassStr = ctrlClassStr.Replace(replaceClassName, className); + string targetPath = foldePath + "/" + className + "Ctrl.cs"; + File.WriteAllText(targetPath, ctrlClassStr, new UTF8Encoding(false)); + } + + private static void CreateUICtrl(string className) + { + string uiCtrlClassStr = +@" + +namespace CrazyZoo +{ + public class #ClassName#UICtrl : BaseUICtrl + { + private #ClassName#UI ui; + private #ClassName#Model model; + + private uint openUIMsg = UICtrlMsg.#ClassName#UI_Open; + private uint closeUIMsg = UICtrlMsg.#ClassName#UI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.#ClassName#Model) as #ClassName#Model; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new #ClassName#UI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +}"; + + string replaceClassName = "#ClassName#"; + uiCtrlClassStr = uiCtrlClassStr.Replace(replaceClassName, className); + string targetPath = foldePath + "/" + className + "UICtrl.cs"; + File.WriteAllText(targetPath, uiCtrlClassStr, new UTF8Encoding(false)); + } + + //测试 + // [MenuItem("Jarvis/MVC/RegisterModuleXXX", false, 0)] + // static void RegisterModuleXXX(){ + // RegisterModule("mmm"); + // AssetDatabase.SaveAssets(); + // AssetDatabase.Refresh(); + // } + + //注册模块 + static void RegisterModule(string name){ + //模块管理路径以及相关文件路径 + string moduleMngRootPath = Application.dataPath + "/CrazyZoo/Runtime//Logic/ModuleManager/"; + string ctrlPath = moduleMngRootPath + "CtrlConst.cs"; + string modelPath = moduleMngRootPath + "ModelConst.cs"; + string uiConstPath = moduleMngRootPath + "UIConst.cs"; + string uiCtrlPath = moduleMngRootPath + "UICtrlConst.cs"; + string moduleMngPath = moduleMngRootPath + "ModuleManagerRegister.cs"; + string UICtrlMsgPath = Application.dataPath + "/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs"; + + //注册模块的常量 + InsertString(ctrlPath, $"\tpublic const string {name}Ctrl = \"{name}Ctrl\";\n\t"); + InsertString(modelPath, $"\tpublic const string {name}Model = \"{name}Model\";\n\t"); + InsertString(uiConstPath, $"\tpublic const string {name}UI = \"{name}UI\";\n\t"); + InsertString(uiCtrlPath, $"\tpublic const string {name}UICtrl = \"{name}UICtrl\";\n\t"); + + //在模块类注册新模块 + InsertStringBeforeCharIndex(moduleMngPath, 0, $"\tmoduleManager.AddModel(ModelConst.{name}Model, new {name}Model());\n\t\t"); + InsertStringBeforeCharIndex(moduleMngPath, 1, $"\tmoduleManager.AddUIType(UIConst.{name}UI, typeof({name}UI));\n\t\t"); + InsertStringBeforeCharIndex(moduleMngPath, 2, $"\tmoduleManager.AddCtrl(CtrlConst.{name}Ctrl, new {name}Ctrl());\n\t\t"); + InsertStringBeforeCharIndex(moduleMngPath, 3, $"\tmoduleManager.AddUICtrl(UICtrlConst.{name}UICtrl, new {name}UICtrl());\n\t\t"); + + InsertString(UICtrlMsgPath, $"\tpublic static uint {name}UI_Open = ++cursor_OpenClose;\n\t\tpublic static uint {name}UI_Close = ++cursor_OpenClose;\n\t"); + } + + static void InsertString(string path, string str){ + string f = File.ReadAllText(path); + int index = f.IndexOf('}'); + f = f.Insert(index, str); + File.WriteAllText(path, f); + } + + static void InsertStringBeforeCharIndex(string path, int charIndex, string str){ + string f = File.ReadAllText(path); + int indexCount = 0; + int index = -1; + for (int i = 0; i < f.Length; i++) + { + char c = f[i]; + if (c == '}' ){ + if (indexCount == charIndex){ + index = i; + break; + } + else{ + indexCount++; + } + } + } + if (index != -1){ + f = f.Insert(index, str); + File.WriteAllText(path, f); + } + } + } +} +#endif \ No newline at end of file diff --git a/Assets/CrazyZoo/MVCBuildWindow.cs.meta b/Assets/CrazyZoo/MVCBuildWindow.cs.meta new file mode 100644 index 0000000..27f2ec3 --- /dev/null +++ b/Assets/CrazyZoo/MVCBuildWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89cdbbc15e57b9741aeacd3504d45639 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins.meta b/Assets/CrazyZoo/Plugins.meta new file mode 100644 index 0000000..5c05a37 --- /dev/null +++ b/Assets/CrazyZoo/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d83b61e5d2dd0e947bc8e4087fe179e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro.meta b/Assets/CrazyZoo/Plugins/ConsolePro.meta new file mode 100644 index 0000000..99b73d0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1da41d8b0c914984fa076026f57a3fa1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs b/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs new file mode 100644 index 0000000..d933f09 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs @@ -0,0 +1,99 @@ +using UnityEngine; +using System; +#if UNITY_EDITOR +using System.Reflection; +#endif + +public static class ConsoleProDebug +{ + // Clear the console and the native console + public static void Clear() + { + #if UNITY_EDITOR + if(ConsoleClearMethod != null) + { + ConsoleClearMethod.Invoke(null, null); + } + #endif + } + + // Send a log to a specific filter regardless of contents + // Ex: ConsoleProDebug.LogToFilter("Hi", "CustomFilter"); + public static void LogToFilter(string inLog, string inFilterName) + { + Debug.Log(inLog + "\nCPAPI:{\"cmd\":\"Filter\" \"name\":\"" + inFilterName + "\"}"); + } + + // Send a log as a regular log but change its type in ConsolePro + // Ex: ConsoleProDebug.LogAsType("Hi", "Error"); + public static void LogAsType(string inLog, string inTypeName) + { + Debug.Log(inLog + "\nCPAPI:{\"cmd\":\"LogType\" \"name\":\"" + inTypeName + "\"}"); + } + + // Watch a variable. This will only produce one log entry regardless of how many times it is logged, allowing you to track variables without spam. + // Ex: + // void Update() { + // ConsoleProDebug.Watch("Player X Position", transform.position.x); + // } + public static void Watch(string inName, string inValue) + { + Debug.Log(inName + " : " + inValue + "\nCPAPI:{\"cmd\":\"Watch\" \"name\":\"" + inName + "\"}"); + } + + public static void Search(string inText) + { + Debug.Log("\nCPAPI:{\"cmd\":\"Search\" \"text\":\"" + inText + "\"}"); + } + + #if UNITY_EDITOR + // Reflection calls to access Console Pro from runtime + private static bool _checkedConsoleClearMethod = false; + private static MethodInfo _consoleClearMethod = null; + private static MethodInfo ConsoleClearMethod + { + get + { + if(_consoleClearMethod == null || !_checkedConsoleClearMethod) + { + _checkedConsoleClearMethod = true; + if(ConsoleWindowType == null) + { + return null; + } + + _consoleClearMethod = ConsoleWindowType.GetMethod("ClearEntries", BindingFlags.Static | BindingFlags.Public); + } + + return _consoleClearMethod; + } + } + + private static bool _checkedConsoleWindowType = false; + private static Type _consoleWindowType = null; + private static Type ConsoleWindowType + { + get + { + if(_consoleWindowType == null || !_checkedConsoleWindowType) + { + _checkedConsoleWindowType = true; + Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); + for(int iAssembly = 0; iAssembly < assemblies.Length; iAssembly++) + { + Type[] types = assemblies[iAssembly].GetTypes(); + for(int iType = 0; iType < types.Length; iType++) + { + if(types[iType].Name == "ConsolePro3Window") + { + _consoleWindowType = types[iType]; + } + } + } + } + + return _consoleWindowType; + } + } + #endif +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs.meta new file mode 100644 index 0000000..56fa712 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/ConsoleProDebug.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 30f42e8a12eb842acbe9a63057fb00e4 +timeCreated: 1469329295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf b/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf new file mode 100644 index 0000000..c57db87 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf differ diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf.meta new file mode 100644 index 0000000..ba3a58a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Editor Console Pro Documentation.pdf.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5de782a9528f04b41a8ba70afba32a61 +timeCreated: 1498113024 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Editor.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Editor.meta new file mode 100644 index 0000000..0e3736e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: be7aee03972b847e4a8b81ef8ce46a8e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll b/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll new file mode 100644 index 0000000..e6c3704 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll differ diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll.meta new file mode 100644 index 0000000..a1b21a1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Editor/ConsolePro.Editor.dll.meta @@ -0,0 +1,30 @@ +fileFormatVersion: 2 +guid: a2284c517ee274c19a6ba4c1a8c96fb6 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote.meta new file mode 100644 index 0000000..8c0572e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1d51a9b386eb4992af4cb193629d854 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs new file mode 100644 index 0000000..62cba16 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs @@ -0,0 +1,237 @@ +// Uncomment to use in Editor +// #define USECONSOLEPROREMOTESERVERINEDITOR + +#if (!UNITY_EDITOR && DEBUG) || (UNITY_EDITOR && USECONSOLEPROREMOTESERVERINEDITOR) + #define USECONSOLEPROREMOTESERVER +#endif + +#if (UNITY_WP_8_1 || UNITY_WSA) + #define UNSUPPORTEDCONSOLEPROREMOTESERVER +#endif + +#if UNITY_EDITOR && !USECONSOLEPROREMOTESERVER +#elif UNSUPPORTEDCONSOLEPROREMOTESERVER +#elif !USECONSOLEPROREMOTESERVER +#else +using System; +using System.Collections.Generic; +#endif + +using UnityEngine; + +#if USECONSOLEPROREMOTESERVER +using FlyingWormConsole3.LiteNetLib; +using FlyingWormConsole3.LiteNetLib.Utils; +#endif + +namespace FlyingWormConsole3 +{ + #if USECONSOLEPROREMOTESERVER +public class ConsoleProRemoteServer : MonoBehaviour, INetEventListener + #else +public class ConsoleProRemoteServer : MonoBehaviour + #endif +{ + public bool useNATPunch = false; + public int port = 51000; + + #if UNITY_EDITOR && !USECONSOLEPROREMOTESERVER + + #elif UNSUPPORTEDCONSOLEPROREMOTESERVER + + public void Awake() + { + Debug.Log("Console Pro Remote Server is not supported on this platform"); + } + + #elif !USECONSOLEPROREMOTESERVER + + public void Awake() + { + Debug.Log("Console Pro Remote Server is disabled in release mode, please use a Development build or define DEBUG to use it"); + } + + #else + + private NetManager _netServer; + private NetPeer _ourPeer; + private NetDataWriter _dataWriter; + + [System.SerializableAttribute] + public class QueuedLog + { + public string message; + public string stackTrace; + public LogType type; + } + + + [NonSerializedAttribute] + public List logs = new List(); + + private static ConsoleProRemoteServer instance = null; + + void Awake() + { + if(instance != null) + { + Destroy(gameObject); + } + + instance = this; + + DontDestroyOnLoad(gameObject); + + Debug.Log("Starting Console Pro Server on port : " + port); + + _dataWriter = new NetDataWriter(); + _netServer = new NetManager(this, 100, "ConsolePro"); + _netServer.Start(port); + _netServer.DiscoveryEnabled = true; + _netServer.UpdateTime = 15; + _netServer.MergeEnabled = true; + _netServer.NatPunchEnabled = useNATPunch; + } + + void OnDestroy() + { + if(_netServer != null) + { + _netServer.Stop(); + } + } + + public void OnPeerConnected(NetPeer peer) + { + Debug.Log("Connected to " + peer.EndPoint); + _ourPeer = peer; + } + + public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) + { + Debug.Log("Disconnected from " + peer.EndPoint + ", info: " + disconnectInfo.Reason); + if (peer == _ourPeer) + { + _ourPeer = null; + } + } + + public void OnNetworkReceive(NetPeer peer, NetDataReader reader) + { + + } + + public void OnPeerDisconnected(NetPeer peer, DisconnectReason reason, int socketErrorCode) + { + + } + + public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode) + { + } + + public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType) + { + if (messageType == UnconnectedMessageType.DiscoveryRequest) + { + // Debug.Log("[SERVER] Received discovery request. Send discovery response"); + _netServer.SendDiscoveryResponse(new byte[] {1}, remoteEndPoint); + } + } + + public void OnNetworkLatencyUpdate(NetPeer peer, int latency) + { + + } + + + #if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 + + void OnEnable() + { + Application.RegisterLogCallback(LogCallback); + } + + void Update() + { + Application.RegisterLogCallback(LogCallback); + } + + void OnDisable() + { + Application.RegisterLogCallback(null); + } + + #else + + void OnEnable() + { + Application.logMessageReceived += LogCallback; + } + + void OnDisable() + { + Application.logMessageReceived -= LogCallback; + } + + #endif + + public void LogCallback(string logString, string stackTrace, LogType type) + { + if(!logString.StartsWith("CPIGNORE")) + { + QueueLog(logString, stackTrace, type); + } + } + + void QueueLog(string logString, string stackTrace, LogType type) + { + if(logs.Count > 200) + { + while(logs.Count > 200) + { + logs.RemoveAt(0); + } + } + + logs.Add(new QueuedLog() { message = logString, stackTrace = stackTrace, type = type } ); + } + + void LateUpdate() + { + if(_netServer == null) + { + return; + } + + _netServer.PollEvents(); + + if(_ourPeer == null) + { + return; + } + + if(logs.Count <= 0) + { + return; + } + + string cMessage = ""; + + for(int i = 0; i < logs.Count; i++) + { + cMessage = ""; + + QueuedLog cLog = logs[i]; + cMessage = "::::" + cLog.type + "::::" + cLog.message + "\n" + cLog.stackTrace; + _dataWriter.Reset(); + _dataWriter.Put(cMessage); + _ourPeer.Send(_dataWriter, SendOptions.ReliableOrdered); + } + + logs.Clear(); + } + + #endif +} +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs.meta new file mode 100644 index 0000000..f706463 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/ConsoleProRemoteServer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d6bcfaced529e418bb75980b297fda2a +timeCreated: 1437614101 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib.meta new file mode 100644 index 0000000..82b978a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2c6bd635eeaa04c228b6d342c4758ad7 +folderAsset: yes +timeCreated: 1494014730 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs new file mode 100644 index 0000000..173b822 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs @@ -0,0 +1,120 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System.Runtime.InteropServices; + +namespace FlyingWormConsole3.LiteNetLib.Utils +{ + public static class FastBitConverter + { + [StructLayout(LayoutKind.Explicit)] + private struct ConverterHelperDouble + { + [FieldOffset(0)] + public ulong Along; + + [FieldOffset(0)] + public double Adouble; + } + + [StructLayout(LayoutKind.Explicit)] + private struct ConverterHelperFloat + { + [FieldOffset(0)] + public int Aint; + + [FieldOffset(0)] + public float Afloat; + } + + private static void WriteLittleEndian(byte[] buffer, int offset, ulong data) + { +#if BIGENDIAN + buffer[offset + 7] = (byte)(data); + buffer[offset + 6] = (byte)(data >> 8); + buffer[offset + 5] = (byte)(data >> 16); + buffer[offset + 4] = (byte)(data >> 24); + buffer[offset + 3] = (byte)(data >> 32); + buffer[offset + 2] = (byte)(data >> 40); + buffer[offset + 1] = (byte)(data >> 48); + buffer[offset ] = (byte)(data >> 56); +#else + buffer[offset] = (byte)(data); + buffer[offset + 1] = (byte)(data >> 8); + buffer[offset + 2] = (byte)(data >> 16); + buffer[offset + 3] = (byte)(data >> 24); + buffer[offset + 4] = (byte)(data >> 32); + buffer[offset + 5] = (byte)(data >> 40); + buffer[offset + 6] = (byte)(data >> 48); + buffer[offset + 7] = (byte)(data >> 56); +#endif + } + + private static void WriteLittleEndian(byte[] buffer, int offset, int data) + { +#if BIGENDIAN + buffer[offset + 3] = (byte)(data); + buffer[offset + 2] = (byte)(data >> 8); + buffer[offset + 1] = (byte)(data >> 16); + buffer[offset ] = (byte)(data >> 24); +#else + buffer[offset] = (byte)(data); + buffer[offset + 1] = (byte)(data >> 8); + buffer[offset + 2] = (byte)(data >> 16); + buffer[offset + 3] = (byte)(data >> 24); +#endif + } + + public static void WriteLittleEndian(byte[] buffer, int offset, short data) + { +#if BIGENDIAN + buffer[offset + 1] = (byte)(data); + buffer[offset ] = (byte)(data >> 8); +#else + buffer[offset] = (byte)(data); + buffer[offset + 1] = (byte)(data >> 8); +#endif + } + + public static void GetBytes(byte[] bytes, int startIndex, double value) + { + ConverterHelperDouble ch = new ConverterHelperDouble { Adouble = value }; + WriteLittleEndian(bytes, startIndex, ch.Along); + } + + public static void GetBytes(byte[] bytes, int startIndex, float value) + { + ConverterHelperFloat ch = new ConverterHelperFloat { Afloat = value }; + WriteLittleEndian(bytes, startIndex, ch.Aint); + } + + public static void GetBytes(byte[] bytes, int startIndex, short value) + { + WriteLittleEndian(bytes, startIndex, value); + } + + public static void GetBytes(byte[] bytes, int startIndex, ushort value) + { + WriteLittleEndian(bytes, startIndex, (short)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, int value) + { + WriteLittleEndian(bytes, startIndex, value); + } + + public static void GetBytes(byte[] bytes, int startIndex, uint value) + { + WriteLittleEndian(bytes, startIndex, (int)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, long value) + { + WriteLittleEndian(bytes, startIndex, (ulong)value); + } + + public static void GetBytes(byte[] bytes, int startIndex, ulong value) + { + WriteLittleEndian(bytes, startIndex, value); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs.meta new file mode 100644 index 0000000..0e19981 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/FastBitConverter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 55df0de9a58e74c9395dfe5ffdab9a5a +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs new file mode 100644 index 0000000..1d4408e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs @@ -0,0 +1,128 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using FlyingWormConsole3.LiteNetLib.Utils; + +namespace FlyingWormConsole3.LiteNetLib +{ + public enum UnconnectedMessageType + { + Default, + DiscoveryRequest, + DiscoveryResponse + } + + public enum DisconnectReason + { + SocketReceiveError, + ConnectionFailed, + Timeout, + SocketSendError, + RemoteConnectionClose, + DisconnectPeerCalled + } + + public struct DisconnectInfo + { + public DisconnectReason Reason; + public int SocketErrorCode; + public NetDataReader AdditionalData; + } + + public interface INetEventListener + { + /// + /// New remote peer connected to host, or client connected to remote host + /// + /// Connected peer object + void OnPeerConnected(NetPeer peer); + + /// + /// Peer disconnected + /// + /// disconnected peer + /// additional info about reason, errorCode or data received with disconnect message + void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); + + /// + /// Network error (on send or receive) + /// + /// From endPoint (can be null) + /// Socket error code + void OnNetworkError(NetEndPoint endPoint, int socketErrorCode); + + /// + /// Received some data + /// + /// From peer + /// DataReader containing all received data + void OnNetworkReceive(NetPeer peer, NetDataReader reader); + + /// + /// Received unconnected message + /// + /// From address (IP and Port) + /// Message data + /// Message type (simple, discovery request or responce) + void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType); + + /// + /// Latency information updated + /// + /// Peer with updated latency + /// latency value in milliseconds + void OnNetworkLatencyUpdate(NetPeer peer, int latency); + } + + public class EventBasedNetListener : INetEventListener + { + public delegate void OnPeerConnected(NetPeer peer); + public delegate void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo); + public delegate void OnNetworkError(NetEndPoint endPoint, int socketErrorCode); + public delegate void OnNetworkReceive(NetPeer peer, NetDataReader reader); + public delegate void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType); + public delegate void OnNetworkLatencyUpdate(NetPeer peer, int latency); + + public event OnPeerConnected PeerConnectedEvent; + public event OnPeerDisconnected PeerDisconnectedEvent; + public event OnNetworkError NetworkErrorEvent; + public event OnNetworkReceive NetworkReceiveEvent; + public event OnNetworkReceiveUnconnected NetworkReceiveUnconnectedEvent; + public event OnNetworkLatencyUpdate NetworkLatencyUpdateEvent; + + void INetEventListener.OnPeerConnected(NetPeer peer) + { + if (PeerConnectedEvent != null) + PeerConnectedEvent(peer); + } + + void INetEventListener.OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) + { + if (PeerDisconnectedEvent != null) + PeerDisconnectedEvent(peer, disconnectInfo); + } + + void INetEventListener.OnNetworkError(NetEndPoint endPoint, int socketErrorCode) + { + if (NetworkErrorEvent != null) + NetworkErrorEvent(endPoint, socketErrorCode); + } + + void INetEventListener.OnNetworkReceive(NetPeer peer, NetDataReader reader) + { + if (NetworkReceiveEvent != null) + NetworkReceiveEvent(peer, reader); + } + + void INetEventListener.OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType) + { + if (NetworkReceiveUnconnectedEvent != null) + NetworkReceiveUnconnectedEvent(remoteEndPoint, reader, messageType); + } + + void INetEventListener.OnNetworkLatencyUpdate(NetPeer peer, int latency) + { + if (NetworkLatencyUpdateEvent != null) + NetworkLatencyUpdateEvent(peer, latency); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs.meta new file mode 100644 index 0000000..0214848 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/INetEventListener.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d391f9565d58e44a798d680ec5c11906 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs new file mode 100644 index 0000000..675ff3a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs @@ -0,0 +1,231 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Collections.Generic; +using FlyingWormConsole3.LiteNetLib.Utils; + +//Some code parts taked from lidgren-network-gen3 + +namespace FlyingWormConsole3.LiteNetLib +{ + public interface INatPunchListener + { + void OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token); + void OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token); + } + + public class EventBasedNatPunchListener : INatPunchListener + { + public delegate void OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token); + public delegate void OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token); + + public event OnNatIntroductionRequest NatIntroductionRequest; + public event OnNatIntroductionSuccess NatIntroductionSuccess; + + void INatPunchListener.OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token) + { + if(NatIntroductionRequest != null) + NatIntroductionRequest(localEndPoint, remoteEndPoint, token); + } + + void INatPunchListener.OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token) + { + if (NatIntroductionSuccess != null) + NatIntroductionSuccess(targetEndPoint, token); + } + } + + public sealed class NatPunchModule + { + struct RequestEventData + { + public NetEndPoint LocalEndPoint; + public NetEndPoint RemoteEndPoint; + public string Token; + } + + struct SuccessEventData + { + public NetEndPoint TargetEndPoint; + public string Token; + } + + private readonly NetManager _netBase; + private readonly Queue _requestEvents; + private readonly Queue _successEvents; + private const byte HostByte = 1; + private const byte ClientByte = 0; + public const int MaxTokenLength = 256; + + private INatPunchListener _natPunchListener; + + internal NatPunchModule(NetManager netBase) + { + _netBase = netBase; + _requestEvents = new Queue(); + _successEvents = new Queue(); + } + + public void Init(INatPunchListener listener) + { + _natPunchListener = listener; + } + + public void NatIntroduce( + NetEndPoint hostInternal, + NetEndPoint hostExternal, + NetEndPoint clientInternal, + NetEndPoint clientExternal, + string additionalInfo) + { + NetDataWriter dw = new NetDataWriter(); + + //First packet (server) + //send to client + dw.Put(ClientByte); + dw.Put(hostInternal); + dw.Put(hostExternal); + dw.Put(additionalInfo, MaxTokenLength); + + var packet = _netBase.PacketPool.GetWithData(PacketProperty.NatIntroduction, dw); + _netBase.SendRawAndRecycle(packet, clientExternal); + + //Second packet (client) + //send to server + dw.Reset(); + dw.Put(HostByte); + dw.Put(clientInternal); + dw.Put(clientExternal); + dw.Put(additionalInfo, MaxTokenLength); + + packet = _netBase.PacketPool.GetWithData(PacketProperty.NatIntroduction, dw); + _netBase.SendRawAndRecycle(packet, hostExternal); + } + + public void PollEvents() + { + if (_natPunchListener == null) + return; + lock (_successEvents) + { + while (_successEvents.Count > 0) + { + var evt = _successEvents.Dequeue(); + _natPunchListener.OnNatIntroductionSuccess(evt.TargetEndPoint, evt.Token); + } + } + lock (_requestEvents) + { + while (_requestEvents.Count > 0) + { + var evt = _requestEvents.Dequeue(); + _natPunchListener.OnNatIntroductionRequest(evt.LocalEndPoint, evt.RemoteEndPoint, evt.Token); + } + } + } + + public void SendNatIntroduceRequest(NetEndPoint masterServerEndPoint, string additionalInfo) + { + if (!_netBase.IsRunning) + return; + + //prepare outgoing data + NetDataWriter dw = new NetDataWriter(); + string networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv4); + if (string.IsNullOrEmpty(networkIp)) + { + networkIp = NetUtils.GetLocalIp(LocalAddrType.IPv6); + } + int networkPort = _netBase.LocalEndPoint.Port; + NetEndPoint localEndPoint = new NetEndPoint(networkIp, networkPort); + dw.Put(localEndPoint); + dw.Put(additionalInfo, MaxTokenLength); + + //prepare packet + var packet = _netBase.PacketPool.GetWithData(PacketProperty.NatIntroductionRequest, dw); + _netBase.SendRawAndRecycle(packet, masterServerEndPoint); + } + + private void HandleNatPunch(NetEndPoint senderEndPoint, NetDataReader dr) + { + byte fromHostByte = dr.GetByte(); + if (fromHostByte != HostByte && fromHostByte != ClientByte) + { + //garbage + return; + } + + //Read info + string additionalInfo = dr.GetString(MaxTokenLength); + NetUtils.DebugWrite(ConsoleColor.Green, "[NAT] punch received from {0} - additional info: {1}", senderEndPoint, additionalInfo); + + //Release punch success to client; enabling him to Connect() to msg.Sender if token is ok + lock (_successEvents) + { + _successEvents.Enqueue(new SuccessEventData { TargetEndPoint = senderEndPoint, Token = additionalInfo }); + } + } + + private void HandleNatIntroduction(NetDataReader dr) + { + // read intro + byte hostByte = dr.GetByte(); + NetEndPoint remoteInternal = dr.GetNetEndPoint(); + NetEndPoint remoteExternal = dr.GetNetEndPoint(); + string token = dr.GetString(MaxTokenLength); + + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] introduction received; we are designated " + (hostByte == HostByte ? "host" : "client")); + NetDataWriter writer = new NetDataWriter(); + + // send internal punch + writer.Put(hostByte); + writer.Put(token); + var packet = _netBase.PacketPool.GetWithData(PacketProperty.NatPunchMessage, writer); + _netBase.SendRawAndRecycle(packet, remoteInternal); + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] internal punch sent to " + remoteInternal); + + // send external punch + writer.Reset(); + writer.Put(hostByte); + writer.Put(token); + packet = _netBase.PacketPool.GetWithData(PacketProperty.NatPunchMessage, writer); + _netBase.SendRawAndRecycle(packet, remoteExternal); + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] external punch sent to " + remoteExternal); + } + + private void HandleNatIntroductionRequest(NetEndPoint senderEndPoint, NetDataReader dr) + { + NetEndPoint localEp = dr.GetNetEndPoint(); + string token = dr.GetString(MaxTokenLength); + lock (_requestEvents) + { + _requestEvents.Enqueue(new RequestEventData + { + LocalEndPoint = localEp, + RemoteEndPoint = senderEndPoint, + Token = token + }); + } + } + + internal void ProcessMessage(NetEndPoint senderEndPoint, NetPacket packet) + { + var dr = new NetDataReader(packet.RawData, NetConstants.HeaderSize, packet.Size); + switch (packet.Property) + { + case PacketProperty.NatIntroductionRequest: + //We got request and must introduce + HandleNatIntroductionRequest(senderEndPoint, dr); + break; + case PacketProperty.NatIntroduction: + //We got introduce and must punch + HandleNatIntroduction(dr); + break; + case PacketProperty.NatPunchMessage: + //We got punch and can connect + HandleNatPunch(senderEndPoint, dr); + break; + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs.meta new file mode 100644 index 0000000..ba586cc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NatPunchModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 11f3508667cc14e3797a49d4695ffdd8 +timeCreated: 1497976517 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs new file mode 100644 index 0000000..e030cc1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs @@ -0,0 +1,53 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +namespace FlyingWormConsole3.LiteNetLib +{ + public enum SendOptions + { + Unreliable, + ReliableUnordered, + Sequenced, + ReliableOrdered + } + + public static class NetConstants + { + public const int HeaderSize = 1; + public const int SequencedHeaderSize = 3; + public const int FragmentHeaderSize = 6; + public const int DefaultWindowSize = 64; + public const ushort MaxSequence = 32768; + public const ushort HalfMaxSequence = MaxSequence / 2; + + //socket + public const string MulticastGroupIPv4 = "224.0.0.1"; + public const string MulticastGroupIPv6 = "FF02:0:0:0:0:0:0:1"; + public const int SocketBufferSize = 1024*1024; //2mb + public const int SocketTTL = 255; + + //protocol + public const int ProtocolId = 1; + public const int MaxUdpHeaderSize = 68; + public const int PacketSizeLimit = ushort.MaxValue - MaxUdpHeaderSize; + public const int MinPacketSize = 576 - MaxUdpHeaderSize; + public const int MinPacketDataSize = MinPacketSize - HeaderSize; + public const int MinSequencedPacketDataSize = MinPacketSize - SequencedHeaderSize; + + public static readonly int[] PossibleMtu = + { + 576 - MaxUdpHeaderSize, //Internet Path MTU for X.25 (RFC 879) + 1492 - MaxUdpHeaderSize, //Ethernet with LLC and SNAP, PPPoE (RFC 1042) + 1500 - MaxUdpHeaderSize, //Ethernet II (RFC 1191) + 4352 - MaxUdpHeaderSize, //FDDI + 4464 - MaxUdpHeaderSize, //Token ring + 7981 - MaxUdpHeaderSize //WLAN + }; + + public static int MaxPacketSize = PossibleMtu[PossibleMtu.Length - 1]; + + //peer specific + public const int FlowUpdateTime = 1000; + public const int FlowIncreaseThreshold = 4; + public const int DefaultPingInterval = 1000; + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs.meta new file mode 100644 index 0000000..b32e617 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetConstants.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 02abb4740bff94f28bdd538839339932 +timeCreated: 1497976517 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs new file mode 100644 index 0000000..7e6ec5a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs @@ -0,0 +1,444 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Text; + +namespace FlyingWormConsole3.LiteNetLib.Utils +{ + public class NetDataReader + { + protected byte[] _data; + protected int _position; + protected int _dataSize; + + public byte[] Data + { + get { return _data; } + } + + public int Position + { + get { return _position; } + } + + public bool EndOfData + { + get { return _position == _dataSize; } + } + + public int AvailableBytes + { + get { return _dataSize - _position; } + } + + public void SetSource(NetDataWriter dataWriter) + { + _data = dataWriter.Data; + _position = 0; + _dataSize = dataWriter.Length; + } + + public void SetSource(byte[] source) + { + _data = source; + _position = 0; + _dataSize = source.Length; + } + + public void SetSource(byte[] source, int offset) + { + _data = source; + _position = offset; + _dataSize = source.Length; + } + + public void SetSource(byte[] source, int offset, int dataSize) + { + _data = source; + _position = offset; + _dataSize = dataSize; + } + + public NetDataReader() + { + + } + + public NetDataReader(byte[] source) + { + SetSource(source); + } + + public NetDataReader(byte[] source, int offset) + { + SetSource(source, offset); + } + + public NetDataReader(byte[] source, int offset, int maxSize) + { + SetSource(source, offset, maxSize); + } + + #region GetMethods + public NetEndPoint GetNetEndPoint() + { + string host = GetString(1000); + int port = GetInt(); + return new NetEndPoint(host, port); + } + + public byte GetByte() + { + byte res = _data[_position]; + _position += 1; + return res; + } + + public sbyte GetSByte() + { + var b = (sbyte)_data[_position]; + _position++; + return b; + } + + public bool[] GetBoolArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new bool[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetBool(); + } + return arr; + } + + public ushort[] GetUShortArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new ushort[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetUShort(); + } + return arr; + } + + public short[] GetShortArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new short[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetShort(); + } + return arr; + } + + public long[] GetLongArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new long[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetLong(); + } + return arr; + } + + public ulong[] GetULongArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new ulong[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetULong(); + } + return arr; + } + + public int[] GetIntArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new int[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetInt(); + } + return arr; + } + + public uint[] GetUIntArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new uint[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetUInt(); + } + return arr; + } + + public float[] GetFloatArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new float[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetFloat(); + } + return arr; + } + + public double[] GetDoubleArray() + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new double[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetDouble(); + } + return arr; + } + + public string[] GetStringArray(int maxLength) + { + ushort size = BitConverter.ToUInt16(_data, _position); + _position += 2; + var arr = new string[size]; + for (int i = 0; i < size; i++) + { + arr[i] = GetString(maxLength); + } + return arr; + } + + public bool GetBool() + { + bool res = _data[_position] > 0; + _position += 1; + return res; + } + + public ushort GetUShort() + { + ushort result = BitConverter.ToUInt16(_data, _position); + _position += 2; + return result; + } + + public short GetShort() + { + short result = BitConverter.ToInt16(_data, _position); + _position += 2; + return result; + } + + public long GetLong() + { + long result = BitConverter.ToInt64(_data, _position); + _position += 8; + return result; + } + + public ulong GetULong() + { + ulong result = BitConverter.ToUInt64(_data, _position); + _position += 8; + return result; + } + + public int GetInt() + { + int result = BitConverter.ToInt32(_data, _position); + _position += 4; + return result; + } + + public uint GetUInt() + { + uint result = BitConverter.ToUInt32(_data, _position); + _position += 4; + return result; + } + + public float GetFloat() + { + float result = BitConverter.ToSingle(_data, _position); + _position += 4; + return result; + } + + public double GetDouble() + { + double result = BitConverter.ToDouble(_data, _position); + _position += 8; + return result; + } + + public string GetString(int maxLength) + { + int bytesCount = GetInt(); + if (bytesCount <= 0 || bytesCount > maxLength*2) + { + return string.Empty; + } + + int charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount); + if (charCount > maxLength) + { + return string.Empty; + } + + string result = Encoding.UTF8.GetString(_data, _position, bytesCount); + _position += bytesCount; + return result; + } + + public string GetString() + { + int bytesCount = GetInt(); + if (bytesCount <= 0) + { + return string.Empty; + } + + string result = Encoding.UTF8.GetString(_data, _position, bytesCount); + _position += bytesCount; + return result; + } + + public byte[] GetRemainingBytes() + { + byte[] outgoingData = new byte[AvailableBytes]; + Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes); + _position = _data.Length; + return outgoingData; + } + + public void GetRemainingBytes(byte[] destination) + { + Buffer.BlockCopy(_data, _position, destination, 0, AvailableBytes); + _position = _data.Length; + } + + public void GetBytes(byte[] destination, int lenght) + { + Buffer.BlockCopy(_data, _position, destination, 0, lenght); + _position += lenght; + } + + public byte[] GetBytesWithLength() + { + int length = GetInt(); + byte[] outgoingData = new byte[length]; + Buffer.BlockCopy(_data, _position, outgoingData, 0, length); + _position += length; + return outgoingData; + } + #endregion + + #region PeekMethods + + public byte PeekByte() + { + return _data[_position]; + } + + public sbyte PeekSByte() + { + return (sbyte)_data[_position]; + } + + public bool PeekBool() + { + return _data[_position] > 0; + } + + public ushort PeekUShort() + { + return BitConverter.ToUInt16(_data, _position); + } + + public short PeekShort() + { + return BitConverter.ToInt16(_data, _position); + } + + public long PeekLong() + { + return BitConverter.ToInt64(_data, _position); + } + + public ulong PeekULong() + { + return BitConverter.ToUInt64(_data, _position); + } + + public int PeekInt() + { + return BitConverter.ToInt32(_data, _position); + } + + public uint PeekUInt() + { + return BitConverter.ToUInt32(_data, _position); + } + + public float PeekFloat() + { + return BitConverter.ToSingle(_data, _position); + } + + public double PeekDouble() + { + return BitConverter.ToDouble(_data, _position); + } + + public string PeekString(int maxLength) + { + int bytesCount = BitConverter.ToInt32(_data, _position); + if (bytesCount <= 0 || bytesCount > maxLength * 2) + { + return string.Empty; + } + + int charCount = Encoding.UTF8.GetCharCount(_data, _position + 4, bytesCount); + if (charCount > maxLength) + { + return string.Empty; + } + + string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); + return result; + } + + public string PeekString() + { + int bytesCount = BitConverter.ToInt32(_data, _position); + if (bytesCount <= 0) + { + return string.Empty; + } + + string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); + return result; + } + #endregion + + public void Clear() + { + _position = 0; + _dataSize = 0; + _data = null; + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs.meta new file mode 100644 index 0000000..108202d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataReader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 37bb0204fc22b499690c4032caf14811 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs new file mode 100644 index 0000000..451bc54 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs @@ -0,0 +1,375 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Text; + +namespace FlyingWormConsole3.LiteNetLib.Utils +{ + public class NetDataWriter + { + protected byte[] _data; + protected int _position; + + private int _maxLength; + private readonly bool _autoResize; + + public NetDataWriter() + { + _maxLength = 64; + _data = new byte[_maxLength]; + _autoResize = true; + } + + public NetDataWriter(bool autoResize) + { + _maxLength = 64; + _data = new byte[_maxLength]; + _autoResize = autoResize; + } + + public NetDataWriter(bool autoResize, int initialSize) + { + _maxLength = initialSize; + _data = new byte[_maxLength]; + _autoResize = autoResize; + } + + public void ResizeIfNeed(int newSize) + { + if (_maxLength < newSize) + { + while (_maxLength < newSize) + { + _maxLength *= 2; + } + Array.Resize(ref _data, _maxLength); + } + } + + public void Reset(int size) + { + ResizeIfNeed(size); + _position = 0; + } + + public void Reset() + { + _position = 0; + } + + public byte[] CopyData() + { + byte[] resultData = new byte[_position]; + Buffer.BlockCopy(_data, 0, resultData, 0, _position); + return resultData; + } + + public byte[] Data + { + get { return _data; } + } + + public int Length + { + get { return _position; } + } + + public void Put(float value) + { + if (_autoResize) + ResizeIfNeed(_position + 4); + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } + + public void Put(double value) + { + if (_autoResize) + ResizeIfNeed(_position + 8); + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } + + public void Put(long value) + { + if (_autoResize) + ResizeIfNeed(_position + 8); + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } + + public void Put(ulong value) + { + if (_autoResize) + ResizeIfNeed(_position + 8); + FastBitConverter.GetBytes(_data, _position, value); + _position += 8; + } + + public void Put(int value) + { + if (_autoResize) + ResizeIfNeed(_position + 4); + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } + + public void Put(uint value) + { + if (_autoResize) + ResizeIfNeed(_position + 4); + FastBitConverter.GetBytes(_data, _position, value); + _position += 4; + } + + public void Put(ushort value) + { + if (_autoResize) + ResizeIfNeed(_position + 2); + FastBitConverter.GetBytes(_data, _position, value); + _position += 2; + } + + public void Put(short value) + { + if (_autoResize) + ResizeIfNeed(_position + 2); + FastBitConverter.GetBytes(_data, _position, value); + _position += 2; + } + + public void Put(sbyte value) + { + if (_autoResize) + ResizeIfNeed(_position + 1); + _data[_position] = (byte)value; + _position++; + } + + public void Put(byte value) + { + if (_autoResize) + ResizeIfNeed(_position + 1); + _data[_position] = value; + _position++; + } + + public void Put(byte[] data, int offset, int length) + { + if (_autoResize) + ResizeIfNeed(_position + length); + Buffer.BlockCopy(data, offset, _data, _position, length); + _position += length; + } + + public void Put(byte[] data) + { + if (_autoResize) + ResizeIfNeed(_position + data.Length); + Buffer.BlockCopy(data, 0, _data, _position, data.Length); + _position += data.Length; + } + + public void PutBytesWithLength(byte[] data, int offset, int length) + { + if (_autoResize) + ResizeIfNeed(_position + length); + Put(length); + Buffer.BlockCopy(data, offset, _data, _position, length); + _position += length; + } + + public void PutBytesWithLength(byte[] data) + { + if (_autoResize) + ResizeIfNeed(_position + data.Length); + Put(data.Length); + Buffer.BlockCopy(data, 0, _data, _position, data.Length); + _position += data.Length; + } + + public void Put(bool value) + { + if (_autoResize) + ResizeIfNeed(_position + 1); + _data[_position] = (byte)(value ? 1 : 0); + _position++; + } + + public void PutArray(float[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 4 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(double[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 8 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(long[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 8 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(ulong[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 8 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(int[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 4 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(uint[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 4 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(ushort[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 2 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(short[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len * 2 + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(bool[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + if (_autoResize) + ResizeIfNeed(_position + len + 2); + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i]); + } + } + + public void PutArray(string[] value) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + Put(len); + for (int i = 0; i < value.Length; i++) + { + Put(value[i]); + } + } + + public void PutArray(string[] value, int maxLength) + { + ushort len = value == null ? (ushort)0 : (ushort)value.Length; + Put(len); + for (int i = 0; i < len; i++) + { + Put(value[i], maxLength); + } + } + + public void Put(NetEndPoint endPoint) + { + Put(endPoint.Host); + Put(endPoint.Port); + } + + public void Put(string value) + { + if (string.IsNullOrEmpty(value)) + { + Put(0); + return; + } + + //put bytes count + int bytesCount = Encoding.UTF8.GetByteCount(value); + if (_autoResize) + ResizeIfNeed(_position + bytesCount + 4); + Put(bytesCount); + + //put string + Encoding.UTF8.GetBytes(value, 0, value.Length, _data, _position); + _position += bytesCount; + } + + public void Put(string value, int maxLength) + { + if (string.IsNullOrEmpty(value)) + { + Put(0); + return; + } + + int length = value.Length > maxLength ? maxLength : value.Length; + //calculate max count + int bytesCount = Encoding.UTF8.GetByteCount(value); + if (_autoResize) + ResizeIfNeed(_position + bytesCount + 4); + + //put bytes count + Put(bytesCount); + + //put string + Encoding.UTF8.GetBytes(value, 0, length, _data, _position); + + _position += bytesCount; + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs.meta new file mode 100644 index 0000000..82fb095 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDataWriter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 81ecf42c9cc394fc395942030e71bddd +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs new file mode 100644 index 0000000..7a8b4a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs @@ -0,0 +1,16 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; + +namespace FlyingWormConsole3.LiteNetLib +{ + public interface INetLogger + { + void WriteNet(ConsoleColor color, string str, params object[] args); + } + + public static class NetDebug + { + public static INetLogger Logger = null; + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs.meta new file mode 100644 index 0000000..5328f0b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetDebug.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 78dc00ceb66ac4fdfa8c3957763522ba +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs new file mode 100644 index 0000000..9ef9ed7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs @@ -0,0 +1,221 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +#if !WINRT || UNITY_EDITOR +using System; +using System.Net; +using System.Net.Sockets; + +namespace FlyingWormConsole3.LiteNetLib +{ + public sealed class NetEndPoint + { + public string Host { get { return EndPoint.Address.ToString(); } } + public int Port { get { return EndPoint.Port; } } + + internal readonly IPEndPoint EndPoint; + + internal NetEndPoint(IPEndPoint ipEndPoint) + { + EndPoint = ipEndPoint; + } + + public override bool Equals(object obj) + { + if (!(obj is NetEndPoint)) + { + return false; + } + return EndPoint.Equals(((NetEndPoint)obj).EndPoint); + } + + public override string ToString() + { + return EndPoint.ToString(); + } + + public override int GetHashCode() + { + return EndPoint.GetHashCode(); + } + + public NetEndPoint(string hostStr, int port) + { + IPAddress ipAddress; + if (!IPAddress.TryParse(hostStr, out ipAddress)) + { + if (Socket.OSSupportsIPv6) + { + if (hostStr == "localhost") + { + ipAddress = IPAddress.IPv6Loopback; + } + else + { + ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetworkV6); + } + } + if (ipAddress == null) + { + ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetwork); + } + } + if (ipAddress == null) + { + throw new Exception("Invalid address: " + hostStr); + } + EndPoint = new IPEndPoint(ipAddress, port); + } + + private IPAddress ResolveAddress(string hostStr, AddressFamily addressFamily) + { +#if NETCORE + var hostTask = Dns.GetHostEntryAsync(hostStr); + hostTask.Wait(); + var host = hostTask.Result; +#else + var host = Dns.GetHostEntry(hostStr); +#endif + foreach (IPAddress ip in host.AddressList) + { + if (ip.AddressFamily == addressFamily) + { + return ip; + } + } + return null; + } + + internal long GetId() + { + byte[] addr = EndPoint.Address.GetAddressBytes(); + long id = 0; + + if (addr.Length == 4) //IPv4 + { + id = addr[0]; + id |= (long)addr[1] << 8; + id |= (long)addr[2] << 16; + id |= (long)addr[3] << 24; + id |= (long)EndPoint.Port << 32; + } + else if (addr.Length == 16) //IPv6 + { + id = addr[0] ^ addr[8]; + id |= (long)(addr[1] ^ addr[9]) << 8; + id |= (long)(addr[2] ^ addr[10]) << 16; + + + id |= (long)(addr[3] ^ addr[11]) << 24; + id |= (long)(addr[4] ^ addr[12]) << 32; + id |= (long)(addr[5] ^ addr[13]) << 40; + id |= (long)(addr[6] ^ addr[14]) << 48; + id |= (long)(Port ^ addr[7] ^ addr[15]) << 56; + } + + return id; + } + } +} +#else +using System; +using Windows.Networking; +using Windows.Networking.Sockets; + +namespace FlyingWormConsole3.LiteNetLib +{ + public sealed class NetEndPoint + { + public string Host { get { return HostName.DisplayName; } } + public int Port { get; private set; } + internal readonly HostName HostName; + internal readonly string PortStr; + + internal NetEndPoint(int port) + { + HostName = null; + PortStr = port.ToString(); + Port = port; + } + + public override bool Equals(object obj) + { + if (!(obj is NetEndPoint)) + { + return false; + } + NetEndPoint other = (NetEndPoint) obj; + return HostName.IsEqual(other.HostName) && PortStr.Equals(other.PortStr); + } + + public override int GetHashCode() + { + return HostName.CanonicalName.GetHashCode() ^ PortStr.GetHashCode(); + } + + internal long GetId() + { + //Check locals + if (HostName == null) + { + return ParseIpToId("0.0.0.0"); + } + + if (HostName.DisplayName == "localhost") + { + return ParseIpToId("127.0.0.1"); + } + + //Check remote + string hostIp = string.Empty; + var task = DatagramSocket.GetEndpointPairsAsync(HostName, "0").AsTask(); + task.Wait(); + + //IPv4 + foreach (var endpointPair in task.Result) + { + hostIp = endpointPair.RemoteHostName.CanonicalName; + if (endpointPair.RemoteHostName.Type == HostNameType.Ipv4) + { + return ParseIpToId(hostIp); + } + } + + //Else + return hostIp.GetHashCode() ^ Port; + } + + private long ParseIpToId(string hostIp) + { + long id = 0; + string[] ip = hostIp.Split('.'); + id |= long.Parse(ip[0]); + id |= long.Parse(ip[1]) << 8; + id |= long.Parse(ip[2]) << 16; + id |= long.Parse(ip[3]) << 24; + id |= (long)Port << 32; + return id; + } + + public override string ToString() + { + return HostName.CanonicalName + ":" + PortStr; + } + + public NetEndPoint(string hostName, int port) + { + var task = DatagramSocket.GetEndpointPairsAsync(new HostName(hostName), port.ToString()).AsTask(); + task.Wait(); + HostName = task.Result[0].RemoteHostName; + Port = port; + PortStr = port.ToString(); + } + + internal NetEndPoint(HostName hostName, string port) + { + HostName = hostName; + Port = int.Parse(port); + PortStr = port; + } + } +} +#endif +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs.meta new file mode 100644 index 0000000..93ef448 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetEndPoint.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 33fb66c3ba5b8429fbbb0a2f5e7ceb57 +timeCreated: 1497976517 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs new file mode 100644 index 0000000..75745f7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs @@ -0,0 +1,1039 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +#if DEBUG +#define STATS_ENABLED +#endif + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using FlyingWormConsole3.LiteNetLib.Utils; + +namespace FlyingWormConsole3.LiteNetLib +{ + public sealed class NetManager + { + internal delegate void OnMessageReceived(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint); + + private struct FlowMode + { + public int PacketsPerSecond; + public int StartRtt; + } + + private enum NetEventType + { + Connect, + Disconnect, + Receive, + ReceiveUnconnected, + Error, + ConnectionLatencyUpdated, + DiscoveryRequest, + DiscoveryResponse + } + + private sealed class NetEvent + { + public NetPeer Peer; + public readonly NetDataReader DataReader = new NetDataReader(); + public NetEventType Type; + public NetEndPoint RemoteEndPoint; + public int AdditionalData; + public DisconnectReason DisconnectReason; + } + +#if DEBUG + private struct IncomingData + { + public byte[] Data; + public NetEndPoint EndPoint; + public DateTime TimeWhenGet; + } + private readonly List _pingSimulationList = new List(); + private readonly Random _randomGenerator = new Random(); + private const int MinLatencyTreshold = 5; +#endif + + private readonly NetSocket _socket; + private readonly List _flowModes; + + private readonly NetThread _logicThread; + + private readonly Queue _netEventsQueue; + private readonly Stack _netEventsPool; + private readonly INetEventListener _netEventListener; + + private readonly NetPeerCollection _peers; + private readonly int _maxConnections; + private readonly string _connectKey; + + private readonly NetPacketPool _netPacketPool; + + //config section + public bool UnconnectedMessagesEnabled = false; + public bool NatPunchEnabled = false; + public int UpdateTime { get { return _logicThread.SleepTime; } set { _logicThread.SleepTime = value; } } + public int PingInterval = NetConstants.DefaultPingInterval; + public long DisconnectTimeout = 5000; + public bool SimulatePacketLoss = false; + public bool SimulateLatency = false; + public int SimulationPacketLossChance = 10; + public int SimulationMinLatency = 30; + public int SimulationMaxLatency = 100; + public bool UnsyncedEvents = false; + public bool DiscoveryEnabled = false; + public bool MergeEnabled = false; + public int ReconnectDelay = 500; + public int MaxConnectAttempts = 10; + public bool ReuseAddress = false; + + private const int DefaultUpdateTime = 15; + + //stats + public ulong PacketsSent { get; private set; } + public ulong PacketsReceived { get; private set; } + public ulong BytesSent { get; private set; } + public ulong BytesReceived { get; private set; } + + //modules + public readonly NatPunchModule NatPunchModule; + + /// + /// Returns true if socket listening and update thread is running + /// + public bool IsRunning + { + get { return _logicThread.IsRunning; } + } + + /// + /// Local EndPoint (host and port) + /// + public NetEndPoint LocalEndPoint + { + get { return _socket.LocalEndPoint; } + } + + /// + /// Connected peers count + /// + public int PeersCount + { + get { return _peers.Count; } + } + + public string ConnectKey + { + get { return _connectKey; } + } + + //Flow + public void AddFlowMode(int startRtt, int packetsPerSecond) + { + var fm = new FlowMode {PacketsPerSecond = packetsPerSecond, StartRtt = startRtt}; + + if (_flowModes.Count > 0 && startRtt < _flowModes[0].StartRtt) + { + _flowModes.Insert(0, fm); + } + else + { + _flowModes.Add(fm); + } + } + + internal int GetPacketsPerSecond(int flowMode) + { + if (flowMode < 0 || _flowModes.Count == 0) + return 0; + return _flowModes[flowMode].PacketsPerSecond; + } + + internal int GetMaxFlowMode() + { + return _flowModes.Count - 1; + } + + internal int GetStartRtt(int flowMode) + { + if (flowMode < 0 || _flowModes.Count == 0) + return 0; + return _flowModes[flowMode].StartRtt; + } + + internal NetPacketPool PacketPool + { + get { return _netPacketPool; } + } + + /// + /// NetManager constructor with maxConnections = 1 (usable for client) + /// + /// Network events listener + /// Application key (must be same with remote host for establish connection) + public NetManager(INetEventListener listener, string connectKey) : this(listener, 1, connectKey) + { + + } + + /// + /// NetManager constructor + /// + /// Network events listener + /// Maximum connections (incoming and outcoming) + /// Application key (must be same with remote host for establish connection) + public NetManager(INetEventListener listener, int maxConnections, string connectKey) + { + _logicThread = new NetThread("LogicThread", DefaultUpdateTime, UpdateLogic); + _socket = new NetSocket(ReceiveLogic); + _netEventListener = listener; + _flowModes = new List(); + _netEventsQueue = new Queue(); + _netEventsPool = new Stack(); + _netPacketPool = new NetPacketPool(); + NatPunchModule = new NatPunchModule(this); + + _connectKey = connectKey; + _peers = new NetPeerCollection(maxConnections); + _maxConnections = maxConnections; + _connectKey = connectKey; + } + + internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency) + { + var evt = CreateEvent(NetEventType.ConnectionLatencyUpdated); + evt.Peer = fromPeer; + evt.AdditionalData = latency; + EnqueueEvent(evt); + } + + internal bool SendRawAndRecycle(NetPacket packet, NetEndPoint remoteEndPoint) + { + var result = SendRaw(packet.RawData, 0, packet.Size, remoteEndPoint); + _netPacketPool.Recycle(packet); + return result; + } + + internal bool SendRaw(byte[] message, int start, int length, NetEndPoint remoteEndPoint) + { + if (!IsRunning) + return false; + + int errorCode = 0; + bool result = _socket.SendTo(message, start, length, remoteEndPoint, ref errorCode) > 0; + + //10040 message to long... need to check + //10065 no route to host + if (errorCode != 0 && errorCode != 10040 && errorCode != 10065) + { + //Send error + NetPeer fromPeer; + if (_peers.TryGetValue(remoteEndPoint, out fromPeer)) + { + DisconnectPeer(fromPeer, DisconnectReason.SocketSendError, errorCode, false, null, 0, 0); + } + var netEvent = CreateEvent(NetEventType.Error); + netEvent.RemoteEndPoint = remoteEndPoint; + netEvent.AdditionalData = errorCode; + EnqueueEvent(netEvent); + return false; + } + if (errorCode == 10040) + { + NetUtils.DebugWrite(ConsoleColor.Red, "[SRD] 10040, datalen: {0}", length); + return false; + } +#if STATS_ENABLED + PacketsSent++; + BytesSent += (uint)length; +#endif + + return result; + } + + private void DisconnectPeer( + NetPeer peer, + DisconnectReason reason, + int socketErrorCode, + bool sendDisconnectPacket, + byte[] data, + int start, + int count) + { + if (sendDisconnectPacket) + { + if (count + 8 >= peer.Mtu) + { + //Drop additional data + data = null; + count = 0; + NetUtils.DebugWriteError("[NM] Disconnect additional data size more than MTU - 8!"); + } + + var disconnectPacket = _netPacketPool.Get(PacketProperty.Disconnect, 8 + count); + FastBitConverter.GetBytes(disconnectPacket.RawData, 1, peer.ConnectId); + if (data != null) + { + Buffer.BlockCopy(data, start, disconnectPacket.RawData, 9, count); + } + SendRawAndRecycle(disconnectPacket, peer.EndPoint); + } + var netEvent = CreateEvent(NetEventType.Disconnect); + netEvent.Peer = peer; + netEvent.AdditionalData = socketErrorCode; + netEvent.DisconnectReason = reason; + EnqueueEvent(netEvent); + RemovePeer(peer.EndPoint); + } + + private void ClearPeers() + { + lock (_peers) + { +#if WINRT && !UNITY_EDITOR + _socket.ClearPeers(); +#endif + _peers.Clear(); + } + } + + private void RemovePeer(NetEndPoint endPoint) + { + _peers.Remove(endPoint); +#if WINRT && !UNITY_EDITOR + _socket.RemovePeer(endPoint); +#endif + } + + private void RemovePeerAt(int idx) + { +#if WINRT && !UNITY_EDITOR + var endPoint = _peers[idx].EndPoint; + _socket.RemovePeer(endPoint); +#endif + _peers.RemoveAt(idx); + } + + private NetEvent CreateEvent(NetEventType type) + { + NetEvent evt = null; + + lock (_netEventsPool) + { + if (_netEventsPool.Count > 0) + { + evt = _netEventsPool.Pop(); + } + } + if(evt == null) + { + evt = new NetEvent(); + } + evt.Type = type; + return evt; + } + + private void EnqueueEvent(NetEvent evt) + { + if (UnsyncedEvents) + { + ProcessEvent(evt); + } + else + { + lock (_netEventsQueue) + { + _netEventsQueue.Enqueue(evt); + } + } + } + + private void ProcessEvent(NetEvent evt) + { + switch (evt.Type) + { + case NetEventType.Connect: + _netEventListener.OnPeerConnected(evt.Peer); + break; + case NetEventType.Disconnect: + var info = new DisconnectInfo + { + Reason = evt.DisconnectReason, + AdditionalData = evt.DataReader, + SocketErrorCode = evt.AdditionalData + }; + _netEventListener.OnPeerDisconnected(evt.Peer, info); + break; + case NetEventType.Receive: + _netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader); + break; + case NetEventType.ReceiveUnconnected: + _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Default); + break; + case NetEventType.DiscoveryRequest: + _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryRequest); + break; + case NetEventType.DiscoveryResponse: + _netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryResponse); + break; + case NetEventType.Error: + _netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.AdditionalData); + break; + case NetEventType.ConnectionLatencyUpdated: + _netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.AdditionalData); + break; + } + + //Recycle + evt.DataReader.Clear(); + evt.Peer = null; + evt.AdditionalData = 0; + evt.RemoteEndPoint = null; + + lock (_netEventsPool) + { + _netEventsPool.Push(evt); + } + } + + //Update function + private void UpdateLogic() + { +#if DEBUG + if (SimulateLatency) + { + var time = DateTime.UtcNow; + lock (_pingSimulationList) + { + for (int i = 0; i < _pingSimulationList.Count; i++) + { + var incomingData = _pingSimulationList[i]; + if (incomingData.TimeWhenGet <= time) + { + DataReceived(incomingData.Data, incomingData.Data.Length, incomingData.EndPoint); + _pingSimulationList.RemoveAt(i); + i--; + } + } + } + } +#endif + + //Process acks + lock (_peers) + { + int delta = _logicThread.SleepTime; + for(int i = 0; i < _peers.Count; i++) + { + var netPeer = _peers[i]; + if (netPeer.ConnectionState == ConnectionState.Connected && netPeer.TimeSinceLastPacket > DisconnectTimeout) + { + NetUtils.DebugWrite("[NM] Disconnect by timeout: {0} > {1}", netPeer.TimeSinceLastPacket, DisconnectTimeout); + var netEvent = CreateEvent(NetEventType.Disconnect); + netEvent.Peer = netPeer; + netEvent.DisconnectReason = DisconnectReason.Timeout; + EnqueueEvent(netEvent); + + RemovePeerAt(i); + i--; + } + else if(netPeer.ConnectionState == ConnectionState.Disconnected) + { + var netEvent = CreateEvent(NetEventType.Disconnect); + netEvent.Peer = netPeer; + netEvent.DisconnectReason = DisconnectReason.ConnectionFailed; + EnqueueEvent(netEvent); + + RemovePeerAt(i); + i--; + } + else + { + netPeer.Update(delta); + } + } + } + } + + private void ReceiveLogic(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint) + { + //Receive some info + if (errorCode == 0) + { +#if DEBUG + bool receivePacket = true; + + if (SimulatePacketLoss && _randomGenerator.Next(100/SimulationPacketLossChance) == 0) + { + receivePacket = false; + } + else if (SimulateLatency) + { + int latency = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency); + if (latency > MinLatencyTreshold) + { + byte[] holdedData = new byte[length]; + Buffer.BlockCopy(data, 0, holdedData, 0, length); + + lock (_pingSimulationList) + { + _pingSimulationList.Add(new IncomingData + { + Data = holdedData, + EndPoint = remoteEndPoint, + TimeWhenGet = DateTime.UtcNow.AddMilliseconds(latency) + }); + } + + receivePacket = false; + } + } + + if (receivePacket) //DataReceived +#endif + //ProcessEvents + DataReceived(data, length, remoteEndPoint); + } + else //Error on receive + { + ClearPeers(); + var netEvent = CreateEvent(NetEventType.Error); + netEvent.AdditionalData = errorCode; + EnqueueEvent(netEvent); + } + } + + private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint) + { +#if STATS_ENABLED + PacketsReceived++; + BytesReceived += (uint) count; +#endif + + //Try read packet + NetPacket packet = _netPacketPool.GetAndRead(reusableBuffer, 0, count); + if (packet == null) + { + NetUtils.DebugWriteError("[NM] DataReceived: bad!"); + return; + } + + //Check unconnected + switch (packet.Property) + { + case PacketProperty.DiscoveryRequest: + if(DiscoveryEnabled) + { + var netEvent = CreateEvent(NetEventType.DiscoveryRequest); + netEvent.RemoteEndPoint = remoteEndPoint; + netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize); + EnqueueEvent(netEvent); + } + return; + case PacketProperty.DiscoveryResponse: + { + var netEvent = CreateEvent(NetEventType.DiscoveryResponse); + netEvent.RemoteEndPoint = remoteEndPoint; + netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize); + EnqueueEvent(netEvent); + } + return; + case PacketProperty.UnconnectedMessage: + if (UnconnectedMessagesEnabled) + { + var netEvent = CreateEvent(NetEventType.ReceiveUnconnected); + netEvent.RemoteEndPoint = remoteEndPoint; + netEvent.DataReader.SetSource(packet.RawData, NetConstants.HeaderSize); + EnqueueEvent(netEvent); + } + return; + case PacketProperty.NatIntroduction: + case PacketProperty.NatIntroductionRequest: + case PacketProperty.NatPunchMessage: + { + if (NatPunchEnabled) + NatPunchModule.ProcessMessage(remoteEndPoint, packet); + return; + } + } + + //Check normal packets + NetPeer netPeer; + + //Check peers + Monitor.Enter(_peers); + int peersCount = _peers.Count; + + if (_peers.TryGetValue(remoteEndPoint, out netPeer)) + { + Monitor.Exit(_peers); + //Send + if (packet.Property == PacketProperty.Disconnect) + { + if (BitConverter.ToInt64(packet.RawData, 1) != netPeer.ConnectId) + { + //Old or incorrect disconnect + _netPacketPool.Recycle(packet); + return; + } + + var netEvent = CreateEvent(NetEventType.Disconnect); + netEvent.Peer = netPeer; + netEvent.DataReader.SetSource(packet.RawData, 5, packet.Size - 5); + netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose; + EnqueueEvent(netEvent); + + _peers.Remove(netPeer.EndPoint); + //do not recycle because no sense) + } + else if (packet.Property == PacketProperty.ConnectAccept) + { + if (netPeer.ProcessConnectAccept(packet)) + { + var connectEvent = CreateEvent(NetEventType.Connect); + connectEvent.Peer = netPeer; + EnqueueEvent(connectEvent); + } + _netPacketPool.Recycle(packet); + } + else + { + netPeer.ProcessPacket(packet); + } + return; + } + + try + { + if (peersCount < _maxConnections && packet.Property == PacketProperty.ConnectRequest) + { + int protoId = BitConverter.ToInt32(packet.RawData, 1); + if (protoId != NetConstants.ProtocolId) + { + NetUtils.DebugWrite(ConsoleColor.Cyan, + "[NM] Peer connect reject. Invalid protocol ID: " + protoId); + return; + } + + string peerKey = Encoding.UTF8.GetString(packet.RawData, 13, packet.Size - 13); + if (peerKey != _connectKey) + { + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NM] Peer connect reject. Invalid key: " + peerKey); + return; + } + + //Getting new id for peer + long connectionId = BitConverter.ToInt64(packet.RawData, 5); + //response with id + netPeer = new NetPeer(this, remoteEndPoint, connectionId); + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NM] Received peer connect request Id: {0}, EP: {1}", + netPeer.ConnectId, remoteEndPoint); + + //clean incoming packet + _netPacketPool.Recycle(packet); + + _peers.Add(remoteEndPoint, netPeer); + + var netEvent = CreateEvent(NetEventType.Connect); + netEvent.Peer = netPeer; + EnqueueEvent(netEvent); + } + } + finally + { + Monitor.Exit(_peers); + } + } + + internal void ReceiveFromPeer(NetPacket packet, NetEndPoint remoteEndPoint) + { + NetPeer fromPeer; + if (_peers.TryGetValue(remoteEndPoint, out fromPeer)) + { + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NM] Received message"); + var netEvent = CreateEvent(NetEventType.Receive); + netEvent.Peer = fromPeer; + netEvent.RemoteEndPoint = fromPeer.EndPoint; + netEvent.DataReader.SetSource(packet.GetPacketData()); + EnqueueEvent(netEvent); + } + } + + /// + /// Send data to all connected peers + /// + /// DataWriter with data + /// Send options (reliable, unreliable, etc.) + public void SendToAll(NetDataWriter writer, SendOptions options) + { + SendToAll(writer.Data, 0, writer.Length, options); + } + + /// + /// Send data to all connected peers + /// + /// Data + /// Send options (reliable, unreliable, etc.) + public void SendToAll(byte[] data, SendOptions options) + { + SendToAll(data, 0, data.Length, options); + } + + /// + /// Send data to all connected peers + /// + /// Data + /// Start of data + /// Length of data + /// Send options (reliable, unreliable, etc.) + public void SendToAll(byte[] data, int start, int length, SendOptions options) + { + lock (_peers) + { + for(int i = 0; i < _peers.Count; i++) + { + _peers[i].Send(data, start, length, options); + } + } + } + + /// + /// Send data to all connected peers + /// + /// DataWriter with data + /// Send options (reliable, unreliable, etc.) + /// Excluded peer + public void SendToAll(NetDataWriter writer, SendOptions options, NetPeer excludePeer) + { + SendToAll(writer.Data, 0, writer.Length, options, excludePeer); + } + + /// + /// Send data to all connected peers + /// + /// Data + /// Send options (reliable, unreliable, etc.) + /// Excluded peer + public void SendToAll(byte[] data, SendOptions options, NetPeer excludePeer) + { + SendToAll(data, 0, data.Length, options, excludePeer); + } + + /// + /// Send data to all connected peers + /// + /// Data + /// Start of data + /// Length of data + /// Send options (reliable, unreliable, etc.) + /// Excluded peer + public void SendToAll(byte[] data, int start, int length, SendOptions options, NetPeer excludePeer) + { + lock (_peers) + { + for (int i = 0; i < _peers.Count; i++) + { + var netPeer = _peers[i]; + if (netPeer != excludePeer) + { + netPeer.Send(data, start, length, options); + } + } + } + } + + /// + /// Start logic thread and listening on available port + /// + public bool Start() + { + return Start(0); + } + + /// + /// Start logic thread and listening on selected port + /// + /// port to listen + public bool Start(int port) + { + if (IsRunning) + { + return false; + } + + _netEventsQueue.Clear(); + if (!_socket.Bind(port, ReuseAddress)) + return false; + + _logicThread.Start(); + return true; + } + + /// + /// Send message without connection + /// + /// Raw data + /// Packet destination + /// Operation result + public bool SendUnconnectedMessage(byte[] message, NetEndPoint remoteEndPoint) + { + return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint); + } + + /// + /// Send message without connection + /// + /// Data serializer + /// Packet destination + /// Operation result + public bool SendUnconnectedMessage(NetDataWriter writer, NetEndPoint remoteEndPoint) + { + return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint); + } + + /// + /// Send message without connection + /// + /// Raw data + /// data start + /// data length + /// Packet destination + /// Operation result + public bool SendUnconnectedMessage(byte[] message, int start, int length, NetEndPoint remoteEndPoint) + { + if (!IsRunning) + return false; + var packet = _netPacketPool.GetWithData(PacketProperty.UnconnectedMessage, message, start, length); + bool result = SendRawAndRecycle(packet, remoteEndPoint); + return result; + } + + public bool SendDiscoveryRequest(NetDataWriter writer, int port) + { + return SendDiscoveryRequest(writer.Data, 0, writer.Length, port); + } + + public bool SendDiscoveryRequest(byte[] data, int port) + { + return SendDiscoveryRequest(data, 0, data.Length, port); + } + + public bool SendDiscoveryRequest(byte[] data, int start, int length, int port) + { + if (!IsRunning) + return false; + var packet = _netPacketPool.GetWithData(PacketProperty.DiscoveryRequest, data, start, length); + bool result = _socket.SendBroadcast(packet.RawData, 0, packet.Size, port); + _netPacketPool.Recycle(packet); + return result; + } + + public bool SendDiscoveryResponse(NetDataWriter writer, NetEndPoint remoteEndPoint) + { + return SendDiscoveryResponse(writer.Data, 0, writer.Length, remoteEndPoint); + } + + public bool SendDiscoveryResponse(byte[] data, NetEndPoint remoteEndPoint) + { + return SendDiscoveryResponse(data, 0, data.Length, remoteEndPoint); + } + + public bool SendDiscoveryResponse(byte[] data, int start, int length, NetEndPoint remoteEndPoint) + { + if (!IsRunning) + return false; + var packet = _netPacketPool.GetWithData(PacketProperty.DiscoveryResponse, data, start, length); + bool result = SendRawAndRecycle(packet, remoteEndPoint); + return result; + } + + /// + /// Flush all queued packets of all peers + /// + public void Flush() + { + lock (_peers) + { + for (int i = 0; i < _peers.Count; i++) + { + _peers[i].Flush(); + } + } + } + + /// + /// Receive all pending events. Call this in game update code + /// + public void PollEvents() + { + if (UnsyncedEvents) + return; + + while (_netEventsQueue.Count > 0) + { + NetEvent evt; + lock (_netEventsQueue) + { + evt = _netEventsQueue.Dequeue(); + } + ProcessEvent(evt); + } + } + + /// + /// Connect to remote host + /// + /// Server IP or hostname + /// Server Port + public void Connect(string address, int port) + { + //Create target endpoint + NetEndPoint ep = new NetEndPoint(address, port); + Connect(ep); + } + + /// + /// Connect to remote host + /// + /// Server end point (ip and port) + public void Connect(NetEndPoint target) + { + if (!IsRunning) + { + throw new Exception("Client is not running"); + } + lock (_peers) + { + if (_peers.ContainsAddress(target) || _peers.Count >= _maxConnections) + { + //Already connected + return; + } + + //Create reliable connection + //And request connection + var newPeer = new NetPeer(this, target, 0); + _peers.Add(target, newPeer); + } + } + + /// + /// Force closes connection and stop all threads. + /// + public void Stop() + { + //Send disconnect packets + lock (_peers) + { + for (int i = 0; i < _peers.Count; i++) + { + var disconnectPacket = _netPacketPool.Get(PacketProperty.Disconnect, 8); + FastBitConverter.GetBytes(disconnectPacket.RawData, 1, _peers[i].ConnectId); + SendRawAndRecycle(disconnectPacket, _peers[i].EndPoint); + } + } + + //Clear + ClearPeers(); + + //Stop + if (IsRunning) + { + _logicThread.Stop(); + _socket.Close(); + } + } + + /// + /// Get first peer. Usefull for Client mode + /// + /// + public NetPeer GetFirstPeer() + { + lock (_peers) + { + if (_peers.Count > 0) + { + return _peers[0]; + } + } + return null; + } + + /// + /// Get copy of current connected peers + /// + /// Array with connected peers + public NetPeer[] GetPeers() + { + NetPeer[] peers; + lock (_peers) + { + peers = _peers.ToArray(); + } + return peers; + } + + /// + /// Get copy of current connected peers (without allocations) + /// + /// List that will contain result + public void GetPeersNonAlloc(List peers) + { + peers.Clear(); + lock (_peers) + { + for(int i = 0; i < _peers.Count; i++) + { + peers.Add(_peers[i]); + } + } + } + + /// + /// Disconnect peer from server + /// + /// peer to disconnect + public void DisconnectPeer(NetPeer peer) + { + DisconnectPeer(peer, null, 0, 0); + } + + /// + /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) + /// + /// peer to disconnect + /// additional data + public void DisconnectPeer(NetPeer peer, byte[] data) + { + DisconnectPeer(peer, data, 0, data.Length); + } + + /// + /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) + /// + /// peer to disconnect + /// additional data + public void DisconnectPeer(NetPeer peer, NetDataWriter writer) + { + DisconnectPeer(peer, writer.Data, 0, writer.Length); + } + + /// + /// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8) + /// + /// peer to disconnect + /// additional data + /// data start + /// data length + public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count) + { + if (peer != null && _peers.ContainsAddress(peer.EndPoint)) + { + DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, 0, true, data, start, count); + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs.meta new file mode 100644 index 0000000..5097d63 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetManager.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a0197124da84847d8855d5f690b8c653 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs new file mode 100644 index 0000000..ccad0e1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs @@ -0,0 +1,163 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using FlyingWormConsole3.LiteNetLib.Utils; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal enum PacketProperty : byte + { + Unreliable, //0 + Reliable, //1 + Sequenced, //2 + ReliableOrdered, //3 + AckReliable, //4 + AckReliableOrdered, //5 + Ping, //6 + Pong, //7 + ConnectRequest, //8 + ConnectAccept, //9 + Disconnect, //10 + UnconnectedMessage, //11 + NatIntroductionRequest, //12 + NatIntroduction, //13 + NatPunchMessage, //14 + MtuCheck, //15 + MtuOk, //16 + DiscoveryRequest, //17 + DiscoveryResponse, //18 + Merged //19 + } + + internal sealed class NetPacket + { + private const int LastProperty = 19; + + //Header + public PacketProperty Property + { + get { return (PacketProperty)(RawData[0] & 0x7F); } + set { RawData[0] = (byte)((RawData[0] & 0x80) | ((byte)value & 0x7F)); } + } + + public ushort Sequence + { + get { return BitConverter.ToUInt16(RawData, 1); } + set { FastBitConverter.GetBytes(RawData, 1, value); } + } + + public bool IsFragmented + { + get { return (RawData[0] & 0x80) != 0; } + set + { + if (value) + RawData[0] |= 0x80; //set first bit + else + RawData[0] &= 0x7F; //unset first bit + } + } + + public ushort FragmentId + { + get { return BitConverter.ToUInt16(RawData, 3); } + set { FastBitConverter.GetBytes(RawData, 3, value); } + } + + public ushort FragmentPart + { + get { return BitConverter.ToUInt16(RawData, 5); } + set { FastBitConverter.GetBytes(RawData, 5, value); } + } + + public ushort FragmentsTotal + { + get { return BitConverter.ToUInt16(RawData, 7); } + set { FastBitConverter.GetBytes(RawData, 7, value); } + } + + //Data + public readonly byte[] RawData; + public int Size; + + public NetPacket(int size) + { + RawData = new byte[size]; + Size = 0; + } + + public static bool GetPacketProperty(byte[] data, out PacketProperty property) + { + byte properyByte = (byte)(data[0] & 0x7F); + if (properyByte > LastProperty) + { + property = PacketProperty.Unreliable; + return false; + } + property = (PacketProperty)properyByte; + return true; + } + + public static int GetHeaderSize(PacketProperty property) + { + return IsSequenced(property) + ? NetConstants.SequencedHeaderSize + : NetConstants.HeaderSize; + } + + public int GetHeaderSize() + { + return GetHeaderSize(Property); + } + + public byte[] GetPacketData() + { + int headerSize = GetHeaderSize(Property); + int dataSize = Size - headerSize; + byte[] data = new byte[dataSize]; + Buffer.BlockCopy(RawData, headerSize, data, 0, dataSize); + return data; + } + + public bool IsClientData() + { + var property = Property; + return property == PacketProperty.Reliable || + property == PacketProperty.ReliableOrdered || + property == PacketProperty.Unreliable || + property == PacketProperty.Sequenced; + } + + public static bool IsSequenced(PacketProperty property) + { + return property == PacketProperty.ReliableOrdered || + property == PacketProperty.Reliable || + property == PacketProperty.Sequenced || + property == PacketProperty.Ping || + property == PacketProperty.Pong || + property == PacketProperty.AckReliable || + property == PacketProperty.AckReliableOrdered; + } + + //Packet contstructor from byte array + public bool FromBytes(byte[] data, int start, int packetSize) + { + //Reading property + byte property = (byte)(data[start] & 0x7F); + bool fragmented = (data[start] & 0x80) != 0; + int headerSize = GetHeaderSize((PacketProperty) property); + + if (property > LastProperty || + packetSize > NetConstants.PacketSizeLimit || + packetSize < headerSize || + (fragmented && packetSize < headerSize + NetConstants.FragmentHeaderSize)) + { + return false; + } + + Buffer.BlockCopy(data, start, RawData, 0, packetSize); + Size = packetSize; + return true; + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs.meta new file mode 100644 index 0000000..7f2d552 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacket.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7aa9ed55f53fa48569ccd0963c50d8da +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs new file mode 100644 index 0000000..c4aba1e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs @@ -0,0 +1,101 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Collections.Generic; +using FlyingWormConsole3.LiteNetLib.Utils; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal class NetPacketPool + { + private readonly Stack _pool; + + public NetPacketPool() + { + _pool = new Stack(); + } + + public NetPacket GetWithData(PacketProperty property, NetDataWriter writer) + { + var packet = Get(property, writer.Length); + Buffer.BlockCopy(writer.Data, 0, packet.RawData, NetPacket.GetHeaderSize(property), writer.Length); + return packet; + } + + public NetPacket GetWithData(PacketProperty property, byte[] data, int start, int length) + { + var packet = Get(property, length); + Buffer.BlockCopy(data, start, packet.RawData, NetPacket.GetHeaderSize(property), length); + return packet; + } + + //Get packet just for read + public NetPacket GetAndRead(byte[] data, int start, int count) + { + NetPacket packet = null; + lock (_pool) + { + if (_pool.Count > 0) + { + packet = _pool.Pop(); + } + } + if (packet == null) + { + //allocate new packet of max size or bigger + packet = new NetPacket(NetConstants.MaxPacketSize); + } + if (!packet.FromBytes(data, start, count)) + { + Recycle(packet); + return null; + } + return packet; + } + + //Get packet with size + public NetPacket Get(PacketProperty property, int size) + { + NetPacket packet = null; + size += NetPacket.GetHeaderSize(property); + if (size <= NetConstants.MaxPacketSize) + { + lock (_pool) + { + if (_pool.Count > 0) + { + packet = _pool.Pop(); + } + } + } + if (packet == null) + { + //allocate new packet of max size or bigger + packet = new NetPacket(size > NetConstants.MaxPacketSize ? size : NetConstants.MaxPacketSize); + } + else + { + Array.Clear(packet.RawData, 0, size); + } + packet.Property = property; + packet.Size = size; + return packet; + } + + public void Recycle(NetPacket packet) + { + if (packet.Size > NetConstants.MaxPacketSize) + { + //Dont pool big packets. Save memory + return; + } + + //Clean fragmented flag + packet.IsFragmented = false; + lock (_pool) + { + _pool.Push(packet); + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs.meta new file mode 100644 index 0000000..d7cb731 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPacketPool.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3637381933a4745b996d4dd48cd71efe +timeCreated: 1497976517 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs new file mode 100644 index 0000000..3ed80d1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs @@ -0,0 +1,857 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Collections.Generic; +using System.Text; +using FlyingWormConsole3.LiteNetLib.Utils; + +namespace FlyingWormConsole3.LiteNetLib +{ + public enum ConnectionState + { + InProgress, + Connected, + Disconnected + } + + public sealed class NetPeer + { + //Flow control + private int _currentFlowMode; + private int _sendedPacketsCount; + private int _flowTimer; + + //Ping and RTT + private int _ping; + private int _rtt; + private int _avgRtt; + private int _rttCount; + private int _goodRttCount; + private ushort _pingSequence; + private ushort _remotePingSequence; + private double _resendDelay = 27.0; + + private int _pingSendTimer; + private const int RttResetDelay = 1000; + private int _rttResetTimer; + + private DateTime _pingTimeStart; + private int _timeSinceLastPacket; + + //Common + private readonly NetEndPoint _remoteEndPoint; + private readonly NetManager _peerListener; + private readonly NetPacketPool _packetPool; + private readonly object _flushLock = new object(); + + //Channels + private readonly ReliableChannel _reliableOrderedChannel; + private readonly ReliableChannel _reliableUnorderedChannel; + private readonly SequencedChannel _sequencedChannel; + private readonly SimpleChannel _simpleChannel; + + private int _windowSize = NetConstants.DefaultWindowSize; + + //MTU + private int _mtu = NetConstants.PossibleMtu[0]; + private int _mtuIdx; + private bool _finishMtu; + private int _mtuCheckTimer; + private int _mtuCheckAttempts; + private const int MtuCheckDelay = 1000; + private const int MaxMtuCheckAttempts = 4; + private readonly object _mtuMutex = new object(); + + //Fragment + private class IncomingFragments + { + public NetPacket[] Fragments; + public int ReceivedCount; + public int TotalSize; + } + private ushort _fragmentId; + private readonly Dictionary _holdedFragments; + + //Merging + private readonly NetPacket _mergeData; + private int _mergePos; + private int _mergeCount; + + //Connection + private int _connectAttempts; + private int _connectTimer; + private long _connectId; + private ConnectionState _connectionState; + + public ConnectionState ConnectionState + { + get { return _connectionState; } + } + + public long ConnectId + { + get { return _connectId; } + } + + public NetEndPoint EndPoint + { + get { return _remoteEndPoint; } + } + + public int Ping + { + get { return _ping; } + } + + public int CurrentFlowMode + { + get { return _currentFlowMode; } + } + + public int Mtu + { + get { return _mtu; } + } + + public int TimeSinceLastPacket + { + get { return _timeSinceLastPacket; } + } + + public NetManager NetManager + { + get { return _peerListener; } + } + + public int PacketsCountInReliableQueue + { + get { return _reliableUnorderedChannel.PacketsInQueue; } + } + + public int PacketsCountInReliableOrderedQueue + { + get { return _reliableOrderedChannel.PacketsInQueue; } + } + + internal double ResendDelay + { + get { return _resendDelay; } + } + + /// + /// Application defined object containing data about the connection + /// + public object Tag; + + internal NetPeer(NetManager peerListener, NetEndPoint remoteEndPoint, long connectId) + { + _packetPool = peerListener.PacketPool; + _peerListener = peerListener; + _remoteEndPoint = remoteEndPoint; + + _avgRtt = 0; + _rtt = 0; + _pingSendTimer = 0; + + _reliableOrderedChannel = new ReliableChannel(this, true, _windowSize); + _reliableUnorderedChannel = new ReliableChannel(this, false, _windowSize); + _sequencedChannel = new SequencedChannel(this); + _simpleChannel = new SimpleChannel(this); + + _holdedFragments = new Dictionary(); + + _mergeData = _packetPool.Get(PacketProperty.Merged, NetConstants.MaxPacketSize); + + //if ID != 0 then we already connected + _connectAttempts = 0; + if (connectId == 0) + { + _connectId = DateTime.UtcNow.Ticks; + SendConnectRequest(); + } + else + { + _connectId = connectId; + _connectionState = ConnectionState.Connected; + SendConnectAccept(); + } + + NetUtils.DebugWrite(ConsoleColor.Cyan, "[CC] ConnectId: {0}", _connectId); + } + + private void SendConnectRequest() + { + //Get connect key bytes + byte[] keyData = Encoding.UTF8.GetBytes(_peerListener.ConnectKey); + + //Make initial packet + var connectPacket = _packetPool.Get(PacketProperty.ConnectRequest, 12 + keyData.Length); + + //Add data + FastBitConverter.GetBytes(connectPacket.RawData, 1, NetConstants.ProtocolId); + FastBitConverter.GetBytes(connectPacket.RawData, 5, _connectId); + Buffer.BlockCopy(keyData, 0, connectPacket.RawData, 13, keyData.Length); + + //Send raw + _peerListener.SendRawAndRecycle(connectPacket, _remoteEndPoint); + } + + private void SendConnectAccept() + { + //Reset connection timer + _timeSinceLastPacket = 0; + + //Make initial packet + var connectPacket = _packetPool.Get(PacketProperty.ConnectAccept, 8); + + //Add data + FastBitConverter.GetBytes(connectPacket.RawData, 1, _connectId); + + //Send raw + _peerListener.SendRawAndRecycle(connectPacket, _remoteEndPoint); + } + + internal bool ProcessConnectAccept(NetPacket packet) + { + if (_connectionState != ConnectionState.InProgress) + return false; + + //check connection id + if (BitConverter.ToInt64(packet.RawData, 1) != _connectId) + { + return false; + } + + NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received connection accept"); + _timeSinceLastPacket = 0; + _connectionState = ConnectionState.Connected; + return true; + } + + private static PacketProperty SendOptionsToProperty(SendOptions options) + { + switch (options) + { + case SendOptions.ReliableUnordered: + return PacketProperty.Reliable; + case SendOptions.Sequenced: + return PacketProperty.Sequenced; + case SendOptions.ReliableOrdered: + return PacketProperty.ReliableOrdered; + default: + return PacketProperty.Unreliable; + } + } + + public int GetMaxSinglePacketSize(SendOptions options) + { + return _mtu - NetPacket.GetHeaderSize(SendOptionsToProperty(options)); + } + + public void Send(byte[] data, SendOptions options) + { + Send(data, 0, data.Length, options); + } + + public void Send(NetDataWriter dataWriter, SendOptions options) + { + Send(dataWriter.Data, 0, dataWriter.Length, options); + } + + public void Send(byte[] data, int start, int length, SendOptions options) + { + //Prepare + PacketProperty property = SendOptionsToProperty(options); + int headerSize = NetPacket.GetHeaderSize(property); + + //Check fragmentation + if (length + headerSize > _mtu) + { + if (options == SendOptions.Sequenced || options == SendOptions.Unreliable) + { + throw new Exception("Unreliable packet size > allowed (" + (_mtu - headerSize) + ")"); + } + + int packetFullSize = _mtu - headerSize; + int packetDataSize = packetFullSize - NetConstants.FragmentHeaderSize; + + int fullPacketsCount = length / packetDataSize; + int lastPacketSize = length % packetDataSize; + int totalPackets = fullPacketsCount + (lastPacketSize == 0 ? 0 : 1); + + NetUtils.DebugWrite("FragmentSend:\n" + + " MTU: {0}\n" + + " headerSize: {1}\n" + + " packetFullSize: {2}\n" + + " packetDataSize: {3}\n" + + " fullPacketsCount: {4}\n" + + " lastPacketSize: {5}\n" + + " totalPackets: {6}", + _mtu, headerSize, packetFullSize, packetDataSize, fullPacketsCount, lastPacketSize, totalPackets); + + if (totalPackets > ushort.MaxValue) + { + throw new Exception("Too many fragments: " + totalPackets + " > " + ushort.MaxValue); + } + + int dataOffset = headerSize + NetConstants.FragmentHeaderSize; + for (ushort i = 0; i < fullPacketsCount; i++) + { + NetPacket p = _packetPool.Get(property, packetFullSize); + p.FragmentId = _fragmentId; + p.FragmentPart = i; + p.FragmentsTotal = (ushort)totalPackets; + p.IsFragmented = true; + Buffer.BlockCopy(data, i * packetDataSize, p.RawData, dataOffset, packetDataSize); + SendPacket(p); + } + + if (lastPacketSize > 0) + { + NetPacket p = _packetPool.Get(property, lastPacketSize + NetConstants.FragmentHeaderSize); + p.FragmentId = _fragmentId; + p.FragmentPart = (ushort)fullPacketsCount; //last + p.FragmentsTotal = (ushort)totalPackets; + p.IsFragmented = true; + Buffer.BlockCopy(data, fullPacketsCount * packetDataSize, p.RawData, dataOffset, lastPacketSize); + SendPacket(p); + } + + _fragmentId++; + return; + } + + //Else just send + NetPacket packet = _packetPool.GetWithData(property, data, start, length); + SendPacket(packet); + } + + private void CreateAndSend(PacketProperty property, ushort sequence) + { + NetPacket packet = _packetPool.Get(property, 0); + packet.Sequence = sequence; + SendPacket(packet); + } + + //from user thread, our thread, or recv? + private void SendPacket(NetPacket packet) + { + NetUtils.DebugWrite("[RS]Packet: " + packet.Property); + switch (packet.Property) + { + case PacketProperty.Reliable: + _reliableUnorderedChannel.AddToQueue(packet); + break; + case PacketProperty.Sequenced: + _sequencedChannel.AddToQueue(packet); + break; + case PacketProperty.ReliableOrdered: + _reliableOrderedChannel.AddToQueue(packet); + break; + case PacketProperty.Unreliable: + _simpleChannel.AddToQueue(packet); + break; + case PacketProperty.MtuCheck: + //Must check result for MTU fix + if (!_peerListener.SendRawAndRecycle(packet, _remoteEndPoint)) + { + _finishMtu = true; + } + break; + case PacketProperty.AckReliable: + case PacketProperty.AckReliableOrdered: + case PacketProperty.Ping: + case PacketProperty.Pong: + case PacketProperty.Disconnect: + case PacketProperty.MtuOk: + SendRawData(packet); + _packetPool.Recycle(packet); + break; + default: + throw new Exception("Unknown packet property: " + packet.Property); + } + } + + private void UpdateRoundTripTime(int roundTripTime) + { + //Calc average round trip time + _rtt += roundTripTime; + _rttCount++; + _avgRtt = _rtt/_rttCount; + + //flowmode 0 = fastest + //flowmode max = lowest + + if (_avgRtt < _peerListener.GetStartRtt(_currentFlowMode - 1)) + { + if (_currentFlowMode <= 0) + { + //Already maxed + return; + } + + _goodRttCount++; + if (_goodRttCount > NetConstants.FlowIncreaseThreshold) + { + _goodRttCount = 0; + _currentFlowMode--; + + NetUtils.DebugWrite("[PA]Increased flow speed, RTT: {0}, PPS: {1}", _avgRtt, _peerListener.GetPacketsPerSecond(_currentFlowMode)); + } + } + else if(_avgRtt > _peerListener.GetStartRtt(_currentFlowMode)) + { + _goodRttCount = 0; + if (_currentFlowMode < _peerListener.GetMaxFlowMode()) + { + _currentFlowMode++; + NetUtils.DebugWrite("[PA]Decreased flow speed, RTT: {0}, PPS: {1}", _avgRtt, _peerListener.GetPacketsPerSecond(_currentFlowMode)); + } + } + + //recalc resend delay + double avgRtt = _avgRtt; + if (avgRtt <= 0.0) + avgRtt = 0.1; + _resendDelay = 25 + (avgRtt * 2.1); // 25 ms + double rtt + } + + internal void AddIncomingPacket(NetPacket p) + { + if (p.IsFragmented) + { + NetUtils.DebugWrite("Fragment. Id: {0}, Part: {1}, Total: {2}", p.FragmentId, p.FragmentPart, p.FragmentsTotal); + //Get needed array from dictionary + ushort packetFragId = p.FragmentId; + IncomingFragments incomingFragments; + if (!_holdedFragments.TryGetValue(packetFragId, out incomingFragments)) + { + incomingFragments = new IncomingFragments + { + Fragments = new NetPacket[p.FragmentsTotal] + }; + _holdedFragments.Add(packetFragId, incomingFragments); + } + + //Cache + var fragments = incomingFragments.Fragments; + + //Error check + if (p.FragmentPart >= fragments.Length || fragments[p.FragmentPart] != null) + { + _packetPool.Recycle(p); + NetUtils.DebugWriteError("Invalid fragment packet"); + return; + } + //Fill array + fragments[p.FragmentPart] = p; + + //Increase received fragments count + incomingFragments.ReceivedCount++; + + //Increase total size + int dataOffset = p.GetHeaderSize() + NetConstants.FragmentHeaderSize; + incomingFragments.TotalSize += p.Size - dataOffset; + + //Check for finish + if (incomingFragments.ReceivedCount != fragments.Length) + { + return; + } + + NetUtils.DebugWrite("Received all fragments!"); + NetPacket resultingPacket = _packetPool.Get( p.Property, incomingFragments.TotalSize ); + + int resultingPacketOffset = resultingPacket.GetHeaderSize(); + int firstFragmentSize = fragments[0].Size - dataOffset; + for (int i = 0; i < incomingFragments.ReceivedCount; i++) + { + //Create resulting big packet + int fragmentSize = fragments[i].Size - dataOffset; + Buffer.BlockCopy( + fragments[i].RawData, + dataOffset, + resultingPacket.RawData, + resultingPacketOffset + firstFragmentSize * i, + fragmentSize); + + //Free memory + _packetPool.Recycle(fragments[i]); + fragments[i] = null; + } + + //Send to process + _peerListener.ReceiveFromPeer(resultingPacket, _remoteEndPoint); + + //Clear memory + _packetPool.Recycle(resultingPacket); + _holdedFragments.Remove(packetFragId); + } + else //Just simple packet + { + _peerListener.ReceiveFromPeer(p, _remoteEndPoint); + _packetPool.Recycle(p); + } + } + + private void ProcessMtuPacket(NetPacket packet) + { + if (packet.Size == 1 || + packet.RawData[1] >= NetConstants.PossibleMtu.Length) + return; + + //MTU auto increase + if (packet.Property == PacketProperty.MtuCheck) + { + if (packet.Size != NetConstants.PossibleMtu[packet.RawData[1]]) + { + return; + } + _mtuCheckAttempts = 0; + NetUtils.DebugWrite("MTU check. Resend: " + packet.RawData[1]); + var mtuOkPacket = _packetPool.Get(PacketProperty.MtuOk, 1); + mtuOkPacket.RawData[1] = packet.RawData[1]; + SendPacket(mtuOkPacket); + } + else if(packet.RawData[1] > _mtuIdx) //MtuOk + { + lock (_mtuMutex) + { + _mtuIdx = packet.RawData[1]; + _mtu = NetConstants.PossibleMtu[_mtuIdx]; + } + //if maxed - finish. + if (_mtuIdx == NetConstants.PossibleMtu.Length - 1) + { + _finishMtu = true; + } + NetUtils.DebugWrite("MTU ok. Increase to: " + _mtu); + } + } + + //Process incoming packet + internal void ProcessPacket(NetPacket packet) + { + _timeSinceLastPacket = 0; + + NetUtils.DebugWrite("[RR]PacketProperty: {0}", packet.Property); + switch (packet.Property) + { + case PacketProperty.ConnectRequest: + //response with connect + long newId = BitConverter.ToInt64(packet.RawData, 1); + if (newId > _connectId) + { + _connectId = newId; + } + + NetUtils.DebugWrite("ConnectRequest LastId: {0}, NewId: {1}, EP: {2}", ConnectId, newId, _remoteEndPoint); + SendConnectAccept(); + _packetPool.Recycle(packet); + break; + + case PacketProperty.Merged: + int pos = NetConstants.HeaderSize; + while (pos < packet.Size) + { + ushort size = BitConverter.ToUInt16(packet.RawData, pos); + pos += 2; + NetPacket mergedPacket = _packetPool.GetAndRead(packet.RawData, pos, size); + if (mergedPacket == null) + { + _packetPool.Recycle(packet); + break; + } + pos += size; + ProcessPacket(mergedPacket); + } + break; + //If we get ping, send pong + case PacketProperty.Ping: + if (NetUtils.RelativeSequenceNumber(packet.Sequence, _remotePingSequence) < 0) + { + _packetPool.Recycle(packet); + break; + } + NetUtils.DebugWrite("[PP]Ping receive, send pong"); + _remotePingSequence = packet.Sequence; + _packetPool.Recycle(packet); + + //send + CreateAndSend(PacketProperty.Pong, _remotePingSequence); + break; + + //If we get pong, calculate ping time and rtt + case PacketProperty.Pong: + if (NetUtils.RelativeSequenceNumber(packet.Sequence, _pingSequence) < 0) + { + _packetPool.Recycle(packet); + break; + } + _pingSequence = packet.Sequence; + int rtt = (int)(DateTime.UtcNow - _pingTimeStart).TotalMilliseconds; + UpdateRoundTripTime(rtt); + NetUtils.DebugWrite("[PP]Ping: {0}", rtt); + _packetPool.Recycle(packet); + break; + + //Process ack + case PacketProperty.AckReliable: + _reliableUnorderedChannel.ProcessAck(packet); + _packetPool.Recycle(packet); + break; + + case PacketProperty.AckReliableOrdered: + _reliableOrderedChannel.ProcessAck(packet); + _packetPool.Recycle(packet); + break; + + //Process in order packets + case PacketProperty.Sequenced: + _sequencedChannel.ProcessPacket(packet); + break; + + case PacketProperty.Reliable: + _reliableUnorderedChannel.ProcessPacket(packet); + break; + + case PacketProperty.ReliableOrdered: + _reliableOrderedChannel.ProcessPacket(packet); + break; + + //Simple packet without acks + case PacketProperty.Unreliable: + AddIncomingPacket(packet); + return; + + case PacketProperty.MtuCheck: + case PacketProperty.MtuOk: + ProcessMtuPacket(packet); + break; + + default: + NetUtils.DebugWriteError("Error! Unexpected packet type: " + packet.Property); + break; + } + } + + private static bool CanMerge(PacketProperty property) + { + switch (property) + { + case PacketProperty.ConnectAccept: + case PacketProperty.ConnectRequest: + case PacketProperty.MtuOk: + case PacketProperty.Pong: + case PacketProperty.Disconnect: + return false; + default: + return true; + } + } + + internal void SendRawData(NetPacket packet) + { + //2 - merge byte + minimal packet size + datalen(ushort) + if (_peerListener.MergeEnabled && + CanMerge(packet.Property) && + _mergePos + packet.Size + NetConstants.HeaderSize*2 + 2 < _mtu) + { + FastBitConverter.GetBytes(_mergeData.RawData, _mergePos + NetConstants.HeaderSize, (ushort)packet.Size); + Buffer.BlockCopy(packet.RawData, 0, _mergeData.RawData, _mergePos + NetConstants.HeaderSize + 2, packet.Size); + _mergePos += packet.Size + 2; + _mergeCount++; + + //DebugWriteForce("Merged: " + _mergePos + "/" + (_mtu - 2) + ", count: " + _mergeCount); + return; + } + + NetUtils.DebugWrite(ConsoleColor.DarkYellow, "[P]SendingPacket: " + packet.Property); + _peerListener.SendRaw(packet.RawData, 0, packet.Size, _remoteEndPoint); + } + + private void SendQueuedPackets(int currentMaxSend) + { + int currentSended = 0; + while (currentSended < currentMaxSend) + { + //Get one of packets + if (_reliableOrderedChannel.SendNextPacket() || + _reliableUnorderedChannel.SendNextPacket() || + _sequencedChannel.SendNextPacket() || + _simpleChannel.SendNextPacket()) + { + currentSended++; + } + else + { + //no outgoing packets + break; + } + } + + //Increase counter + _sendedPacketsCount += currentSended; + + //If merging enabled + if (_mergePos > 0) + { + if (_mergeCount > 1) + { + NetUtils.DebugWrite("Send merged: " + _mergePos + ", count: " + _mergeCount); + _peerListener.SendRaw(_mergeData.RawData, 0, NetConstants.HeaderSize + _mergePos, _remoteEndPoint); + } + else + { + //Send without length information and merging + _peerListener.SendRaw(_mergeData.RawData, NetConstants.HeaderSize + 2, _mergePos - 2, _remoteEndPoint); + } + _mergePos = 0; + _mergeCount = 0; + } + } + + /// + /// Flush all queued packets + /// + public void Flush() + { + lock (_flushLock) + { + SendQueuedPackets(int.MaxValue); + } + } + + internal void Update(int deltaTime) + { + if (_connectionState == ConnectionState.Disconnected) + { + return; + } + + _timeSinceLastPacket += deltaTime; + if (_connectionState == ConnectionState.InProgress) + { + _connectTimer += deltaTime; + if (_connectTimer > _peerListener.ReconnectDelay) + { + _connectTimer = 0; + _connectAttempts++; + if (_connectAttempts > _peerListener.MaxConnectAttempts) + { + _connectionState = ConnectionState.Disconnected; + return; + } + + //else send connect again + SendConnectRequest(); + } + return; + } + + //Get current flow mode + int maxSendPacketsCount = _peerListener.GetPacketsPerSecond(_currentFlowMode); + int currentMaxSend; + + if (maxSendPacketsCount > 0) + { + int availableSendPacketsCount = maxSendPacketsCount - _sendedPacketsCount; + currentMaxSend = Math.Min(availableSendPacketsCount, (maxSendPacketsCount*deltaTime)/NetConstants.FlowUpdateTime); + } + else + { + currentMaxSend = int.MaxValue; + } + + //DebugWrite("[UPDATE]Delta: {0}ms, MaxSend: {1}", deltaTime, currentMaxSend); + + //Pending acks + _reliableOrderedChannel.SendAcks(); + _reliableUnorderedChannel.SendAcks(); + + //ResetFlowTimer + _flowTimer += deltaTime; + if (_flowTimer >= NetConstants.FlowUpdateTime) + { + NetUtils.DebugWrite("[UPDATE]Reset flow timer, _sendedPackets - {0}", _sendedPacketsCount); + _sendedPacketsCount = 0; + _flowTimer = 0; + } + + //Send ping + _pingSendTimer += deltaTime; + if (_pingSendTimer >= _peerListener.PingInterval) + { + NetUtils.DebugWrite("[PP] Send ping..."); + + //reset timer + _pingSendTimer = 0; + + //send ping + CreateAndSend(PacketProperty.Ping, _pingSequence); + + //reset timer + _pingTimeStart = DateTime.UtcNow; + } + + //RTT - round trip time + _rttResetTimer += deltaTime; + if (_rttResetTimer >= RttResetDelay) + { + _rttResetTimer = 0; + //Rtt update + _rtt = _avgRtt; + _ping = _avgRtt; + _peerListener.ConnectionLatencyUpdated(this, _ping); + _rttCount = 1; + } + + //MTU - Maximum transmission unit + if (!_finishMtu) + { + _mtuCheckTimer += deltaTime; + if (_mtuCheckTimer >= MtuCheckDelay) + { + _mtuCheckTimer = 0; + _mtuCheckAttempts++; + if (_mtuCheckAttempts >= MaxMtuCheckAttempts) + { + _finishMtu = true; + } + else + { + lock (_mtuMutex) + { + //Send increased packet + if (_mtuIdx < NetConstants.PossibleMtu.Length - 1) + { + int newMtu = NetConstants.PossibleMtu[_mtuIdx + 1] - NetConstants.HeaderSize; + var p = _packetPool.Get(PacketProperty.MtuCheck, newMtu); + p.RawData[1] = (byte)(_mtuIdx + 1); + SendPacket(p); + } + } + } + } + } + //MTU - end + + //Pending send + lock (_flushLock) + { + SendQueuedPackets(currentMaxSend); + } + } + + //For channels + internal void Recycle(NetPacket packet) + { + _packetPool.Recycle(packet); + } + + internal NetPacket GetPacketFromPool(PacketProperty property, int bytesCount) + { + return _packetPool.Get(property, bytesCount); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs.meta new file mode 100644 index 0000000..0e04605 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 39ca2e83856ea4ba0a0100a00089e695 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs new file mode 100644 index 0000000..a76a5d2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs @@ -0,0 +1,81 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Collections.Generic; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class NetPeerCollection + { + private readonly Dictionary _peersDict; + private readonly NetPeer[] _peersArray; + private int _count; + + public int Count + { + get { return _count; } + } + + public NetPeer this[int index] + { + get { return _peersArray[index]; } + } + + public NetPeerCollection(int maxPeers) + { + _peersArray = new NetPeer[maxPeers]; + _peersDict = new Dictionary(); + } + + public bool TryGetValue(NetEndPoint endPoint, out NetPeer peer) + { + return _peersDict.TryGetValue(endPoint, out peer); + } + + public void Clear() + { + Array.Clear(_peersArray, 0, _count); + _peersDict.Clear(); + _count = 0; + } + + public void Add(NetEndPoint endPoint, NetPeer peer) + { + _peersArray[_count] = peer; + _peersDict.Add(endPoint, peer); + _count++; + } + + public bool ContainsAddress(NetEndPoint endPoint) + { + return _peersDict.ContainsKey(endPoint); + } + + public NetPeer[] ToArray() + { + NetPeer[] result = new NetPeer[_count]; + Array.Copy(_peersArray, 0, result, 0, _count); + return result; + } + + public void RemoveAt(int idx) + { + _peersDict.Remove(_peersArray[idx].EndPoint); + _peersArray[idx] = _peersArray[_count - 1]; + _peersArray[_count - 1] = null; + _count--; + } + + public void Remove(NetEndPoint endPoint) + { + for (int i = 0; i < _count; i++) + { + if (_peersArray[i].EndPoint.Equals(endPoint)) + { + RemoveAt(i); + break; + } + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs.meta new file mode 100644 index 0000000..c091188 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetPeerCollection.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ca9b271291848481a86c9b3cb7f07451 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs new file mode 100644 index 0000000..f51299f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs @@ -0,0 +1,709 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Reflection; +using System.Collections.Generic; +#if WINRT || NETCORE +using System.Linq; +#endif + +namespace FlyingWormConsole3.LiteNetLib.Utils +{ + public interface INetSerializable + { + void Serialize(NetDataWriter writer); + void Desereialize(NetDataReader reader); + } + + public abstract class NetSerializerHasher + { + public abstract ulong GetHash(string type); + public abstract void WriteHash(ulong hash, NetDataWriter writer); + public abstract ulong ReadHash(NetDataReader reader); + } + + public sealed class FNVHasher : NetSerializerHasher + { + private readonly Dictionary _hashCache = new Dictionary(); + private readonly char[] _hashBuffer = new char[1024]; + + public override ulong GetHash(string type) + { + ulong hash; + if (_hashCache.TryGetValue(type, out hash)) + { + return hash; + } + hash = 14695981039346656037UL; //offset + int len = type.Length; + type.CopyTo(0, _hashBuffer, 0, len); + for (var i = 0; i < len; i++) + { + hash = hash ^ _hashBuffer[i]; + hash *= 1099511628211UL; //prime + } + _hashCache.Add(type, hash); + return hash; + } + + public override ulong ReadHash(NetDataReader reader) + { + return reader.GetULong(); + } + + public override void WriteHash(ulong hash, NetDataWriter writer) + { + writer.Put(hash); + } + } + + public sealed class NetSerializer + { + private sealed class CustomType + { + public readonly CustomTypeWrite WriteDelegate; + public readonly CustomTypeRead ReadDelegate; + + public CustomType(CustomTypeWrite writeDelegate, CustomTypeRead readDelegate) + { + WriteDelegate = writeDelegate; + ReadDelegate = readDelegate; + } + } + + private delegate void CustomTypeWrite(NetDataWriter writer, object customObj); + private delegate object CustomTypeRead(NetDataReader reader); + + private sealed class StructInfo + { + public readonly Action[] WriteDelegate; + public readonly Action[] ReadDelegate; + public readonly Type[] FieldTypes; + public object Reference; + public Func CreatorFunc; + public Action OnReceive; + public readonly ulong Hash; + public readonly int MembersCount; + + public StructInfo(ulong hash, int membersCount) + { + Hash = hash; + MembersCount = membersCount; + WriteDelegate = new Action[membersCount]; + ReadDelegate = new Action[membersCount]; + FieldTypes = new Type[membersCount]; + } + + public void Write(NetDataWriter writer, object obj) + { + Reference = obj; + for (int i = 0; i < MembersCount; i++) + { + WriteDelegate[i](writer); + } + } + + public void Read(NetDataReader reader) + { + for (int i = 0; i < MembersCount; i++) + { + ReadDelegate[i](reader); + } + } + } + + private readonly Dictionary _cache; + private readonly Dictionary _registeredCustomTypes; + + private static readonly HashSet BasicTypes = new HashSet + { + typeof(int), + typeof(uint), + typeof(byte), + typeof(sbyte), + typeof(short), + typeof(ushort), + typeof(long), + typeof(ulong), + typeof(string), + typeof(float), + typeof(double), + typeof(bool) + }; + + private readonly NetDataWriter _writer; + private readonly NetSerializerHasher _hasher; + private const int MaxStringLenght = 1024; + + public NetSerializer() : this(new FNVHasher()) + { + } + + public NetSerializer(NetSerializerHasher hasher) + { + _hasher = hasher; + _cache = new Dictionary(); + _registeredCustomTypes = new Dictionary(); + _writer = new NetDataWriter(); + } + + private bool RegisterCustomTypeInternal(Func constructor) where T : INetSerializable + { + var t = typeof(T); + if (_registeredCustomTypes.ContainsKey(t)) + { + return false; + } + + var rwDelegates = new CustomType( + (writer, obj) => + { + ((T)obj).Serialize(writer); + }, + reader => + { + var instance = constructor(); + instance.Desereialize(reader); + return instance; + }); + _registeredCustomTypes.Add(t, rwDelegates); + return true; + } + + /// + /// Register custom property type + /// + /// INetSerializable structure + /// True - if register successful, false - if type already registered + public bool RegisterCustomType() where T : struct, INetSerializable + { + return RegisterCustomTypeInternal(() => new T()); + } + + /// + /// Register custom property type + /// + /// INetSerializable class + /// True - if register successful, false - if type already registered + public bool RegisterCustomType(Func constructor) where T : class, INetSerializable + { + return RegisterCustomTypeInternal(constructor); + } + + /// + /// Register custom property type + /// + /// + /// + /// True - if register successful, false - if type already registered + public bool RegisterCustomType(Action writeDelegate, Func readDelegate) + { + var t = typeof(T); + if (BasicTypes.Contains(t) || _registeredCustomTypes.ContainsKey(t)) + { + return false; + } + + var rwDelegates = new CustomType( + (writer, obj) => writeDelegate(writer, (T)obj), + reader => readDelegate(reader)); + + _registeredCustomTypes.Add(t, rwDelegates); + return true; + } + + private static Delegate CreateDelegate(Type type, MethodInfo info) + { +#if WINRT || NETCORE + return info.CreateDelegate(type); +#else + return Delegate.CreateDelegate(type, info); +#endif + } + + private static Func ExtractGetDelegate(MethodInfo info) + { + return (Func)CreateDelegate(typeof(Func), info); + } + + private static Action ExtractSetDelegate(MethodInfo info) + { + return (Action)CreateDelegate(typeof(Action), info); + } + + private StructInfo RegisterInternal() where T : class + { + Type t = typeof(T); + ulong nameHash = _hasher.GetHash(t.Name); + + StructInfo info; + if (_cache.TryGetValue(nameHash, out info)) + { + return info; + } + +#if WINRT || NETCORE + var props = t.GetRuntimeProperties().ToArray(); + int propsCount = props.Count(); +#else + var props = t.GetProperties( + BindingFlags.Instance | + BindingFlags.Public | + BindingFlags.GetProperty | + BindingFlags.SetProperty); + int propsCount = props.Length; +#endif + if (props == null || propsCount < 0) + { + throw new ArgumentException("Type does not contain acceptable fields"); + } + + info = new StructInfo(nameHash, propsCount); + for (int i = 0; i < props.Length; i++) + { + var property = props[i]; + var propertyType = property.PropertyType; + + //Set field type + info.FieldTypes[i] = propertyType.IsArray ? propertyType.GetElementType() : propertyType; +#if WINRT || NETCORE + bool isEnum = propertyType.GetTypeInfo().IsEnum; + var getMethod = property.GetMethod; + var setMethod = property.SetMethod; +#else + bool isEnum = propertyType.IsEnum; + var getMethod = property.GetGetMethod(); + var setMethod = property.GetSetMethod(); +#endif + if (isEnum) + { + var underlyingType = Enum.GetUnderlyingType(propertyType); + if (underlyingType == typeof(byte)) + { + info.ReadDelegate[i] = reader => + { + property.SetValue(info.Reference, Enum.ToObject(propertyType, reader.GetByte()), null); + }; + info.WriteDelegate[i] = writer => + { + writer.Put((byte)property.GetValue(info.Reference, null)); + }; + } + else if (underlyingType == typeof(int)) + { + info.ReadDelegate[i] = reader => + { + property.SetValue(info.Reference, Enum.ToObject(propertyType, reader.GetInt()), null); + }; + info.WriteDelegate[i] = writer => + { + writer.Put((int)property.GetValue(info.Reference, null)); + }; + } + else + { + throw new Exception("Not supported enum underlying type: " + underlyingType.Name); + } + } + else if (propertyType == typeof(string)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetString(MaxStringLenght)); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference), MaxStringLenght); + } + else if (propertyType == typeof(bool)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetBool()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(byte)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetByte()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(sbyte)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetSByte()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(short)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetShort()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(ushort)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetUShort()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(int)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetInt()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(uint)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetUInt()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(long)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetLong()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(ulong)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetULong()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(float)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetFloat()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(double)) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetDouble()); + info.WriteDelegate[i] = writer => writer.Put(getDelegate((T)info.Reference)); + } + // Array types + else if (propertyType == typeof(string[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetStringArray(MaxStringLenght)); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference), MaxStringLenght); + } + else if (propertyType == typeof(byte[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetBytesWithLength()); + info.WriteDelegate[i] = writer => writer.PutBytesWithLength(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(short[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetShortArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(ushort[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetUShortArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(int[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetIntArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(uint[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetUIntArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(long[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetLongArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(ulong[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetULongArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(float[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetFloatArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else if (propertyType == typeof(double[])) + { + var setDelegate = ExtractSetDelegate(setMethod); + var getDelegate = ExtractGetDelegate(getMethod); + info.ReadDelegate[i] = reader => setDelegate((T)info.Reference, reader.GetDoubleArray()); + info.WriteDelegate[i] = writer => writer.PutArray(getDelegate((T)info.Reference)); + } + else + { + CustomType registeredCustomType; + bool array = false; + + if (propertyType.IsArray) + { + array = true; + propertyType = propertyType.GetElementType(); + } + + if (_registeredCustomTypes.TryGetValue(propertyType, out registeredCustomType)) + { + if (array) //Array type serialize/deserialize + { + info.ReadDelegate[i] = reader => + { + ushort arrLength = reader.GetUShort(); + Array arr = Array.CreateInstance(propertyType, arrLength); + for (int k = 0; k < arrLength; k++) + { + arr.SetValue(registeredCustomType.ReadDelegate(reader), k); + } + + property.SetValue(info.Reference, arr, null); + }; + + info.WriteDelegate[i] = writer => + { + Array arr = (Array)property.GetValue(info.Reference, null); + writer.Put((ushort)arr.Length); + for (int k = 0; k < arr.Length; k++) + { + registeredCustomType.WriteDelegate(writer, arr.GetValue(k)); + } + }; + } + else //Simple + { + info.ReadDelegate[i] = reader => + { + property.SetValue(info.Reference, registeredCustomType.ReadDelegate(reader), null); + }; + + info.WriteDelegate[i] = writer => + { + registeredCustomType.WriteDelegate(writer, property.GetValue(info.Reference, null)); + }; + } + } + else + { + throw new Exception("Unknown property type: " + propertyType.Name); + } + } + } + _cache.Add(nameHash, info); + + return info; + } + + /// + /// Reads all available data from NetDataReader and calls OnReceive delegates + /// + /// NetDataReader with packets data + public void ReadAllPackets(NetDataReader reader) + { + while (reader.AvailableBytes > 0) + { + ReadPacket(reader); + } + } + + /// + /// Reads all available data from NetDataReader and calls OnReceive delegates + /// + /// NetDataReader with packets data + /// Argument that passed to OnReceivedEvent + public void ReadAllPackets(NetDataReader reader, T userData) + { + while (reader.AvailableBytes > 0) + { + ReadPacket(reader, userData); + } + } + + /// + /// Reads one packet from NetDataReader and calls OnReceive delegate + /// + /// NetDataReader with packet + public void ReadPacket(NetDataReader reader) + { + ReadPacket(reader, null); + } + + private StructInfo ReadInfo(NetDataReader reader) + { + ulong hash = _hasher.ReadHash(reader); + StructInfo info; + if (!_cache.TryGetValue(hash, out info)) + { + throw new Exception("Undefined packet received"); + } + return info; + } + + /// + /// Reads packet with known type + /// + /// NetDataReader with packet + /// Returns packet if packet in reader is matched type + public T ReadKnownPacket(NetDataReader reader) where T : class, new() + { + var info = ReadInfo(reader); + ulong typeHash = _hasher.GetHash(typeof(T).Name); + if (typeHash != info.Hash) + { + return null; + } + info.Reference = info.CreatorFunc != null ? info.CreatorFunc() : Activator.CreateInstance(); + info.Read(reader); + return (T)info.Reference; + } + + /// + /// Reads packet with known type (non alloc variant) + /// + /// NetDataReader with packet + /// Deserialization target + /// Returns true if packet in reader is matched type + public bool ReadKnownPacket(NetDataReader reader, T target) where T : class, new() + { + var info = ReadInfo(reader); + ulong typeHash = _hasher.GetHash(typeof(T).Name); + if (typeHash != info.Hash) + { + return false; + } + + info.Reference = target; + info.Read(reader); + return true; + } + + /// + /// Reads one packet from NetDataReader and calls OnReceive delegate + /// + /// NetDataReader with packet + /// Argument that passed to OnReceivedEvent + public void ReadPacket(NetDataReader reader, object userData) + { + var info = ReadInfo(reader); + if (info.CreatorFunc != null) + { + info.Reference = info.CreatorFunc(); + } + info.Read(reader); + info.OnReceive(info.Reference, userData); + } + + /// + /// Register and subscribe to packet receive event + /// + /// event that will be called when packet deserialized with ReadPacket method + /// Method that constructs packet intead of slow Activator.CreateInstance + public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + { + var info = RegisterInternal(); + info.CreatorFunc = () => packetConstructor(); + info.OnReceive = (o, userData) => { onReceive((T)o); }; + } + + /// + /// Register packet type for direct reading (ReadKnownPacket) + /// + /// Method that constructs packet intead of slow Activator.CreateInstance + public void Register(Func packetConstructor = null) where T : class, new() + { + var info = RegisterInternal(); + if (packetConstructor != null) + { + info.CreatorFunc = () => packetConstructor(); + } + info.OnReceive = (o, userData) => { }; + } + + /// + /// Register and subscribe to packet receive event (with userData) + /// + /// event that will be called when packet deserialized with ReadPacket method + /// Method that constructs packet intead of slow Activator.CreateInstance + public void Subscribe(Action onReceive, Func packetConstructor) where T : class, new() + { + var info = RegisterInternal(); + info.CreatorFunc = () => packetConstructor(); + info.OnReceive = (o, userData) => { onReceive((T)o, (TUserData)userData); }; + } + + /// + /// Register and subscribe to packet receive event + /// This metod will overwrite last received packet class on receive (less garbage) + /// + /// event that will be called when packet deserialized with ReadPacket method + public void SubscribeReusable(Action onReceive) where T : class, new() + { + var info = RegisterInternal(); + info.Reference = new T(); + info.OnReceive = (o, userData) => { onReceive((T)o); }; + } + + /// + /// Register and subscribe to packet receive event + /// This metod will overwrite last received packet class on receive (less garbage) + /// + /// event that will be called when packet deserialized with ReadPacket method + public void SubscribeReusable(Action onReceive) where T : class, new() + { + var info = RegisterInternal(); + info.Reference = new T(); + info.OnReceive = (o, userData) => { onReceive((T)o, (TUserData)userData); }; + } + + /// + /// Serialize struct to NetDataWriter (fast) + /// + /// Serialization target NetDataWriter + /// Struct to serialize + public void Serialize(NetDataWriter writer, T obj) where T : class, new() + { + var info = RegisterInternal(); + _hasher.WriteHash(info.Hash, writer); + info.Write(writer, obj); + } + + /// + /// Serialize struct to byte array + /// + /// Struct to serialize + /// byte array with serialized data + public byte[] Serialize(T obj) where T : class, new() + { + _writer.Reset(); + Serialize(_writer, obj); + return _writer.CopyData(); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs.meta new file mode 100644 index 0000000..363b33c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSerializer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e26db3a8188754e07b42db31f32e20f7 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs new file mode 100644 index 0000000..608d98c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs @@ -0,0 +1,455 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +#if !WINRT || UNITY_EDITOR +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class NetSocket + { + private Socket _udpSocketv4; + private Socket _udpSocketv6; + private NetEndPoint _localEndPoint; + private Thread _threadv4; + private Thread _threadv6; + private bool _running; + private readonly NetManager.OnMessageReceived _onMessageReceived; + + private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse (NetConstants.MulticastGroupIPv6); + private static readonly bool IPv6Support; + private const int SocketReceivePollTime = 100000; + private const int SocketSendPollTime = 5000; + + public NetEndPoint LocalEndPoint + { + get { return _localEndPoint; } + } + + static NetSocket() + { + try + { + //Unity3d .NET 2.0 throws exception. + // IPv6Support = Socket.OSSupportsIPv6; + IPv6Support = false; + } + catch + { + IPv6Support = false; + } + } + + public NetSocket(NetManager.OnMessageReceived onMessageReceived) + { + _onMessageReceived = onMessageReceived; + } + + private void ReceiveLogic(object state) + { + Socket socket = (Socket)state; + EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); + NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint); + byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit]; + + while (_running) + { + //wait for data + if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead)) + { + continue; + } + + int result; + + //Reading data + try + { + result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint); + if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint)) + { + bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint); + } + } + catch (SocketException ex) + { + if (ex.SocketErrorCode == SocketError.ConnectionReset || + ex.SocketErrorCode == SocketError.MessageSize) + { + //10040 - message too long + //10054 - remote close (not error) + //Just UDP + NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString() ); + continue; + } + NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString()); + _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint); + continue; + } + + //All ok! + NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Recieved data from {0}, result: {1}", bufferNetEndPoint.ToString(), result); + _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint); + } + } + + public bool Bind(int port, bool reuseAddress) + { + _udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + _udpSocketv4.Blocking = false; + _udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize; + _udpSocketv4.SendBufferSize = NetConstants.SocketBufferSize; + _udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, NetConstants.SocketTTL); + if(reuseAddress) + _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); +#if !NETCORE + _udpSocketv4.DontFragment = true; +#endif + + try + { + _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); + } + catch (SocketException e) + { + NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString()); + } + + if (!BindSocket(_udpSocketv4, new IPEndPoint(IPAddress.Any, port))) + { + return false; + } + _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv4.LocalEndPoint); + + _running = true; + _threadv4 = new Thread(ReceiveLogic); + _threadv4.Name = "SocketThreadv4(" + port + ")"; + _threadv4.IsBackground = true; + _threadv4.Start(_udpSocketv4); + + //Check IPv6 support + if (!IPv6Support) + return true; + + //Use one port for two sockets + port = _localEndPoint.Port; + + _udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); + _udpSocketv6.Blocking = false; + _udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize; + _udpSocketv6.SendBufferSize = NetConstants.SocketBufferSize; + if (reuseAddress) + _udpSocketv6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + + if (BindSocket(_udpSocketv6, new IPEndPoint(IPAddress.IPv6Any, port))) + { + _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv6.LocalEndPoint); + + try + { + _udpSocketv6.SetSocketOption( + SocketOptionLevel.IPv6, + SocketOptionName.AddMembership, + new IPv6MulticastOption(MulticastAddressV6)); + } + catch(Exception) + { + // Unity3d throws exception - ignored + } + + _threadv6 = new Thread(ReceiveLogic); + _threadv6.Name = "SocketThreadv6(" + port + ")"; + _threadv6.IsBackground = true; + _threadv6.Start(_udpSocketv6); + } + + return true; + } + + private bool BindSocket(Socket socket, IPEndPoint ep) + { + try + { + socket.Bind(ep); + NetUtils.DebugWrite(ConsoleColor.Blue, "[B]Succesfully binded to port: {0}", ((IPEndPoint)socket.LocalEndPoint).Port); + } + catch (SocketException ex) + { + NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString()); + //ODO: very temporary hack for iOS (Unity3D) + if (ex.SocketErrorCode == SocketError.AddressFamilyNotSupported) + { + return true; + } + return false; + } + return true; + } + + public bool SendBroadcast(byte[] data, int offset, int size, int port) + { + try + { + int result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port)); + if (result <= 0) + return false; + if (IPv6Support) + { + result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port)); + if (result <= 0) + return false; + } + } + catch (Exception ex) + { + NetUtils.DebugWriteError("[S][MCAST]" + ex); + return false; + } + return true; + } + + public int SendTo(byte[] data, int offset, int size, NetEndPoint remoteEndPoint, ref int errorCode) + { + try + { + int result = 0; + if (remoteEndPoint.EndPoint.AddressFamily == AddressFamily.InterNetwork) + { + if (!_udpSocketv4.Poll(SocketSendPollTime, SelectMode.SelectWrite)) + return -1; + result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint); + } + else if(IPv6Support) + { + if (!_udpSocketv6.Poll(SocketSendPollTime, SelectMode.SelectWrite)) + return -1; + result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint); + } + + NetUtils.DebugWrite(ConsoleColor.Blue, "[S]Send packet to {0}, result: {1}", remoteEndPoint.EndPoint, result); + return result; + } + catch (SocketException ex) + { + if (ex.SocketErrorCode != SocketError.MessageSize) + { + NetUtils.DebugWriteError("[S]" + ex); + } + + errorCode = (int)ex.SocketErrorCode; + return -1; + } + catch (Exception ex) + { + NetUtils.DebugWriteError("[S]" + ex); + return -1; + } + } + + private void CloseSocket(Socket s) + { +#if NETCORE + s.Dispose(); +#else + s.Close(); +#endif + } + + public void Close() + { + _running = false; + + //Close IPv4 + if (Thread.CurrentThread != _threadv4) + { + _threadv4.Join(); + } + _threadv4 = null; + if (_udpSocketv4 != null) + { + CloseSocket(_udpSocketv4); + _udpSocketv4 = null; + } + + //No ipv6 + if (_udpSocketv6 == null) + return; + + //Close IPv6 + if (Thread.CurrentThread != _threadv6) + { + _threadv6.Join(); + } + _threadv6 = null; + if (_udpSocketv6 != null) + { + CloseSocket(_udpSocketv6); + _udpSocketv6 = null; + } + } + } +} +#else +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices.WindowsRuntime; +using System.Threading; +using System.Threading.Tasks; +using Windows.Networking; +using Windows.Networking.Sockets; +using Windows.Storage.Streams; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class NetSocket + { + private DatagramSocket _datagramSocket; + private readonly Dictionary _peers = new Dictionary(); + private readonly NetManager.OnMessageReceived _onMessageReceived; + private readonly byte[] _byteBuffer = new byte[NetConstants.PacketSizeLimit]; + private readonly IBuffer _buffer; + private NetEndPoint _bufferEndPoint; + private NetEndPoint _localEndPoint; + private static readonly HostName BroadcastAddress = new HostName("255.255.255.255"); + private static readonly HostName MulticastAddressV6 = new HostName(NetConstants.MulticastGroupIPv6); + + public NetEndPoint LocalEndPoint + { + get { return _localEndPoint; } + } + + public NetSocket(NetManager.OnMessageReceived onMessageReceived) + { + _onMessageReceived = onMessageReceived; + _buffer = _byteBuffer.AsBuffer(); + } + + private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) + { + var result = args.GetDataStream().ReadAsync(_buffer, _buffer.Capacity, InputStreamOptions.None).AsTask().Result; + int length = (int)result.Length; + if (length <= 0) + return; + + if (_bufferEndPoint == null || + !_bufferEndPoint.HostName.IsEqual(args.RemoteAddress) || + !_bufferEndPoint.PortStr.Equals(args.RemotePort)) + { + _bufferEndPoint = new NetEndPoint(args.RemoteAddress, args.RemotePort); + } + _onMessageReceived(_byteBuffer, length, 0, _bufferEndPoint); + } + + public bool Bind(int port, bool reuseAddress) + { + _datagramSocket = new DatagramSocket(); + _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize; + _datagramSocket.Control.DontFragment = true; + _datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL; + _datagramSocket.MessageReceived += OnMessageReceived; + + try + { + _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait(); + _datagramSocket.JoinMulticastGroup(MulticastAddressV6); + _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort); + } + catch (Exception ex) + { + NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString()); + return false; + } + return true; + } + + public bool SendBroadcast(byte[] data, int offset, int size, int port) + { + var portString = port.ToString(); + try + { + var outputStream = + _datagramSocket.GetOutputStreamAsync(BroadcastAddress, portString) + .AsTask() + .Result; + var writer = outputStream.AsStreamForWrite(); + writer.Write(data, offset, size); + writer.Flush(); + + outputStream = + _datagramSocket.GetOutputStreamAsync(MulticastAddressV6, portString) + .AsTask() + .Result; + writer = outputStream.AsStreamForWrite(); + writer.Write(data, offset, size); + writer.Flush(); + } + catch (Exception ex) + { + NetUtils.DebugWriteError("[S][MCAST]" + ex); + return false; + } + return true; + } + + public int SendTo(byte[] data, int offset, int length, NetEndPoint remoteEndPoint, ref int errorCode) + { + Task task = null; + try + { + IOutputStream writer; + if (!_peers.TryGetValue(remoteEndPoint, out writer)) + { + writer = + _datagramSocket.GetOutputStreamAsync(remoteEndPoint.HostName, remoteEndPoint.PortStr) + .AsTask() + .Result; + _peers.Add(remoteEndPoint, writer); + } + + task = writer.WriteAsync(data.AsBuffer(offset, length)).AsTask(); + return (int)task.Result; + } + catch (Exception ex) + { + if (task?.Exception?.InnerExceptions != null) + { + ex = task.Exception.InnerException; + } + var errorStatus = SocketError.GetStatus(ex.HResult); + switch (errorStatus) + { + case SocketErrorStatus.MessageTooLong: + errorCode = 10040; + break; + default: + errorCode = (int)errorStatus; + NetUtils.DebugWriteError("[S " + errorStatus + "(" + errorCode + ")]" + ex); + break; + } + + return -1; + } + } + + internal void RemovePeer(NetEndPoint ep) + { + _peers.Remove(ep); + } + + public void Close() + { + _datagramSocket.Dispose(); + _datagramSocket = null; + ClearPeers(); + } + + internal void ClearPeers() + { + _peers.Clear(); + } + } +} +#endif +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs.meta new file mode 100644 index 0000000..7661576 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetSocket.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c517b909a8c704eae91d4eccf06bc8a1 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs new file mode 100644 index 0000000..cdd433f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs @@ -0,0 +1,97 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +#if WINRT && !UNITY_EDITOR +#define USE_WINRT +#endif + +using System; +using System.Threading; + +#if USE_WINRT +using Windows.Foundation; +using Windows.System.Threading; +using Windows.System.Threading.Core; +#endif + +namespace FlyingWormConsole3.LiteNetLib +{ + public sealed class NetThread + { +#if USE_WINRT + private readonly ManualResetEvent _updateWaiter = new ManualResetEvent(false); + private readonly ManualResetEvent _joinWaiter = new ManualResetEvent(false); +#else + private Thread _thread; +#endif + + private readonly Action _callback; + + public int SleepTime; + private bool _running; + private readonly string _name; + + public bool IsRunning + { + get { return _running; } + } + + public NetThread(string name, int sleepTime, Action callback) + { + _callback = callback; + SleepTime = sleepTime; + _name = name; + } + + public void Start() + { + if (_running) + return; + _running = true; +#if USE_WINRT + var thread = new PreallocatedWorkItem(ThreadLogic, WorkItemPriority.Normal, WorkItemOptions.TimeSliced); + thread.RunAsync().AsTask(); +#else + _thread = new Thread(ThreadLogic) + { + Name = _name, + IsBackground = true + }; + _thread.Start(); +#endif + } + + public void Stop() + { + if (!_running) + return; + _running = false; + +#if USE_WINRT + _joinWaiter.WaitOne(); +#else + _thread.Join(); +#endif + } + +#if USE_WINRT + private void ThreadLogic(IAsyncAction action) + { + while (_running) + { + _callback(); + _updateWaiter.WaitOne(SleepTime); + } + _joinWaiter.Set(); + } +#else + private void ThreadLogic() + { + while (_running) + { + _callback(); + Thread.Sleep(SleepTime); + } + } +#endif + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs.meta new file mode 100644 index 0000000..af275bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetThread.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d1928476aac6242d29fab6849f102494 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs new file mode 100644 index 0000000..c6d3675 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs @@ -0,0 +1,219 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +#define UNITY + +using System; +using System.Collections.Generic; +using System.Diagnostics; +#if WINRT && !UNITY_EDITOR +using Windows.Networking; +using Windows.Networking.Connectivity; +#else +using System.Net; +using System.Net.Sockets; +using System.Net.NetworkInformation; +#endif + +namespace FlyingWormConsole3.LiteNetLib +{ +#if WINRT && !UNITY_EDITOR + public enum ConsoleColor + { + Gray, + Yellow, + Cyan, + DarkCyan, + DarkGreen, + Blue, + DarkRed, + Red, + Green, + DarkYellow + } +#endif + + [Flags] + public enum LocalAddrType + { + IPv4 = 1, + IPv6 = 2, + All = 3 + } + + public static class NetUtils + { + internal static int RelativeSequenceNumber(int number, int expected) + { + return (number - expected + NetConstants.MaxSequence + NetConstants.HalfMaxSequence) % NetConstants.MaxSequence - NetConstants.HalfMaxSequence; + } + + internal static int GetDividedPacketsCount(int size, int mtu) + { + return (size / mtu) + (size % mtu == 0 ? 0 : 1); + } + + public static void PrintInterfaceInfos() + { +#if !WINRT || UNITY_EDITOR + DebugWriteForce(ConsoleColor.Green, "IPv6Support: {0}", Socket.OSSupportsIPv6); + try + { + foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) + { + foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) + { + if (ip.Address.AddressFamily == AddressFamily.InterNetwork || + ip.Address.AddressFamily == AddressFamily.InterNetworkV6) + { + DebugWriteForce( + ConsoleColor.Green, + "Interface: {0}, Type: {1}, Ip: {2}, OpStatus: {3}", + ni.Name, + ni.NetworkInterfaceType.ToString(), + ip.Address.ToString(), + ni.OperationalStatus.ToString()); + } + } + } + } + catch (Exception e) + { + DebugWriteForce(ConsoleColor.Red, "Error while getting interface infos: {0}", e.ToString()); + } +#endif + } + + public static void GetLocalIpList(List targetList, LocalAddrType addrType) + { + bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; + bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; +#if WINRT && !UNITY_EDITOR + foreach (HostName localHostName in NetworkInformation.GetHostNames()) + { + if (localHostName.IPInformation != null && + ((ipv4 && localHostName.Type == HostNameType.Ipv4) || + (ipv6 && localHostName.Type == HostNameType.Ipv6))) + { + targetList.Add(localHostName.ToString()); + } + } +#else + try + { + foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) + { + //Skip loopback + if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) + continue; + + var ipProps = ni.GetIPProperties(); + + //Skip address without gateway + if (ipProps.GatewayAddresses.Count == 0) + continue; + + foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) + { + var address = ip.Address; + if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || + (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) + targetList.Add(address.ToString()); + } + } + } + catch + { + //ignored + } + + //Fallback mode (unity android) + if (targetList.Count == 0) + { +#if NETCORE + var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName()); + hostTask.Wait(); + var host = hostTask.Result; +#else + var host = Dns.GetHostEntry(Dns.GetHostName()); +#endif + foreach (IPAddress ip in host.AddressList) + { + if((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || + (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) + targetList.Add(ip.ToString()); + } + } +#endif + if (targetList.Count == 0) + { + if(ipv4) + targetList.Add("127.0.0.1"); + if(ipv6) + targetList.Add("::1"); + } + } + + private static readonly List IpList = new List(); + public static string GetLocalIp(LocalAddrType addrType) + { + lock (IpList) + { + IpList.Clear(); + GetLocalIpList(IpList, addrType); + return IpList.Count == 0 ? string.Empty : IpList[0]; + } + } + + private static readonly object DebugLogLock = new object(); + + private static void DebugWriteLogic(ConsoleColor color, string str, params object[] args) + { + lock (DebugLogLock) + { + + if (NetDebug.Logger == null) + { +#if UNITY +#if !UNITY_4_0 + UnityEngine.Debug.LogFormat(str, args); +#endif +#elif WINRT + Debug.WriteLine(str, args); +#else + Console.ForegroundColor = color; + Console.WriteLine(str, args); + Console.ForegroundColor = ConsoleColor.Gray; +#endif + } + else + { + NetDebug.Logger.WriteNet(color, str, args); + } + } + } + + [Conditional("DEBUG_MESSAGES")] + internal static void DebugWrite(string str, params object[] args) + { + DebugWriteLogic(ConsoleColor.DarkGreen, str, args); + } + + [Conditional("DEBUG_MESSAGES")] + internal static void DebugWrite(ConsoleColor color, string str, params object[] args) + { + DebugWriteLogic(color, str, args); + } + + [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] + internal static void DebugWriteForce(ConsoleColor color, string str, params object[] args) + { + DebugWriteLogic(color, str, args); + } + + [Conditional("DEBUG_MESSAGES"), Conditional("DEBUG")] + internal static void DebugWriteError(string str, params object[] args) + { + DebugWriteLogic(ConsoleColor.Red, str, args); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs.meta new file mode 100644 index 0000000..8f96878 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NetUtils.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0b27974b2b4714973a8f5a3ea4036677 +timeCreated: 1497976517 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs new file mode 100644 index 0000000..83b5d86 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs @@ -0,0 +1,59 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Threading; + +namespace FlyingWormConsole3.LiteNetLib +{ + public class NtpSyncModule + { + public DateTime? SyncedTime { get; private set; } + private readonly NetSocket _socket; + private readonly NetEndPoint _ntpEndPoint; + private readonly ManualResetEvent _waiter = new ManualResetEvent(false); + + public NtpSyncModule(string ntpServer) + { + _ntpEndPoint = new NetEndPoint(ntpServer, 123); + _socket = new NetSocket(OnMessageReceived); + _socket.Bind(0, false); + SyncedTime = null; + } + + private void OnMessageReceived(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint) + { + if (errorCode != 0) + { + _waiter.Set(); + return; + } + + ulong intPart = (ulong)data[40] << 24 | (ulong)data[41] << 16 | (ulong)data[42] << 8 | (ulong)data[43]; + ulong fractPart = (ulong)data[44] << 24 | (ulong)data[45] << 16 | (ulong)data[46] << 8 | (ulong)data[47]; + + var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); + SyncedTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds); + + _waiter.Set(); + } + + public void GetNetworkTime() + { + if (SyncedTime != null) + return; + + var ntpData = new byte[48]; + //LeapIndicator = 0 (no warning) + //VersionNum = 3 + //Mode = 3 (Client Mode) + ntpData[0] = 0x1B; + + //send + int errorCode = 0; + _socket.SendTo(ntpData, 0, ntpData.Length, _ntpEndPoint, ref errorCode); + + if(errorCode == 0) + _waiter.WaitOne(1000); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs.meta new file mode 100644 index 0000000..02cf492 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/NtpSyncModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 91e481bf657774228854ba5923470b26 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs new file mode 100644 index 0000000..3d4a1ab --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs @@ -0,0 +1,375 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System; +using System.Collections.Generic; +using System.Threading; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class ReliableChannel + { + private class PendingPacket + { + public NetPacket Packet; + public DateTime? TimeStamp; + + public NetPacket GetAndClear() + { + var packet = Packet; + Packet = null; + TimeStamp = null; + return packet; + } + } + + private readonly Queue _outgoingPackets; + private readonly bool[] _outgoingAcks; //for send acks + private readonly PendingPacket[] _pendingPackets; //for unacked packets and duplicates + private readonly NetPacket[] _receivedPackets; //for order + private readonly bool[] _earlyReceived; //for unordered + + private int _localSeqence; + private int _remoteSequence; + private int _localWindowStart; + private int _remoteWindowStart; + + private readonly NetPeer _peer; + private bool _mustSendAcks; + + private readonly bool _ordered; + private readonly int _windowSize; + private const int BitsInByte = 8; + + private int _queueIndex; + + public int PacketsInQueue + { + get { return _outgoingPackets.Count; } + } + + public ReliableChannel(NetPeer peer, bool ordered, int windowSize) + { + _windowSize = windowSize; + _peer = peer; + _ordered = ordered; + + _outgoingPackets = new Queue(_windowSize); + + _outgoingAcks = new bool[_windowSize]; + _pendingPackets = new PendingPacket[_windowSize]; + for (int i = 0; i < _pendingPackets.Length; i++) + { + _pendingPackets[i] = new PendingPacket(); + } + + if (_ordered) + _receivedPackets = new NetPacket[_windowSize]; + else + _earlyReceived = new bool[_windowSize]; + + _localWindowStart = 0; + _localSeqence = 0; + _remoteSequence = 0; + _remoteWindowStart = 0; + } + + //ProcessAck in packet + public void ProcessAck(NetPacket packet) + { + int validPacketSize = (_windowSize - 1) / BitsInByte + 1 + NetConstants.SequencedHeaderSize; + if (packet.Size != validPacketSize) + { + NetUtils.DebugWrite("[PA]Invalid acks packet size"); + return; + } + + ushort ackWindowStart = packet.Sequence; + if (ackWindowStart > NetConstants.MaxSequence) + { + NetUtils.DebugWrite("[PA]Bad window start"); + return; + } + + //check relevance + if (NetUtils.RelativeSequenceNumber(ackWindowStart, _localWindowStart) <= -_windowSize) + { + NetUtils.DebugWrite("[PA]Old acks"); + return; + } + + byte[] acksData = packet.RawData; + NetUtils.DebugWrite("[PA]AcksStart: {0}", ackWindowStart); + int startByte = NetConstants.SequencedHeaderSize; + + Monitor.Enter(_pendingPackets); + for (int i = 0; i < _windowSize; i++) + { + int ackSequence = (ackWindowStart + i) % NetConstants.MaxSequence; + if (NetUtils.RelativeSequenceNumber(ackSequence, _localWindowStart) < 0) + { + //NetUtils.DebugWrite(ConsoleColor.Cyan, "[PA] SKIP OLD: " + ackSequence); + //Skip old ack + continue; + } + + int currentByte = startByte + i / BitsInByte; + int currentBit = i % BitsInByte; + + if ((acksData[currentByte] & (1 << currentBit)) == 0) + { + //NetUtils.DebugWrite(ConsoleColor.Cyan, "[PA] SKIP FALSE: " + ackSequence); + //Skip false ack + continue; + } + + if (ackSequence == _localWindowStart) + { + //Move window + _localWindowStart = (_localWindowStart + 1) % NetConstants.MaxSequence; + } + + NetPacket removed = _pendingPackets[ackSequence % _windowSize].GetAndClear(); + if (removed != null) + { + _peer.Recycle(removed); + + NetUtils.DebugWrite("[PA]Removing reliableInOrder ack: {0} - true", ackSequence); + } + else + { + NetUtils.DebugWrite("[PA]Removing reliableInOrder ack: {0} - false", ackSequence); + } + } + Monitor.Exit(_pendingPackets); + } + + public void AddToQueue(NetPacket packet) + { + lock (_outgoingPackets) + { + _outgoingPackets.Enqueue(packet); + } + } + + private void ProcessQueuedPackets() + { + //get packets from queue + while (_outgoingPackets.Count > 0) + { + int relate = NetUtils.RelativeSequenceNumber(_localSeqence, _localWindowStart); + if (relate < _windowSize) + { + NetPacket packet; + lock (_outgoingPackets) + { + packet = _outgoingPackets.Dequeue(); + } + packet.Sequence = (ushort)_localSeqence; + _pendingPackets[_localSeqence % _windowSize].Packet = packet; + _localSeqence = (_localSeqence + 1) % NetConstants.MaxSequence; + } + else //Queue filled + { + break; + } + } + } + + public bool SendNextPacket() + { + //check sending acks + DateTime currentTime = DateTime.UtcNow; + + Monitor.Enter(_pendingPackets); + ProcessQueuedPackets(); + + //send + PendingPacket currentPacket; + bool packetFound = false; + int startQueueIndex = _queueIndex; + do + { + currentPacket = _pendingPackets[_queueIndex]; + if (currentPacket.Packet != null) + { + //check send time + if(currentPacket.TimeStamp.HasValue) + { + double packetHoldTime = (currentTime - currentPacket.TimeStamp.Value).TotalMilliseconds; + if (packetHoldTime > _peer.ResendDelay) + { + NetUtils.DebugWrite("[RC]Resend: {0} > {1}", (int)packetHoldTime, _peer.ResendDelay); + packetFound = true; + } + } + else //Never sended + { + packetFound = true; + } + } + + _queueIndex = (_queueIndex + 1) % _windowSize; + } while (!packetFound && _queueIndex != startQueueIndex); + + if (packetFound) + { + currentPacket.TimeStamp = DateTime.UtcNow; + _peer.SendRawData(currentPacket.Packet); + NetUtils.DebugWrite("[RR]Sended"); + } + Monitor.Exit(_pendingPackets); + return packetFound; + } + + public void SendAcks() + { + if (!_mustSendAcks) + return; + _mustSendAcks = false; + + NetUtils.DebugWrite("[RR]SendAcks"); + + //Init packet + int bytesCount = (_windowSize - 1) / BitsInByte + 1; + PacketProperty property = _ordered ? PacketProperty.AckReliableOrdered : PacketProperty.AckReliable; + var acksPacket = _peer.GetPacketFromPool(property, bytesCount); + + //For quick access + byte[] data = acksPacket.RawData; //window start + acks size + + //Put window start + Monitor.Enter(_outgoingAcks); + acksPacket.Sequence = (ushort)_remoteWindowStart; + + //Put acks + int startAckIndex = _remoteWindowStart % _windowSize; + int currentAckIndex = startAckIndex; + int currentBit = 0; + int currentByte = NetConstants.SequencedHeaderSize; + do + { + if (_outgoingAcks[currentAckIndex]) + { + data[currentByte] |= (byte)(1 << currentBit); + } + + currentBit++; + if (currentBit == BitsInByte) + { + currentByte++; + currentBit = 0; + } + currentAckIndex = (currentAckIndex + 1) % _windowSize; + } while (currentAckIndex != startAckIndex); + Monitor.Exit(_outgoingAcks); + + _peer.SendRawData(acksPacket); + _peer.Recycle(acksPacket); + } + + //Process incoming packet + public void ProcessPacket(NetPacket packet) + { + if (packet.Sequence >= NetConstants.MaxSequence) + { + NetUtils.DebugWrite("[RR]Bad sequence"); + return; + } + + int relate = NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteWindowStart); + int relateSeq = NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteSequence); + + if (relateSeq > _windowSize) + { + NetUtils.DebugWrite("[RR]Bad sequence"); + return; + } + + //Drop bad packets + if(relate < 0) + { + //Too old packet doesn't ack + NetUtils.DebugWrite("[RR]ReliableInOrder too old"); + return; + } + if (relate >= _windowSize * 2) + { + //Some very new packet + NetUtils.DebugWrite("[RR]ReliableInOrder too new"); + return; + } + + //If very new - move window + Monitor.Enter(_outgoingAcks); + if (relate >= _windowSize) + { + //New window position + int newWindowStart = (_remoteWindowStart + relate - _windowSize + 1) % NetConstants.MaxSequence; + + //Clean old data + while (_remoteWindowStart != newWindowStart) + { + _outgoingAcks[_remoteWindowStart % _windowSize] = false; + _remoteWindowStart = (_remoteWindowStart + 1) % NetConstants.MaxSequence; + } + } + + //Final stage - process valid packet + //trigger acks send + _mustSendAcks = true; + + if (_outgoingAcks[packet.Sequence % _windowSize]) + { + NetUtils.DebugWrite("[RR]ReliableInOrder duplicate"); + Monitor.Exit(_outgoingAcks); + return; + } + + //save ack + _outgoingAcks[packet.Sequence % _windowSize] = true; + Monitor.Exit(_outgoingAcks); + + //detailed check + if (packet.Sequence == _remoteSequence) + { + NetUtils.DebugWrite("[RR]ReliableInOrder packet succes"); + _peer.AddIncomingPacket(packet); + _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; + + if (_ordered) + { + NetPacket p; + while ( (p = _receivedPackets[_remoteSequence % _windowSize]) != null) + { + //process holded packet + _receivedPackets[_remoteSequence % _windowSize] = null; + _peer.AddIncomingPacket(p); + _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; + } + } + else + { + while (_earlyReceived[_remoteSequence % _windowSize]) + { + //process early packet + _earlyReceived[_remoteSequence % _windowSize] = false; + _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; + } + } + + return; + } + + //holded packet + if (_ordered) + { + _receivedPackets[packet.Sequence % _windowSize] = packet; + } + else + { + _earlyReceived[packet.Sequence % _windowSize] = true; + _peer.AddIncomingPacket(packet); + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs.meta new file mode 100644 index 0000000..04a8ce2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/ReliableChannel.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 516bd901eb62f4bb391ef541f9effdec +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix new file mode 100644 index 0000000..b594d17 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix @@ -0,0 +1,4 @@ +for file in *.cs; do + echo "#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA" | cat - $file > tempfile && mv tempfile $file + echo '#endif' >> "$file" +done \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix.meta new file mode 100644 index 0000000..810a23a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/RemoteFix.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a9f1f24482ff84a25a1188dd49ec4d86 +timeCreated: 1498001160 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs new file mode 100644 index 0000000..985ca1c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs @@ -0,0 +1,53 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System.Collections.Generic; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class SequencedChannel + { + private ushort _localSequence; + private ushort _remoteSequence; + private readonly Queue _outgoingPackets; + private readonly NetPeer _peer; + + public SequencedChannel(NetPeer peer) + { + _outgoingPackets = new Queue(); + _peer = peer; + } + + public void AddToQueue(NetPacket packet) + { + lock (_outgoingPackets) + { + _outgoingPackets.Enqueue(packet); + } + } + + public bool SendNextPacket() + { + NetPacket packet; + lock (_outgoingPackets) + { + if (_outgoingPackets.Count == 0) + return false; + packet = _outgoingPackets.Dequeue(); + } + _localSequence++; + packet.Sequence = _localSequence; + _peer.SendRawData(packet); + _peer.Recycle(packet); + return true; + } + + public void ProcessPacket(NetPacket packet) + { + if (NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteSequence) > 0) + { + _remoteSequence = packet.Sequence; + _peer.AddIncomingPacket(packet); + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs.meta new file mode 100644 index 0000000..1eb5158 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SequencedChannel.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 84bbbc6c6e45c4287917fc944650e4af +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs new file mode 100644 index 0000000..1a1ffa1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs @@ -0,0 +1,40 @@ +#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA +using System.Collections.Generic; + +namespace FlyingWormConsole3.LiteNetLib +{ + internal sealed class SimpleChannel + { + private readonly Queue _outgoingPackets; + private readonly NetPeer _peer; + + public SimpleChannel(NetPeer peer) + { + _outgoingPackets = new Queue(); + _peer = peer; + } + + public void AddToQueue(NetPacket packet) + { + lock (_outgoingPackets) + { + _outgoingPackets.Enqueue(packet); + } + } + + public bool SendNextPacket() + { + NetPacket packet; + lock (_outgoingPackets) + { + if (_outgoingPackets.Count == 0) + return false; + packet = _outgoingPackets.Dequeue(); + } + _peer.SendRawData(packet); + _peer.Recycle(packet); + return true; + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs.meta b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs.meta new file mode 100644 index 0000000..a2cb11c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/Remote/LiteNetLib/SimpleChannel.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6b4cdb673a0094d438a802844a8cc794 +timeCreated: 1497976518 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/ver@3.964.txt b/Assets/CrazyZoo/Plugins/ConsolePro/ver@3.964.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/ConsolePro/ver@3.964.txt.meta b/Assets/CrazyZoo/Plugins/ConsolePro/ver@3.964.txt.meta new file mode 100644 index 0000000..7e4896c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/ConsolePro/ver@3.964.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 90979fd73276eab448e2785362667c6a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant.meta b/Assets/CrazyZoo/Plugins/Demigiant.meta new file mode 100644 index 0000000..c230bfd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 22ef105f20eb93b41ade947d92a380c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween.meta new file mode 100644 index 0000000..cbebc39 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween.meta @@ -0,0 +1,21 @@ +fileFormatVersion: 2 +guid: a50bd9a009c8dfc4ebd88cc8101225a7 +labels: +- Tween +- Tweening +- Animation +- HOTween +- Paths +- iTween +- DFTween +- LeanTween +- Ease +- Easing +- Shake +- Punch +- 2DToolkit +- TextMeshPro +- Text +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML new file mode 100644 index 0000000..11e9215 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML @@ -0,0 +1,2769 @@ + + + + DOTween + + + + + Types of autoPlay behaviours + + + + No tween is automatically played + + + Only Sequences are automatically played + + + Only Tweeners are automatically played + + + All tweens are automatically played + + + + What axis to constrain in case of Vector tweens + + + + Called the first time the tween is set in a playing state, after any eventual delay + + + + Used in place of System.Func, which is not available in mscorlib. + + + + + Used in place of System.Action. + + + + + Public so it can be used by lose scripts related to DOTween (like DOTweenAnimation) + + + + + Used to separate DOTween class from the MonoBehaviour instance (in order to use static constructors on DOTween). + Contains all instance-based methods + + + + Used internally inside Unity Editor, as a trick to update DOTween's inspector at every frame + + + + Directly sets the current max capacity of Tweeners and Sequences + (meaning how many Tweeners and Sequences can be running at the same time), + so that DOTween doesn't need to automatically increase them in case the max is reached + (which might lead to hiccups when that happens). + Sequences capacity must be less or equal to Tweeners capacity + (if you pass a low Tweener capacity it will be automatically increased to match the Sequence's). + Beware: use this method only when there are no tweens running. + + Max Tweeners capacity. + Default: 200 + Max Sequences capacity. + Default: 50 + + + + This class contains a C# port of the easing equations created by Robert Penner (http://robertpenner.com/easing). + + + + + Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + + + Current time (in frames or seconds). + + + Expected easing duration (in frames or seconds). + + Unused: here to keep same delegate for all ease types. + Unused: here to keep same delegate for all ease types. + + The eased value. + + + + + Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + + + Current time (in frames or seconds). + + + Expected easing duration (in frames or seconds). + + Unused: here to keep same delegate for all ease types. + Unused: here to keep same delegate for all ease types. + + The eased value. + + + + + Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + + + Current time (in frames or seconds). + + + Expected easing duration (in frames or seconds). + + Unused: here to keep same delegate for all ease types. + Unused: here to keep same delegate for all ease types. + + The eased value. + + + + + Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected + + + + + Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected + + + + + Used to interpret AnimationCurves as eases. + Public so it can be used by external ease factories + + + + + Behaviour in case a tween nested inside a Sequence fails + + + + If the Sequence contains other elements, kill the failed tween but preserve the rest + + + Kill the whole Sequence + + + + Additional notices passed to plugins when updating. + Public so it can be used by custom plugins. Internally, only PathPlugin uses it + + + + + None + + + + + Lets the plugin know that we restarted or rewinded + + + + + OnRewind callback behaviour (can only be set via DOTween's Utility Panel) + + + + + When calling Rewind or PlayBackwards/SmoothRewind, OnRewind callbacks will be fired only if the tween isn't already rewinded + + + + + When calling Rewind, OnRewind callbacks will always be fired, even if the tween is already rewinded. + When calling PlayBackwards/SmoothRewind instead, OnRewind callbacks will be fired only if the tween isn't already rewinded + + + + + When calling Rewind or PlayBackwards/SmoothRewind, OnRewind callbacks will always be fired, even if the tween is already rewinded + + + + + Public only so custom shortcuts can access some of these methods + + + + + INTERNAL: used by DO shortcuts and Modules to set special startup mode + + + + + INTERNAL: used by DO shortcuts and Modules to set the tween as blendable + + + + + INTERNAL: used by DO shortcuts and Modules to prevent a tween from using a From setup even if passed + + + + + Used to dispatch commands that need to be captured externally, usually by Modules + + + + + Returns a Vector3 with z = 0 + + + + + Returns the 2D angle between two vectors + + + + + Uses approximate equality on each axis instead of Unity's Vector3 equality, + because the latter fails (in some cases) when assigning a Vector3 to a transform.position and then checking it. + + + + + Looks for the type within all possible project assembly names + + + + NO-GC METHOD: changes the start value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new start value + If bigger than 0 applies it as the new tween duration + + + NO-GC METHOD: changes the end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new end value + If TRUE the start value will become the current target's value, otherwise it will stay the same + + + NO-GC METHOD: changes the end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new end value + If bigger than 0 applies it as the new tween duration + If TRUE the start value will become the current target's value, otherwise it will stay the same + + + NO-GC METHOD: changes the start and end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new start value + The new end value + If bigger than 0 applies it as the new tween duration + + + + Struct that stores two colors (used for LineRenderer tweens) + + + + + Used for tween callbacks + + + + + Used for tween callbacks + + + + + Used for custom and animationCurve-based ease functions. Must return a value between 0 and 1. + + + + + Straight Quaternion plugin. Instead of using Vector3 values accepts Quaternion values directly. + Beware: doesn't work with LoopType.Incremental (neither directly nor if inside a LoopType.Incremental Sequence). + To use it, call DOTween.To with the plugin parameter overload, passing it PureQuaternionPlugin.Plug() as first parameter + (do not use any of the other public PureQuaternionPlugin methods): + DOTween.To(PureQuaternionPlugin.Plug(), ()=> myQuaternionProperty, x=> myQuaternionProperty = x, myQuaternionEndValue, duration); + + + + + Plug this plugin inside a DOTween.To call. + Example: + DOTween.To(PureQuaternionPlugin.Plug(), ()=> myQuaternionProperty, x=> myQuaternionProperty = x, myQuaternionEndValue, duration); + + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + INTERNAL: do not use + + + + Main DOTween class. Contains static methods to create and control tweens in a generic way + + + + DOTween's version + + + If TRUE (default) makes tweens slightly slower but safer, automatically taking care of a series of things + (like targets becoming null while a tween is playing). + Default: TRUE + + + Behaviour in case a tween nested inside a Sequence fails (caught by safe mode). + Default: NestedTweenFailureBehaviour.TryToPreserveSequence + + + If TRUE you will get a DOTween report when exiting play mode (only in the Editor). + Useful to know how many max Tweeners and Sequences you reached and optimize your final project accordingly. + Beware, this will slightly slow down your tweens while inside Unity Editor. + Default: FALSE + + + Global DOTween timeScale. + Default: 1 + + + If TRUE, DOTween will use Time.smoothDeltaTime instead of Time.deltaTime for UpdateType.Normal and UpdateType.Late tweens + (unless they're set as timeScaleIndependent, in which case a value between the last timestep + and will be used instead). + Setting this to TRUE will lead to smoother animations. + Default: FALSE + + + If is TRUE, this indicates the max timeStep that an independent update call can last. + Setting this to TRUE will lead to smoother animations. + Default: FALSE + + + DOTween's log behaviour. + Default: LogBehaviour.ErrorsOnly + + + Used to intercept DOTween's logs. If this method isn't NULL, DOTween will call it before writing a log via Unity's own Debug log methods. + Return TRUE if you want DOTween to proceed with the log, FALSE otherwise. + This method must return a bool and accept two parameters: + - LogType: the type of Unity log that DOTween is trying to log + - object: the log message that DOTween wants to log + + + If TRUE draws path gizmos in Unity Editor (if the gizmos button is active). + Deactivate this if you want to avoid gizmos overhead while in Unity Editor + + + If TRUE activates various debug options + + + Stores the target id so it can be used to give more info in case of safeMode error capturing. + Only active if both debugMode and useSafeMode are TRUE + + + Default updateType for new tweens. + Default: UpdateType.Normal + + + Sets whether Unity's timeScale should be taken into account by default or not. + Default: false + + + Default autoPlay behaviour for new tweens. + Default: AutoPlay.All + + + Default autoKillOnComplete behaviour for new tweens. + Default: TRUE + + + Default loopType applied to all new tweens. + Default: LoopType.Restart + + + If TRUE all newly created tweens are set as recyclable, otherwise not. + Default: FALSE + + + Default ease applied to all new Tweeners (not to Sequences which always have Ease.Linear as default). + Default: Ease.InOutQuad + + + Default overshoot/amplitude used for eases + Default: 1.70158f + + + Default period used for eases + Default: 0 + + + Used internally. Assigned/removed by DOTweenComponent.Create/DestroyInstance + + + + Must be called once, before the first ever DOTween call/reference, + otherwise it will be called automatically and will use default options. + Calling it a second time won't have any effect. + You can chain SetCapacity to this method, to directly set the max starting size of Tweeners and Sequences: + DOTween.Init(false, false, LogBehaviour.Default).SetCapacity(100, 20); + + If TRUE all new tweens will be set for recycling, meaning that when killed, + instead of being destroyed, they will be put in a pool and reused instead of creating new tweens. This option allows you to avoid + GC allocations by reusing tweens, but you will have to take care of tween references, since they might result active + even if they were killed (since they might have been respawned and are now being used for other tweens). + If you want to automatically set your tween references to NULL when a tween is killed + you can use the OnKill callback like this: + .OnKill(()=> myTweenReference = null) + You can change this setting at any time by changing the static property, + or you can set the recycling behaviour for each tween separately, using: + SetRecyclable(bool recyclable) + Default: FALSE + If TRUE makes tweens slightly slower but safer, automatically taking care of a series of things + (like targets becoming null while a tween is playing). + You can change this setting at any time by changing the static property. + Default: FALSE + Type of logging to use. + You can change this setting at any time by changing the static property. + Default: ErrorsOnly + + + + Directly sets the current max capacity of Tweeners and Sequences + (meaning how many Tweeners and Sequences can be running at the same time), + so that DOTween doesn't need to automatically increase them in case the max is reached + (which might lead to hiccups when that happens). + Sequences capacity must be less or equal to Tweeners capacity + (if you pass a low Tweener capacity it will be automatically increased to match the Sequence's). + Beware: use this method only when there are no tweens running. + + Max Tweeners capacity. + Default: 200 + Max Sequences capacity. + Default: 50 + + + + Kills all tweens, clears all cached tween pools and plugins and resets the max Tweeners/Sequences capacities to the default values. + + If TRUE also destroys DOTween's gameObject and resets its initializiation, default settings and everything else + (so that next time you use it it will need to be re-initialized) + + + + Clears all cached tween pools. + + + + + Checks all active tweens to find and remove eventually invalid ones (usually because their targets became NULL) + and returns the total number of invalid tweens found and removed. + IMPORTANT: this will cause an error on UWP platform, so don't use it there + BEWARE: this is a slightly expensive operation so use it with care + + + + + Updates all tweens that are set to . + + Manual deltaTime + Unscaled delta time (used with tweens set as timeScaleIndependent) + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a property or field to the given value using a custom plugin + The plugin to use. Each custom plugin implements a static Get() method + you'll need to call to assign the correct plugin in the correct way, like this: + CustomPlugin.Get() + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens only one axis of a Vector3 to the given value using default plugins. + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + The axis to tween + + + Tweens only the alpha of a Color to the given value using default plugins + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end value to reachThe tween's duration + + + Tweens a virtual property from the given start to the given end value + and implements a setter that allows to use that value with an external method or a lambda + Example: + To(MyMethod, 0, 12, 0.5f); + Where MyMethod is a function that accepts a float parameter (which will be the result of the virtual tween) + The action to perform with the tweened value + The value to start from + The end value to reach + The duration of the virtual tween + + + + Punches a Vector3 towards the given direction and then back to the starting one + as if it was connected to the starting position via an elastic. + This tween type generates some GC allocations at startup + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The direction and strength of the punch + The duration of the tween + Indicates how much will the punch vibrate + Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards. + 1 creates a full oscillation between the direction and the opposite decaying direction, + while 0 oscillates only between the starting position and the decaying direction + + + Shakes a Vector3 with the given values. + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction and behave like a random punch. + If TRUE only shakes on the X Y axis (looks better with things like cameras). + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Vector3 with the given values. + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction and behave like a random punch. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Tweens a property or field to the given values using default plugins. + Ease is applied between each segment and not as a whole. + This tween type generates some GC allocations at startup + A getter for the field or property to tween. + Example usage with lambda:()=> myProperty + A setter for the field or property to tween + Example usage with lambda:x=> myProperty = x + The end values to reach for each segment. This array must have the same length as durations + The duration of each segment. This array must have the same length as endValues + + + + Returns a new to be used for tween groups + + + + Completes all tweens and returns the number of actual tweens completed + (meaning tweens that don't have infinite loops and were not already complete) + For Sequences only: if TRUE also internal Sequence callbacks will be fired, + otherwise they will be ignored + + + Completes all tweens with the given ID or target and returns the number of actual tweens completed + (meaning the tweens that don't have infinite loops and were not already complete) + For Sequences only: if TRUE internal Sequence callbacks will be fired, + otherwise they will be ignored + + + Flips all tweens (changing their direction to forward if it was backwards and viceversa), + then returns the number of actual tweens flipped + + + Flips the tweens with the given ID or target (changing their direction to forward if it was backwards and viceversa), + then returns the number of actual tweens flipped + + + Sends all tweens to the given position (calculating also eventual loop cycles) and returns the actual tweens involved + + + Sends all tweens with the given ID or target to the given position (calculating also eventual loop cycles) + and returns the actual tweens involved + + + Kills all tweens and returns the number of actual tweens killed + If TRUE completes the tweens before killing them + + + Kills all tweens and returns the number of actual tweens killed + If TRUE completes the tweens before killing them + Eventual IDs or targets to exclude from the killing + + + Kills all tweens with the given ID or target and returns the number of actual tweens killed + If TRUE completes the tweens before killing them + + + Pauses all tweens and returns the number of actual tweens paused + + + Pauses all tweens with the given ID or target and returns the number of actual tweens paused + (meaning the tweens that were actually playing and have been paused) + + + Plays all tweens and returns the number of actual tweens played + (meaning tweens that were not already playing or complete) + + + Plays all tweens with the given ID or target and returns the number of actual tweens played + (meaning the tweens that were not already playing or complete) + + + Plays all tweens with the given target and the given ID, and returns the number of actual tweens played + (meaning the tweens that were not already playing or complete) + + + Plays backwards all tweens and returns the number of actual tweens played + (meaning tweens that were not already started, playing backwards or rewinded) + + + Plays backwards all tweens with the given ID or target and returns the number of actual tweens played + (meaning the tweens that were not already started, playing backwards or rewinded) + + + Plays backwards all tweens with the given target and ID and returns the number of actual tweens played + (meaning the tweens that were not already started, playing backwards or rewinded) + + + Plays forward all tweens and returns the number of actual tweens played + (meaning tweens that were not already playing forward or complete) + + + Plays forward all tweens with the given ID or target and returns the number of actual tweens played + (meaning the tweens that were not already playing forward or complete) + + + Plays forward all tweens with the given target and ID and returns the number of actual tweens played + (meaning the tweens that were not already started, playing backwards or rewinded) + + + Restarts all tweens, then returns the number of actual tweens restarted + + + Restarts all tweens with the given ID or target, then returns the number of actual tweens restarted + If TRUE includes the eventual tweens delays, otherwise skips them + If >= 0 changes the startup delay of all involved tweens to this value, otherwise doesn't touch it + + + Restarts all tweens with the given target and the given ID, and returns the number of actual tweens played + (meaning the tweens that were not already playing or complete) + If TRUE includes the eventual tweens delays, otherwise skips them + If >= 0 changes the startup delay of all involved tweens to this value, otherwise doesn't touch it + + + Rewinds and pauses all tweens, then returns the number of actual tweens rewinded + (meaning tweens that were not already rewinded) + + + Rewinds and pauses all tweens with the given ID or target, then returns the number of actual tweens rewinded + (meaning the tweens that were not already rewinded) + + + Smoothly rewinds all tweens (delays excluded), then returns the number of actual tweens rewinding/rewinded + (meaning tweens that were not already rewinded). + A "smooth rewind" animates the tween to its start position, + skipping all elapsed loops (except in case of LoopType.Incremental) while keeping the animation fluent. + Note that a tween that was smoothly rewinded will have its play direction flipped + + + Smoothly rewinds all tweens (delays excluded) with the given ID or target, then returns the number of actual tweens rewinding/rewinded + (meaning the tweens that were not already rewinded). + A "smooth rewind" animates the tween to its start position, + skipping all elapsed loops (except in case of LoopType.Incremental) while keeping the animation fluent. + Note that a tween that was smoothly rewinded will have its play direction flipped + + + Toggles the play state of all tweens and returns the number of actual tweens toggled + (meaning tweens that could be played or paused, depending on the toggle state) + + + Toggles the play state of all tweens with the given ID or target and returns the number of actual tweens toggled + (meaning the tweens that could be played or paused, depending on the toggle state) + + + + Returns TRUE if a tween with the given ID or target is active. + You can also use this to know if a shortcut tween is active for a given target. + Example: + transform.DOMoveX(45, 1); // transform is automatically added as the tween target + DOTween.IsTweening(transform); // Returns true + + The target or ID to look for + If FALSE (default) returns TRUE as long as a tween for the given target/ID is active, + otherwise also requires it to be playing + + + + Returns the total number of active and playing tweens. + A tween is considered as playing even if its delay is actually playing + + + + + Returns a list of all active tweens in a playing state. + Returns NULL if there are no active playing tweens. + Beware: each time you call this method a new list is generated, so use it for debug only + + If NULL creates a new list, otherwise clears and fills this one (and thus saves allocations) + + + + Returns a list of all active tweens in a paused state. + Returns NULL if there are no active paused tweens. + Beware: each time you call this method a new list is generated, so use it for debug only + + If NULL creates a new list, otherwise clears and fills this one (and thus saves allocations) + + + + Returns a list of all active tweens with the given id. + Returns NULL if there are no active tweens with the given id. + Beware: each time you call this method a new list is generated + + If TRUE returns only the tweens with the given ID that are currently playing + If NULL creates a new list, otherwise clears and fills this one (and thus saves allocations) + + + + Returns a list of all active tweens with the given target. + Returns NULL if there are no active tweens with the given target. + Beware: each time you call this method a new list is generated + If TRUE returns only the tweens with the given target that are currently playing + If NULL creates a new list, otherwise clears and fills this one (and thus saves allocations) + + + + + Creates virtual tweens that can be used to change other elements via their OnUpdate calls + + + + + Tweens a virtual float. + You can add regular settings to the generated tween, + but do not use SetUpdate or you will overwrite the onVirtualUpdate parameter + + The value to start from + The value to tween to + The duration of the tween + A callback which must accept a parameter of type float, called at each update + + + + Returns a value based on the given ease and lifetime percentage (0 to 1) + The value to start from when lifetimePercentage is 0 + The value to reach when lifetimePercentage is 1 + The time percentage (0 to 1) at which the value should be taken + The type of ease + + + Returns a value based on the given ease and lifetime percentage (0 to 1) + The value to start from when lifetimePercentage is 0 + The value to reach when lifetimePercentage is 1 + The time percentage (0 to 1) at which the value should be taken + The type of ease + Eventual overshoot to use with Back ease + + + Returns a value based on the given ease and lifetime percentage (0 to 1) + The value to start from when lifetimePercentage is 0 + The value to reach when lifetimePercentage is 1 + The time percentage (0 to 1) at which the value should be taken + The type of ease + Eventual amplitude to use with Elastic easeType + Eventual period to use with Elastic easeType + + + Returns a value based on the given ease and lifetime percentage (0 to 1) + The value to start from when lifetimePercentage is 0 + The value to reach when lifetimePercentage is 1 + The time percentage (0 to 1) at which the value should be taken + The AnimationCurve to use for ease + + + Fires the given callback after the given time. + Callback delay + Callback to fire when the delay has expired + If TRUE (default) ignores Unity's timeScale + + + + Don't assign this! It's assigned automatically when creating 0 duration tweens + + + + + Don't assign this! It's assigned automatically when setting the ease to an AnimationCurve or to a custom ease function + + + + + Allows to wrap ease method in special ways, adding extra features + + + + + Converts the given ease so that it also creates a stop-motion effect, by playing the tween at the given FPS + + FPS at which the tween should be played + Ease type + + + + Converts the given ease so that it also creates a stop-motion effect, by playing the tween at the given FPS + + FPS at which the tween should be played + AnimationCurve to use for the ease + + + + Converts the given ease so that it also creates a stop-motion effect, by playing the tween at the given FPS + + FPS at which the tween should be played + Custom ease function to use + + + + Used to allow method chaining with DOTween.Init + + + + + Directly sets the current max capacity of Tweeners and Sequences + (meaning how many Tweeners and Sequences can be running at the same time), + so that DOTween doesn't need to automatically increase them in case the max is reached + (which might lead to hiccups when that happens). + Sequences capacity must be less or equal to Tweeners capacity + (if you pass a low Tweener capacity it will be automatically increased to match the Sequence's). + Beware: use this method only when there are no tweens running. + + Max Tweeners capacity. + Default: 200 + Max Sequences capacity. + Default: 50 + + + + Behaviour that can be assigned when chaining a SetLink to a tween + + + + Pauses the tween when the link target is disabled + + + Pauses the tween when the link target is disabled, plays it when it's enabled + + + Pauses the tween when the link target is disabled, restarts it when it's enabled + + + Plays the tween when the link target is enabled + + + Restarts the tween when the link target is enabled + + + Kills the tween when the link target is disabled + + + Kills the tween when the link target is destroyed (becomes NULL). This is always active even if another behaviour is chosen + + + Completes the tween when the link target is disabled + + + Completes and kills the tween when the link target is disabled + + + Rewinds the tween (delay excluded) when the link target is disabled + + + Rewinds and kills the tween when the link target is disabled + + + + Path mode (used to determine correct LookAt orientation) + + + + Ignores the path mode (and thus LookAt behaviour) + + + Regular 3D path + + + 2D top-down path + + + 2D side-scroller path + + + + Type of path to use with DOPath tweens + + + + Linear, composed of straight segments between each waypoint + + + Curved path (which uses Catmull-Rom curves) + + + EXPERIMENTAL: Curved path (which uses Cubic Bezier curves, where each point requires two extra control points) + + + + Path control point + + + + + Path waypoints (modified by PathPlugin when setting relative end/change value or by CubicBezierDecoder) and by DOTweenPathInspector + + + + + Gets the point on the path at the given percentage (0 to 1) + + The percentage (0 to 1) at which to get the point + If TRUE constant speed is taken into account, otherwise not + + + + Base interface for all tween plugins options + + + + Resets the plugin + + + + This plugin generates some GC allocations at startup + + + + + Path plugin works exclusively with Transforms + + + + + Rotation mode used with DORotate methods + + + + + Fastest way that never rotates beyond 360° + + + + + Fastest way that rotates beyond 360° + + + + + Adds the given rotation to the transform using world axis and an advanced precision mode + (like when using transform.Rotate(Space.World)). + In this mode the end value is is always considered relative + + + + + Adds the given rotation to the transform's local axis + (like when rotating an object with the "local" switch enabled in Unity's editor or using transform.Rotate(Space.Self)). + In this mode the end value is is always considered relative + + + + + Type of scramble to apply to string tweens + + + + + No scrambling of characters + + + + + A-Z + a-z + 0-9 characters + + + + + A-Z characters + + + + + a-z characters + + + + + 0-9 characters + + + + + Custom characters + + + + + Methods that extend Tween objects and allow to control or get data from them + + + + Completes the tween + + + Completes the tween + For Sequences only: if TRUE also internal Sequence callbacks will be fired, + otherwise they will be ignored + + + Flips the direction of this tween (backwards if it was going forward or viceversa) + + + Forces the tween to initialize its settings immediately + + + Send the tween to the given position in time + Time position to reach + (if higher than the whole tween duration the tween will simply reach its end) + If TRUE will play the tween after reaching the given position, otherwise it will pause it + + + Kills the tween + If TRUE completes the tween before killing it + + + Pauses the tween + + + Plays the tween + + + Sets the tween in a backwards direction and plays it + + + Sets the tween in a forward direction and plays it + + + Restarts the tween from the beginning + Ignored in case of Sequences. If TRUE includes the eventual tween delay, otherwise skips it + Ignored in case of Sequences. If >= 0 changes the startup delay to this value, otherwise doesn't touch it + + + Rewinds and pauses the tween + Ignored in case of Sequences. If TRUE includes the eventual tween delay, otherwise skips it + + + Smoothly rewinds the tween (delays excluded). + A "smooth rewind" animates the tween to its start position, + skipping all elapsed loops (except in case of LoopType.Incremental) while keeping the animation fluent. + If called on a tween who is still waiting for its delay to happen, it will simply set the delay to 0 and pause the tween. + Note that a tween that was smoothly rewinded will have its play direction flipped + + + Plays the tween if it was paused, pauses it if it was playing + + + Send a path tween to the given waypoint. + Has no effect if this is not a path tween. + BEWARE, this is a special utility method: + it works only with Linear eases. Also, the lookAt direction might be wrong after calling this and might need to be set manually + (because it relies on a smooth path movement and doesn't work well with jumps that encompass dramatic direction changes) + Waypoint index to reach + (if higher than the max waypoint index the tween will simply go to the last one) + If TRUE will play the tween after reaching the given waypoint, otherwise it will pause it + + + + Creates a yield instruction that waits until the tween is killed or complete. + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForCompletion(); + + + + + Creates a yield instruction that waits until the tween is killed or rewinded. + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForRewind(); + + + + + Creates a yield instruction that waits until the tween is killed. + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForKill(); + + + + + Creates a yield instruction that waits until the tween is killed or has gone through the given amount of loops. + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForElapsedLoops(2); + + Elapsed loops to wait for + + + + Creates a yield instruction that waits until the tween is killed or has reached the given position (loops included, delays excluded). + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForPosition(2.5f); + + Position (loops included, delays excluded) to wait for + + + + Creates a yield instruction that waits until the tween is killed or started + (meaning when the tween is set in a playing state the first time, after any eventual delay). + It can be used inside a coroutine as a yield. + Example usage:yield return myTween.WaitForStart(); + + + + Returns the total number of loops completed by this tween + + + Returns the eventual delay set for this tween + + + Returns the eventual elapsed delay set for this tween + + + Returns the duration of this tween (delays excluded). + NOTE: when using settings like SpeedBased, the duration will be recalculated when the tween starts + If TRUE returns the full duration loops included, + otherwise the duration of a single loop cycle + + + Returns the elapsed time for this tween (delays exluded) + If TRUE returns the elapsed time since startup loops included, + otherwise the elapsed time within the current loop cycle + + + Returns the elapsed percentage (0 to 1) of this tween (delays exluded) + If TRUE returns the elapsed percentage since startup loops included, + otherwise the elapsed percentage within the current loop cycle + + + Returns the elapsed percentage (0 to 1) of this tween (delays exluded), + based on a single loop, and calculating eventual backwards Yoyo loops as 1 to 0 instead of 0 to 1 + + + Returns FALSE if this tween has been killed or is NULL, TRUE otherwise. + BEWARE: if this tween is recyclable it might have been spawned again for another use and thus return TRUE anyway. + When working with recyclable tweens you should take care to know when a tween has been killed and manually set your references to NULL. + If you want to be sure your references are set to NULL when a tween is killed you can use the OnKill callback like this: + .OnKill(()=> myTweenReference = null) + + + Returns TRUE if this tween was reversed and is set to go backwards + + + Returns TRUE if the tween is complete + (silently fails and returns FALSE if the tween has been killed) + + + Returns TRUE if this tween has been initialized + + + Returns TRUE if this tween is playing + + + Returns the total number of loops set for this tween + (returns -1 if the loops are infinite) + + + + Returns a point on a path based on the given path percentage. + Returns Vector3.zero if this is not a path tween, if the tween is invalid, or if the path is not yet initialized. + A path is initialized after its tween starts, or immediately if the tween was created with the Path Editor (DOTween Pro feature). + You can force a path to be initialized by calling myTween.ForceInit(). + + Percentage of the path (0 to 1) on which to get the point + + + + Returns an array of points that can be used to draw the path. + Note that this method generates allocations, because it creates a new array. + Returns NULL if this is not a path tween, if the tween is invalid, or if the path is not yet initialized. + A path is initialized after its tween starts, or immediately if the tween was created with the Path Editor (DOTween Pro feature). + You can force a path to be initialized by calling myTween.ForceInit(). + + How many points to create for each path segment (waypoint to waypoint). + Only used in case of non-Linear paths + + + + Returns the length of a path. + Returns -1 if this is not a path tween, if the tween is invalid, or if the path is not yet initialized. + A path is initialized after its tween starts, or immediately if the tween was created with the Path Editor (DOTween Pro feature). + You can force a path to be initialized by calling myTween.ForceInit(). + + + + + Types of loop + + + + Each loop cycle restarts from the beginning + + + The tween moves forward and backwards at alternate cycles + + + Continuously increments the tween at the end of each loop cycle (A to B, B to B+(A-B), and so on), thus always moving "onward". + In case of String tweens works only if the tween is set as relative + + + + Controls other tweens as a group + + + + + Methods that extend known Unity objects and allow to directly create and control tweens from their instances + + + + Tweens a Camera's aspect to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's backgroundColor to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's farClipPlane to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's fieldOfView to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's nearClipPlane to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's orthographicSize to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's pixelRect to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Camera's rect to the given value. + Also stores the camera as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Shakes a Camera's localPosition along its relative X Y axes with the given values. + Also stores the camera as the tween's target so it can be used for filtered operations + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Camera's localPosition along its relative X Y axes with the given values. + Also stores the camera as the tween's target so it can be used for filtered operations + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Camera's localRotation. + Also stores the camera as the tween's target so it can be used for filtered operations + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Camera's localRotation. + Also stores the camera as the tween's target so it can be used for filtered operations + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Tweens a Light's color to the given value. + Also stores the light as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Light's intensity to the given value. + Also stores the light as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Light's shadowStrength to the given value. + Also stores the light as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a LineRenderer's color to the given value. + Also stores the LineRenderer as the tween's target so it can be used for filtered operations. + Note that this method requires to also insert the start colors for the tween, + since LineRenderers have no way to get them. + The start value to tween from + The end value to reachThe duration of the tween + + + Tweens a Material's color to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Material's named color property to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween (like _Tint or _SpecColor) + The duration of the tween + + + Tweens a Material's named color property with the given ID to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The ID of the material property to tween (also called nameID in Unity's manual) + The duration of the tween + + + Tweens a Material's alpha color to the given value + (will have no effect unless your material supports transparency). + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Material's alpha color to the given value + (will have no effect unless your material supports transparency). + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween (like _Tint or _SpecColor) + The duration of the tween + + + Tweens a Material's alpha color with the given ID to the given value + (will have no effect unless your material supports transparency). + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The ID of the material property to tween (also called nameID in Unity's manual) + The duration of the tween + + + Tweens a Material's named float property to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween + The duration of the tween + + + Tweens a Material's named float property with the given ID to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The ID of the material property to tween (also called nameID in Unity's manual) + The duration of the tween + + + Tweens a Material's texture offset to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The duration of the tween + + + Tweens a Material's named texture offset property to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween + The duration of the tween + + + Tweens a Material's texture scale to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The duration of the tween + + + Tweens a Material's named texture scale property to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween + The duration of the tween + + + Tweens a Material's named Vector property to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The name of the material property to tween + The duration of the tween + + + Tweens a Material's named Vector property with the given ID to the given value. + Also stores the material as the tween's target so it can be used for filtered operations + The end value to reach + The ID of the material property to tween (also called nameID in Unity's manual) + The duration of the tween + + + Tweens a TrailRenderer's startWidth/endWidth to the given value. + Also stores the TrailRenderer as the tween's target so it can be used for filtered operations + The end startWidth to reachThe end endWidth to reach + The duration of the tween + + + Tweens a TrailRenderer's time to the given value. + Also stores the TrailRenderer as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's position to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's X position to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's Y position to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's Z position to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's localPosition to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's X localPosition to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's Y localPosition to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's Z localPosition to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's rotation to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + Rotation mode + + + Tweens a Transform's rotation to the given value using pure quaternion values. + Also stores the transform as the tween's target so it can be used for filtered operations. + PLEASE NOTE: DORotate, which takes Vector3 values, is the preferred rotation method. + This method was implemented for very special cases, and doesn't support LoopType.Incremental loops + (neither for itself nor if placed inside a LoopType.Incremental Sequence) + + The end value to reachThe duration of the tween + + + Tweens a Transform's localRotation to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + Rotation mode + + + Tweens a Transform's rotation to the given value using pure quaternion values. + Also stores the transform as the tween's target so it can be used for filtered operations. + PLEASE NOTE: DOLocalRotate, which takes Vector3 values, is the preferred rotation method. + This method was implemented for very special cases, and doesn't support LoopType.Incremental loops + (neither for itself nor if placed inside a LoopType.Incremental Sequence) + + The end value to reachThe duration of the tween + + + Tweens a Transform's localScale to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's localScale uniformly to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's X localScale to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's Y localScale to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's Z localScale to the given value. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Transform's rotation so that it will look towards the given position. + Also stores the transform as the tween's target so it can be used for filtered operations + The position to look atThe duration of the tween + Eventual axis constraint for the rotation + The vector that defines in which direction up is (default: Vector3.up) + + + Punches a Transform's localPosition towards the given direction and then back to the starting one + as if it was connected to the starting position via an elastic. + The direction and strength of the punch (added to the Transform's current position) + The duration of the tween + Indicates how much will the punch vibrate + Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards. + 1 creates a full oscillation between the punch direction and the opposite direction, + while 0 oscillates only between the punch and the start position + If TRUE the tween will smoothly snap all values to integers + + + Punches a Transform's localScale towards the given size and then back to the starting one + as if it was connected to the starting scale via an elastic. + The punch strength (added to the Transform's current scale) + The duration of the tween + Indicates how much will the punch vibrate + Represents how much (0 to 1) the vector will go beyond the starting size when bouncing backwards. + 1 creates a full oscillation between the punch scale and the opposite scale, + while 0 oscillates only between the punch scale and the start scale + + + Punches a Transform's localRotation towards the given size and then back to the starting one + as if it was connected to the starting rotation via an elastic. + The punch strength (added to the Transform's current rotation) + The duration of the tween + Indicates how much will the punch vibrate + Represents how much (0 to 1) the vector will go beyond the starting rotation when bouncing backwards. + 1 creates a full oscillation between the punch rotation and the opposite rotation, + while 0 oscillates only between the punch and the start rotation + + + Shakes a Transform's localPosition with the given values. + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the tween will smoothly snap all values to integers + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Transform's localPosition with the given values. + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the tween will smoothly snap all values to integers + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Transform's localRotation. + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Transform's localRotation. + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Transform's localScale. + The duration of the tween + The shake strength + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Shakes a Transform's localScale. + The duration of the tween + The shake strength on each axis + Indicates how much will the shake vibrate + Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + Setting it to 0 will shake along a single direction. + If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + + + Tweens a Transform's position to the given value, while also applying a jump effect along the Y axis. + Returns a Sequence instead of a Tweener. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reach + Power of the jump (the max height of the jump is represented by this plus the final Y offset) + Total number of jumps + The duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's localPosition to the given value, while also applying a jump effect along the Y axis. + Returns a Sequence instead of a Tweener. + Also stores the transform as the tween's target so it can be used for filtered operations + The end value to reach + Power of the jump (the max height of the jump is represented by this plus the final Y offset) + Total number of jumps + The duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's position through the given path waypoints, using the chosen path algorithm. + Also stores the transform as the tween's target so it can be used for filtered operations + The waypoints to go through + The duration of the tween + The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + The path mode: 3D, side-scroller 2D, top-down 2D + The resolution of the path (useless in case of Linear paths): higher resolutions make for more detailed curved paths but are more expensive. + Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + The color of the path (shown when gizmos are active in the Play panel and the tween is running) + + + Tweens a Transform's localPosition through the given path waypoints, using the chosen path algorithm. + Also stores the transform as the tween's target so it can be used for filtered operations + The waypoint to go through + The duration of the tween + The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + The path mode: 3D, side-scroller 2D, top-down 2D + The resolution of the path: higher resolutions make for more detailed curved paths but are more expensive. + Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + The color of the path (shown when gizmos are active in the Play panel and the tween is running) + + + IMPORTANT: Unless you really know what you're doing, you should use the overload that accepts a Vector3 array instead. + Tweens a Transform's position via the given path. + Also stores the transform as the tween's target so it can be used for filtered operations + The path to use + The duration of the tween + The path mode: 3D, side-scroller 2D, top-down 2D + + + IMPORTANT: Unless you really know what you're doing, you should use the overload that accepts a Vector3 array instead. + Tweens a Transform's localPosition via the given path. + Also stores the transform as the tween's target so it can be used for filtered operations + The path to use + The duration of the tween + The path mode: 3D, side-scroller 2D, top-down 2D + + + Tweens a Tween's timeScale to the given value. + Also stores the Tween as the tween's target so it can be used for filtered operations + The end value to reachThe duration of the tween + + + Tweens a Light's color to the given value, + in a way that allows other DOBlendableColor tweens to work together on the same target, + instead than fight each other as multiple DOColor would do. + Also stores the Light as the tween's target so it can be used for filtered operations + The value to tween toThe duration of the tween + + + Tweens a Material's color to the given value, + in a way that allows other DOBlendableColor tweens to work together on the same target, + instead than fight each other as multiple DOColor would do. + Also stores the Material as the tween's target so it can be used for filtered operations + The value to tween toThe duration of the tween + + + Tweens a Material's named color property to the given value, + in a way that allows other DOBlendableColor tweens to work together on the same target, + instead than fight each other as multiple DOColor would do. + Also stores the Material as the tween's target so it can be used for filtered operations + The value to tween to + The name of the material property to tween (like _Tint or _SpecColor) + The duration of the tween + + + Tweens a Material's named color property with the given ID to the given value, + in a way that allows other DOBlendableColor tweens to work together on the same target, + instead than fight each other as multiple DOColor would do. + Also stores the Material as the tween's target so it can be used for filtered operations + The value to tween to + The ID of the material property to tween (also called nameID in Unity's manual) + The duration of the tween + + + Tweens a Transform's position BY the given value (as if you chained a SetRelative), + in a way that allows other DOBlendableMove tweens to work together on the same target, + instead than fight each other as multiple DOMove would do. + Also stores the transform as the tween's target so it can be used for filtered operations + The value to tween byThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + Tweens a Transform's localPosition BY the given value (as if you chained a SetRelative), + in a way that allows other DOBlendableMove tweens to work together on the same target, + instead than fight each other as multiple DOMove would do. + Also stores the transform as the tween's target so it can be used for filtered operations + The value to tween byThe duration of the tween + If TRUE the tween will smoothly snap all values to integers + + + EXPERIMENTAL METHOD - Tweens a Transform's rotation BY the given value (as if you chained a SetRelative), + in a way that allows other DOBlendableRotate tweens to work together on the same target, + instead than fight each other as multiple DORotate would do. + Also stores the transform as the tween's target so it can be used for filtered operations + The value to tween byThe duration of the tween + Rotation mode + + + EXPERIMENTAL METHOD - Tweens a Transform's lcoalRotation BY the given value (as if you chained a SetRelative), + in a way that allows other DOBlendableRotate tweens to work together on the same target, + instead than fight each other as multiple DORotate would do. + Also stores the transform as the tween's target so it can be used for filtered operations + The value to tween byThe duration of the tween + Rotation mode + + + Punches a Transform's localRotation BY the given value and then back to the starting one + as if it was connected to the starting rotation via an elastic. Does it in a way that allows other + DOBlendableRotate tweens to work together on the same target + The punch strength (added to the Transform's current rotation) + The duration of the tween + Indicates how much will the punch vibrate + Represents how much (0 to 1) the vector will go beyond the starting rotation when bouncing backwards. + 1 creates a full oscillation between the punch rotation and the opposite rotation, + while 0 oscillates only between the punch and the start rotation + + + Tweens a Transform's localScale BY the given value (as if you chained a SetRelative), + in a way that allows other DOBlendableScale tweens to work together on the same target, + instead than fight each other as multiple DOScale would do. + Also stores the transform as the tween's target so it can be used for filtered operations + The value to tween byThe duration of the tween + + + + Completes all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens completed + (meaning the tweens that don't have infinite loops and were not already complete) + + For Sequences only: if TRUE also internal Sequence callbacks will be fired, + otherwise they will be ignored + + + + Completes all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens completed + (meaning the tweens that don't have infinite loops and were not already complete) + + For Sequences only: if TRUE also internal Sequence callbacks will be fired, + otherwise they will be ignored + + + + Kills all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens killed. + + If TRUE completes the tween before killing it + + + + Kills all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens killed. + + If TRUE completes the tween before killing it + + + + Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens flipped. + + + + + Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens flipped. + + + + + Sends to the given position all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens involved. + + Time position to reach + (if higher than the whole tween duration the tween will simply reach its end) + If TRUE will play the tween after reaching the given position, otherwise it will pause it + + + + Sends to the given position all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens involved. + + Time position to reach + (if higher than the whole tween duration the tween will simply reach its end) + If TRUE will play the tween after reaching the given position, otherwise it will pause it + + + + Pauses all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens paused. + + + + + Pauses all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens paused. + + + + + Plays all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Plays all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Plays backwards all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Plays backwards all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Plays forward all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Plays forward all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens played. + + + + + Restarts all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens restarted. + + + + + Restarts all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens restarted. + + + + + Rewinds all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens rewinded. + + + + + Rewinds all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens rewinded. + + + + + Smoothly rewinds all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens rewinded. + + + + + Smoothly rewinds all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens rewinded. + + + + + Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens involved. + + + + + Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference + (meaning tweens that were started from this target, or that had this target added as an Id) + and returns the total number of tweens involved. + + + + + This class serves only as a utility class to store tween settings to apply on multiple tweens. + It is in no way needed otherwise, since you can directly apply tween settings to a tween via chaining + + + + A variable you can eventually Clear and reuse when needed, + to avoid instantiating TweenParams objects + + + Creates a new TweenParams object, which you can use to store tween settings + to pass to multiple tweens via myTween.SetAs(myTweenParms) + + + Clears and resets this TweenParams instance using default values, + so it can be reused without instantiating another one + + + Sets the autoKill behaviour of the tween. + Has no effect if the tween has already started + If TRUE the tween will be automatically killed when complete + + + Sets an ID for the tween, which can then be used as a filter with DOTween's static methods. + The ID to assign to this tween. Can be an int, a string, an object or anything else. + + + Sets the target for the tween, which can then be used as a filter with DOTween's static methods. + IMPORTANT: use it with caution. If you just want to set an ID for the tween use SetId instead. + When using shorcuts the shortcut target is already assigned as the tween's target, + so using this method will overwrite it and prevent shortcut-operations like myTarget.DOPause from working correctly. + The target to assign to this tween. Can be an int, a string, an object or anything else. + + + Sets the looping options for the tween. + Has no effect if the tween has already started + Number of cycles to play (-1 for infinite - will be converted to 1 in case the tween is nested in a Sequence) + Loop behaviour type (default: LoopType.Restart) + + + Sets the ease of the tween. + If applied to Sequences eases the whole sequence animation + Eventual overshoot or amplitude to use with Back or Elastic easeType (default is 1.70158) + Eventual period to use with Elastic easeType (default is 0) + + + Sets the ease of the tween using an AnimationCurve. + If applied to Sequences eases the whole sequence animation + + + Sets the ease of the tween using a custom ease function. + If applied to Sequences eases the whole sequence animation + + + Sets the recycling behaviour for the tween. + If TRUE the tween will be recycled after being killed, otherwise it will be destroyed. + + + Sets the update type to the one defined in DOTween.defaultUpdateType (UpdateType.Normal unless changed) + and lets you choose if it should be independent from Unity's Time.timeScale + If TRUE the tween will ignore Unity's Time.timeScale + + + Sets the type of update (default or independent) for the tween + The type of update (default: UpdateType.Normal) + If TRUE the tween will ignore Unity's Time.timeScale + + + Sets the onStart callback for the tween. + Called the first time the tween is set in a playing state, after any eventual delay + + + Sets the onPlay callback for the tween. + Called when the tween is set in a playing state, after any eventual delay. + Also called each time the tween resumes playing from a paused state + + + Sets the onRewind callback for the tween. + Called when the tween is rewinded, + either by calling Rewind or by reaching the start position while playing backwards. + Rewinding a tween that is already rewinded will not fire this callback + + + Sets the onUpdate callback for the tween. + Called each time the tween updates + + + Sets the onStepComplete callback for the tween. + Called the moment the tween completes one loop cycle, even when going backwards + + + Sets the onComplete callback for the tween. + Called the moment the tween reaches its final forward position, loops included + + + Sets the onKill callback for the tween. + Called the moment the tween is killed + + + Sets the onWaypointChange callback for the tween. + Called when a path tween reaches a new waypoint + + + Sets a delayed startup for the tween. + Has no effect on Sequences or if the tween has already started + + + If isRelative is TRUE sets the tween as relative + (the endValue will be calculated as startValue + endValue instead than being used directly). + Has no effect on Sequences or if the tween has already started + + + If isSpeedBased is TRUE sets the tween as speed based + (the duration will represent the number of units the tween moves x second). + Has no effect on Sequences, nested tweens, or if the tween has already started + + + + Methods that extend Tween objects and allow to set their parameters + + + + Sets the autoKill behaviour of the tween to TRUE. + Has no effect if the tween has already started or if it's added to a Sequence + + + Sets the autoKill behaviour of the tween. + Has no effect if the tween has already started or if it's added to a Sequence + If TRUE the tween will be automatically killed when complete + + + Sets an ID for the tween (), which can then be used as a filter with DOTween's static methods. + The ID to assign to this tween. Can be an int, a string, an object or anything else. + + + Sets a string ID for the tween (), which can then be used as a filter with DOTween's static methods. + Filtering via string is 2X faster than using an object as an ID (using the alternate obejct overload) + The string ID to assign to this tween. + + + Sets an int ID for the tween (), which can then be used as a filter with DOTween's static methods. + Filtering via int is 4X faster than via object, 2X faster than via string (using the alternate object/string overloads) + The int ID to assign to this tween. + + + Allows to link this tween to a GameObject + so that it will be automatically killed when the GameObject is destroyed. + Has no effect if the tween is added to a Sequence + The link target (unrelated to the target set via SetTarget) + + + Allows to link this tween to a GameObject and assign a behaviour depending on it. + This will also automatically kill the tween when the GameObject is destroyed. + Has no effect if the tween is added to a Sequence + The link target (unrelated to the target set via SetTarget) + The behaviour to use ( is always evaluated even if you choose another one) + + + Sets the target for the tween, which can then be used as a filter with DOTween's static methods. + IMPORTANT: use it with caution. If you just want to set an ID for the tween use SetId instead. + When using shorcuts the shortcut target is already assigned as the tween's target, + so using this method will overwrite it and prevent shortcut-operations like myTarget.DOPause from working correctly. + The target to assign to this tween. Can be an int, a string, an object or anything else. + + + Sets the looping options for the tween. + Has no effect if the tween has already started + Number of cycles to play (-1 for infinite - will be converted to 1 in case the tween is nested in a Sequence) + + + Sets the looping options for the tween. + Has no effect if the tween has already started + Number of cycles to play (-1 for infinite - will be converted to 1 in case the tween is nested in a Sequence) + Loop behaviour type (default: LoopType.Restart) + + + Sets the ease of the tween. + If applied to Sequences eases the whole sequence animation + + + Sets the ease of the tween. + If applied to Sequences eases the whole sequence animation + + Eventual overshoot to use with Back or Flash ease (default is 1.70158 - 1 for Flash). + In case of Flash ease it must be an intenger and sets the total number of flashes that will happen. + Using an even number will complete the tween on the starting value, while an odd one will complete it on the end value. + + + + Sets the ease of the tween. + If applied to Sequences eases the whole sequence animation + Eventual amplitude to use with Elastic easeType or overshoot to use with Flash easeType (default is 1.70158 - 1 for Flash). + In case of Flash ease it must be an integer and sets the total number of flashes that will happen. + Using an even number will complete the tween on the starting value, while an odd one will complete it on the end value. + + Eventual period to use with Elastic or Flash easeType (default is 0). + In case of Flash ease it indicates the power in time of the ease, and must be between -1 and 1. + 0 is balanced, 1 weakens the ease with time, -1 starts the ease weakened and gives it power towards the end. + + + + Sets the ease of the tween using an AnimationCurve. + If applied to Sequences eases the whole sequence animation + + + Sets the ease of the tween using a custom ease function (which must return a value between 0 and 1). + If applied to Sequences eases the whole sequence animation + + + Allows the tween to be recycled after being killed. + + + Sets the recycling behaviour for the tween. + If TRUE the tween will be recycled after being killed, otherwise it will be destroyed. + + + Sets the update type to UpdateType.Normal and lets you choose if it should be independent from Unity's Time.timeScale + If TRUE the tween will ignore Unity's Time.timeScale + + + Sets the type of update for the tween + The type of update (defalt: UpdateType.Normal) + + + Sets the type of update for the tween and lets you choose if it should be independent from Unity's Time.timeScale + The type of update + If TRUE the tween will ignore Unity's Time.timeScale + + + Sets the onStart callback for the tween, clearing any previous onStart callback that was set. + Called the first time the tween is set in a playing state, after any eventual delay + + + Sets the onPlay callback for the tween, clearing any previous onPlay callback that was set. + Called when the tween is set in a playing state, after any eventual delay. + Also called each time the tween resumes playing from a paused state + + + Sets the onPause callback for the tween, clearing any previous onPause callback that was set. + Called when the tween state changes from playing to paused. + If the tween has autoKill set to FALSE, this is called also when the tween reaches completion. + + + Sets the onRewind callback for the tween, clearing any previous onRewind callback that was set. + Called when the tween is rewinded, + either by calling Rewind or by reaching the start position while playing backwards. + Rewinding a tween that is already rewinded will not fire this callback + + + Sets the onUpdate callback for the tween, clearing any previous onUpdate callback that was set. + Called each time the tween updates + + + Sets the onStepComplete callback for the tween, clearing any previous onStepComplete callback that was set. + Called the moment the tween completes one loop cycle, even when going backwards + + + Sets the onComplete callback for the tween, clearing any previous onComplete callback that was set. + Called the moment the tween reaches its final forward position, loops included + + + Sets the onKill callback for the tween, clearing any previous onKill callback that was set. + Called the moment the tween is killed + + + Sets the onWaypointChange callback for the tween, clearing any previous onWaypointChange callback that was set. + Called when a path tween's current waypoint changes + + + Sets the parameters of the tween (id, ease, loops, delay, timeScale, callbacks, etc) as the parameters of the given one. + Doesn't copy specific SetOptions settings: those will need to be applied manually each time. + Has no effect if the tween has already started. + NOTE: the tween's target will not be changed + Tween from which to copy the parameters + + + Sets the parameters of the tween (id, ease, loops, delay, timeScale, callbacks, etc) as the parameters of the given TweenParams. + Has no effect if the tween has already started. + TweenParams from which to copy the parameters + + + Adds the given tween to the end of the Sequence. + Has no effect if the Sequence has already started + The tween to append + + + Adds the given tween to the beginning of the Sequence, pushing forward the other nested content. + Has no effect if the Sequence has already started + The tween to prepend + + + Inserts the given tween at the same time position of the last tween, callback or intervale added to the Sequence. + Note that, in case of a Join after an interval, the insertion time will be the time where the interval starts, not where it finishes. + Has no effect if the Sequence has already started + + + Inserts the given tween at the given time position in the Sequence, + automatically adding an interval if needed. + Has no effect if the Sequence has already started + The time position where the tween will be placed + The tween to insert + + + Adds the given interval to the end of the Sequence. + Has no effect if the Sequence has already started + The interval duration + + + Adds the given interval to the beginning of the Sequence, pushing forward the other nested content. + Has no effect if the Sequence has already started + The interval duration + + + Adds the given callback to the end of the Sequence. + Has no effect if the Sequence has already started + The callback to append + + + Adds the given callback to the beginning of the Sequence, pushing forward the other nested content. + Has no effect if the Sequence has already started + The callback to prepend + + + Inserts the given callback at the given time position in the Sequence, + automatically adding an interval if needed. + Has no effect if the Sequence has already started + The time position where the callback will be placed + The callback to insert + + + Changes a TO tween into a FROM tween: sets the current target's position as the tween's endValue + then immediately sends the target to the previously set endValue. + + + Changes a TO tween into a FROM tween: sets the current target's position as the tween's endValue + then immediately sends the target to the previously set endValue. + If TRUE the FROM value will be calculated as relative to the current one + + + Changes a TO tween into a FROM tween: sets the tween's starting value to the given one + and eventually sets the tween's target to that value immediately. + Value to start from + If TRUE sets the target to from value immediately, otherwise waits for the tween to start + + + Changes a TO tween into a FROM tween: sets the tween's starting value to the given one + and eventually sets the tween's target to that value immediately. + Alpha value to start from (in case of Fade tweens) + If TRUE sets the target to from value immediately, otherwise waits for the tween to start + + + Changes a TO tween into a FROM tween: sets the tween's starting value to the given one + and eventually sets the tween's target to that value immediately. + Value to start from (in case of Vector tweens that act on a single coordinate or scale tweens) + If TRUE sets the target to from value immediately, otherwise waits for the tween to start + + + Sets a delayed startup for the tween. + In case of Sequences behaves the same as , + which means the delay will repeat in case of loops (while with tweens it's ignored after the first loop cycle). + Has no effect if the tween has already started + + + EXPERIMENTAL: implemented in v1.2.340. + Sets a delayed startup for the tween with options to choose how the delay is applied in case of Sequences. + Has no effect if the tween has already started + Only used by types: If FALSE sets the delay as a one-time occurrence + (defaults to this for types), + otherwise as a Sequence interval which will repeat at the beginning of every loop cycle + + + Sets the tween as relative + (the endValue will be calculated as startValue + endValue instead than being used directly). + Has no effect on Sequences or if the tween has already started + + + If isRelative is TRUE sets the tween as relative + (the endValue will be calculated as startValue + endValue instead than being used directly). + Has no effect on Sequences or if the tween has already started + + + If isSpeedBased is TRUE sets the tween as speed based + (the duration will represent the number of units the tween moves x second). + Has no effect on Sequences, nested tweens, or if the tween has already started + + + If isSpeedBased is TRUE sets the tween as speed based + (the duration will represent the number of units the tween moves x second). + Has no effect on Sequences, nested tweens, or if the tween has already started + + + Options for float tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector2 tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector2 tweens + Selecting an axis will tween the vector only on that axis, leaving the others untouched + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector3 tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector3 tweens + Selecting an axis will tween the vector only on that axis, leaving the others untouched + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector4 tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector4 tweens + Selecting an axis will tween the vector only on that axis, leaving the others untouched + If TRUE the tween will smoothly snap all values to integers + + + Options for Quaternion tweens + If TRUE (default) the rotation will take the shortest route, and will not rotate more than 360°. + If FALSE the rotation will be fully accounted. Is always FALSE if the tween is set as relative + + + Options for Color tweens + If TRUE only the alpha value of the color will be tweened + + + Options for Vector4 tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector4 tweens + If TRUE, rich text will be interpreted correctly while animated, + otherwise all tags will be considered as normal text + The type of scramble to use, if any + A string containing the characters to use for scrambling. + Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. + Leave it to NULL to use default ones + + + Options for Vector3Array tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Vector3Array tweens + If TRUE the tween will smoothly snap all values to integers + + + Options for Path tweens (created via the DOPath shortcut) + The eventual movement axis to lock. You can input multiple axis if you separate them like this: + AxisConstrain.X | AxisConstraint.Y + The eventual rotation axis to lock. You can input multiple axis if you separate them like this: + AxisConstrain.X | AxisConstraint.Y + + + Options for Path tweens (created via the DOPath shortcut) + If TRUE the path will be automatically closed + The eventual movement axis to lock. You can input multiple axis if you separate them like this: + AxisConstrain.X | AxisConstraint.Y + The eventual rotation axis to lock. You can input multiple axis if you separate them like this: + AxisConstrain.X | AxisConstraint.Y + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the target towards the given position. + Must be chained directly to the tween creation method or to a SetOptions + The position to look at + The eventual direction to consider as "forward". + If left to NULL defaults to the regular forward side of the transform + The vector that defines in which direction up is (default: Vector3.up) + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the target towards the given position with options to keep the Z rotation stable. + Must be chained directly to the tween creation method or to a SetOptions + The position to look at + If TRUE doesn't rotate the target along the Z axis + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the target towards another transform. + Must be chained directly to the tween creation method or to a SetOptions + The transform to look at + The eventual direction to consider as "forward". + If left to NULL defaults to the regular forward side of the transform + The vector that defines in which direction up is (default: Vector3.up) + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the target towards another transform with options to keep the Z rotation stable. + Must be chained directly to the tween creation method or to a SetOptions + The transform to look at + If TRUE doesn't rotate the target along the Z axis + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the target to the path, with the given lookAhead. + Must be chained directly to the tween creation method or to a SetOptions + The percentage of lookAhead to use (0 to 1) + The eventual direction to consider as "forward". + If left to NULL defaults to the regular forward side of the transform + The vector that defines in which direction up is (default: Vector3.up) + + + Additional LookAt options for Path tweens (created via the DOPath shortcut). + Orients the path with options to keep the Z rotation stable. + Must be chained directly to the tween creation method or to a SetOptions + The percentage of lookAhead to use (0 to 1) + If TRUE doesn't rotate the target along the Z axis + + + + Types of log behaviours + + + + Log only warnings and errors + + + Log warnings, errors and additional infos + + + Log only errors + + + + Indicates either a Tweener or a Sequence + + + + TimeScale for the tween + + + If TRUE the tween wil go backwards + + + Object ID (usable for filtering with DOTween static methods). Can be anything except a string or an int + (use or for those) + + + String ID (usable for filtering with DOTween static methods). 2X faster than using an object id + + + Int ID (usable for filtering with DOTween static methods). 4X faster than using an object id, 2X faster than using a string id. + Default is -999 so avoid using an ID like that or it will capture all unset intIds + + + Tween target (usable for filtering with DOTween static methods). Automatically set by tween creation shortcuts + + + Called when the tween is set in a playing state, after any eventual delay. + Also called each time the tween resumes playing from a paused state + + + Called when the tween state changes from playing to paused. + If the tween has autoKill set to FALSE, this is called also when the tween reaches completion. + + + Called when the tween is rewinded, + either by calling Rewind or by reaching the start position while playing backwards. + Rewinding a tween that is already rewinded will not fire this callback + + + Called each time the tween updates + + + Called the moment the tween completes one loop cycle + + + Called the moment the tween reaches completion (loops included) + + + Called the moment the tween is killed + + + Called when a path tween's current waypoint changes + + + Tweeners-only (ignored by Sequences), returns TRUE if the tween was set as relative + + + + Set by SetTarget if DOTween's Debug Mode is on (see DOTween Utility Panel -> "Store GameObject's ID" debug option + + + + FALSE when tween is (or should be) despawned - set only by TweenManager + + + Gets and sets the time position (loops included, delays excluded) of the tween + + + Returns TRUE if the tween is set to loop (either a set number of times or infinitely) + + + TRUE after the tween was set in a play state at least once, AFTER any delay is elapsed + + + Time position within a single loop cycle + + + + Animates a single value + + + + Changes the start value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new start value + If bigger than 0 applies it as the new tween duration + + + Changes the end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new end value + If bigger than 0 applies it as the new tween duration + If TRUE the start value will become the current target's value, otherwise it will stay the same + + + Changes the end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new end value + If TRUE the start value will become the current target's value, otherwise it will stay the same + + + Changes the start and end value of a tween and rewinds it (without pausing it). + Has no effect with tweens that are inside Sequences + The new start value + The new end value + If bigger than 0 applies it as the new tween duration + + + + Used internally + + + + + Update type + + + + Updates every frame during Update calls + + + Updates every frame during LateUpdate calls + + + Updates using FixedUpdate calls + + + Updates using manual update calls + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML.meta new file mode 100644 index 0000000..7a866b5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.XML.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 34192c5e0d14aee43a0e86cc4823268a +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll new file mode 100644 index 0000000..986eb70 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb new file mode 100644 index 0000000..29b57c3 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb.meta new file mode 100644 index 0000000..f64a22a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 4f007001a22b3d24dae350342c4d19c8 +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.meta new file mode 100644 index 0000000..d0a5a8e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/DOTween.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: a811bde74b26b53498b4f6d872b09b6d +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor.meta new file mode 100644 index 0000000..532edfb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: b27f58ae5d5c33a4bb2d1f4f34bd036d +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML new file mode 100644 index 0000000..9ebc231 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML @@ -0,0 +1,107 @@ + + + + DOTweenEditor + + + + + Starts the update loop of tween in the editor. Has no effect during playMode. + + Eventual callback to call after every update + + + + Stops the update loop and clears the onPreviewUpdated callback. + + If TRUE also resets the tweened objects to their original state + + + + Readies the tween for editor preview by setting its UpdateType to Manual plus eventual extra settings. + + The tween to ready + If TRUE (recommended) removes all callbacks (OnComplete/Rewind/etc) + If TRUE prevents the tween from being auto-killed at completion + If TRUE starts playing the tween immediately + + + Full major version + first minor version (ex: 2018.1f) + + + Major version + + + First minor version (ex: in 2018.1 it would be 1) + + + + Checks that the given editor texture use the correct import settings, + and applies them if they're incorrect. + + + + + Returns TRUE if setup is required + + + + + Returns TRUE if the file/directory at the given path exists. + + Path, relative to Unity's project folder + + + + + Converts the given project-relative path to a full path, + with backward (\) slashes). + + + + + Converts the given full path to a path usable with AssetDatabase methods + (relative to Unity's project folder, and with the correct Unity forward (/) slashes). + + + + + Connects to a asset. + If the asset already exists at the given path, loads it and returns it. + Otherwise, either returns NULL or automatically creates it before loading and returning it + (depending on the given parameters). + + Asset type + File path (relative to Unity's project folder) + If TRUE and the requested asset doesn't exist, forces its creation + + + + Full path for the given loaded assembly, assembly file included + + + + + Adds the given global define if it's not already present + + + + + Removes the given global define if it's present + + + + + Returns TRUE if the given global define is present in all the + or only in the given , depending on passed parameters. + + + to use. Leave NULL to check in all of them. + + + + Not used as menu item anymore, but as a utiity function + + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML.meta new file mode 100644 index 0000000..7cec113 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.XML.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 2e2c6224d345d9249acfa6e8ef40bb2d +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll new file mode 100644 index 0000000..42fbb48 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb new file mode 100644 index 0000000..1599fd5 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb.meta new file mode 100644 index 0000000..bf461f3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 8f46310a8b0a8f04a92993c37c713243 +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.meta new file mode 100644 index 0000000..05db677 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/DOTweenEditor.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 45d5034162d6cf04dbe46da84fc7d074 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs.meta new file mode 100644 index 0000000..a81ba5f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 0034ebae0c2a9344e897db1160d71b6d +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png new file mode 100644 index 0000000..d06fc7c Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png.meta new file mode 100644 index 0000000..61c3cce --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/DOTweenIcon.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8da095e39e9b4df488dfd436f81116d6 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 128 + textureSettings: + filterMode: 1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png new file mode 100644 index 0000000..e29d02f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png.meta new file mode 100644 index 0000000..7ca1911 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 7051dba417b3d53409f2918f1ea4938d +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 256 + textureSettings: + filterMode: 1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png new file mode 100644 index 0000000..e48db5e Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png.meta new file mode 100644 index 0000000..f12a1a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Footer_dark.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 519694efe2bb2914788b151fbd8c01f4 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg new file mode 100644 index 0000000..4d710d7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg.meta new file mode 100644 index 0000000..26e4255 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Editor/Imgs/Header.jpg.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 78a59ca99f8987941adb61f9e14a06a7 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 512 + textureSettings: + filterMode: 1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules.meta new file mode 100644 index 0000000..24cd2ac --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 143604b8bad857d47a6f7cc7a533e2dc +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef new file mode 100644 index 0000000..42ef5ab --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef @@ -0,0 +1,3 @@ +{ + "name": "DOTween.Modules" +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef.meta new file mode 100644 index 0000000..5022663 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTween.Modules.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1d85850b2bd2239408107d29ad53c78e +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs new file mode 100644 index 0000000..c195b6c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs @@ -0,0 +1,202 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +#if true // MODULE_MARKER +using System; +using DG.Tweening.Core; +using DG.Tweening.Plugins.Options; +using UnityEngine; +#if UNITY_5 || UNITY_2017_1_OR_NEWER +using UnityEngine.Audio; // Required for AudioMixer +#endif + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenModuleAudio + { + #region Shortcuts + + #region Audio + + /// Tweens an AudioSource's volume to the given value. + /// Also stores the AudioSource as the tween's target so it can be used for filtered operations + /// The end value to reach (0 to 1)The duration of the tween + public static TweenerCore DOFade(this AudioSource target, float endValue, float duration) + { + if (endValue < 0) endValue = 0; + else if (endValue > 1) endValue = 1; + TweenerCore t = DOTween.To(() => target.volume, x => target.volume = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens an AudioSource's pitch to the given value. + /// Also stores the AudioSource as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOPitch(this AudioSource target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.pitch, x => target.pitch = x, endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + +#if UNITY_5 || UNITY_2017_1_OR_NEWER + #region AudioMixer (Unity 5 or Newer) + + /// Tweens an AudioMixer's exposed float to the given value. + /// Also stores the AudioMixer as the tween's target so it can be used for filtered operations. + /// Note that you need to manually expose a float in an AudioMixerGroup in order to be able to tween it from an AudioMixer. + /// Name given to the exposed float to set + /// The end value to reachThe duration of the tween + public static TweenerCore DOSetFloat(this AudioMixer target, string floatName, float endValue, float duration) + { + TweenerCore t = DOTween.To(()=> { + float currVal; + target.GetFloat(floatName, out currVal); + return currVal; + }, x=> target.SetFloat(floatName, x), endValue, duration); + t.SetTarget(target); + return t; + } + + #region Operation Shortcuts + + /// + /// Completes all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens completed + /// (meaning the tweens that don't have infinite loops and were not already complete) + /// + /// For Sequences only: if TRUE also internal Sequence callbacks will be fired, + /// otherwise they will be ignored + public static int DOComplete(this AudioMixer target, bool withCallbacks = false) + { + return DOTween.Complete(target, withCallbacks); + } + + /// + /// Kills all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens killed. + /// + /// If TRUE completes the tween before killing it + public static int DOKill(this AudioMixer target, bool complete = false) + { + return DOTween.Kill(target, complete); + } + + /// + /// Flips the direction (backwards if it was going forward or viceversa) of all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens flipped. + /// + public static int DOFlip(this AudioMixer target) + { + return DOTween.Flip(target); + } + + /// + /// Sends to the given position all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens involved. + /// + /// Time position to reach + /// (if higher than the whole tween duration the tween will simply reach its end) + /// If TRUE will play the tween after reaching the given position, otherwise it will pause it + public static int DOGoto(this AudioMixer target, float to, bool andPlay = false) + { + return DOTween.Goto(target, to, andPlay); + } + + /// + /// Pauses all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens paused. + /// + public static int DOPause(this AudioMixer target) + { + return DOTween.Pause(target); + } + + /// + /// Plays all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens played. + /// + public static int DOPlay(this AudioMixer target) + { + return DOTween.Play(target); + } + + /// + /// Plays backwards all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens played. + /// + public static int DOPlayBackwards(this AudioMixer target) + { + return DOTween.PlayBackwards(target); + } + + /// + /// Plays forward all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens played. + /// + public static int DOPlayForward(this AudioMixer target) + { + return DOTween.PlayForward(target); + } + + /// + /// Restarts all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens restarted. + /// + public static int DORestart(this AudioMixer target) + { + return DOTween.Restart(target); + } + + /// + /// Rewinds all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens rewinded. + /// + public static int DORewind(this AudioMixer target) + { + return DOTween.Rewind(target); + } + + /// + /// Smoothly rewinds all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens rewinded. + /// + public static int DOSmoothRewind(this AudioMixer target) + { + return DOTween.SmoothRewind(target); + } + + /// + /// Toggles the paused state (plays if it was paused, pauses if it was playing) of all tweens that have this target as a reference + /// (meaning tweens that were started from this target, or that had this target added as an Id) + /// and returns the total number of tweens involved. + /// + public static int DOTogglePause(this AudioMixer target) + { + return DOTween.TogglePause(target); + } + + #endregion + + #endregion +#endif + + #endregion + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs.meta new file mode 100644 index 0000000..50aa010 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleAudio.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b766d08851589514b97afb23c6f30a70 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs new file mode 100644 index 0000000..08b0700 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs @@ -0,0 +1,216 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +#if true // MODULE_MARKER +using System; +using DG.Tweening.Core; +using DG.Tweening.Core.Enums; +using DG.Tweening.Plugins; +using DG.Tweening.Plugins.Core.PathCore; +using DG.Tweening.Plugins.Options; +using UnityEngine; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenModulePhysics + { + #region Shortcuts + + #region Rigidbody + + /// Tweens a Rigidbody's position to the given value. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMove(this Rigidbody target, Vector3 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody's X position to the given value. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMoveX(this Rigidbody target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, new Vector3(endValue, 0, 0), duration); + t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody's Y position to the given value. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMoveY(this Rigidbody target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, new Vector3(0, endValue, 0), duration); + t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody's Z position to the given value. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMoveZ(this Rigidbody target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, new Vector3(0, 0, endValue), duration); + t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody's rotation to the given value. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// Rotation mode + public static TweenerCore DORotate(this Rigidbody target, Vector3 endValue, float duration, RotateMode mode = RotateMode.Fast) + { + TweenerCore t = DOTween.To(() => target.rotation, target.MoveRotation, endValue, duration); + t.SetTarget(target); + t.plugOptions.rotateMode = mode; + return t; + } + + /// Tweens a Rigidbody's rotation so that it will look towards the given position. + /// Also stores the rigidbody as the tween's target so it can be used for filtered operations + /// The position to look atThe duration of the tween + /// Eventual axis constraint for the rotation + /// The vector that defines in which direction up is (default: Vector3.up) + public static TweenerCore DOLookAt(this Rigidbody target, Vector3 towards, float duration, AxisConstraint axisConstraint = AxisConstraint.None, Vector3? up = null) + { + TweenerCore t = DOTween.To(() => target.rotation, target.MoveRotation, towards, duration) + .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetLookAt); + t.plugOptions.axisConstraint = axisConstraint; + t.plugOptions.up = (up == null) ? Vector3.up : (Vector3)up; + return t; + } + + #region Special + + /// Tweens a Rigidbody's position to the given value, while also applying a jump effect along the Y axis. + /// Returns a Sequence instead of a Tweener. + /// Also stores the Rigidbody as the tween's target so it can be used for filtered operations + /// The end value to reach + /// Power of the jump (the max height of the jump is represented by this plus the final Y offset) + /// Total number of jumps + /// The duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Sequence DOJump(this Rigidbody target, Vector3 endValue, float jumpPower, int numJumps, float duration, bool snapping = false) + { + if (numJumps < 1) numJumps = 1; + float startPosY = 0; + float offsetY = -1; + bool offsetYSet = false; + Sequence s = DOTween.Sequence(); + Tween yTween = DOTween.To(() => target.position, target.MovePosition, new Vector3(0, jumpPower, 0), duration / (numJumps * 2)) + .SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative() + .SetLoops(numJumps * 2, LoopType.Yoyo) + .OnStart(() => startPosY = target.position.y); + s.Append(DOTween.To(() => target.position, target.MovePosition, new Vector3(endValue.x, 0, 0), duration) + .SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear) + ).Join(DOTween.To(() => target.position, target.MovePosition, new Vector3(0, 0, endValue.z), duration) + .SetOptions(AxisConstraint.Z, snapping).SetEase(Ease.Linear) + ).Join(yTween) + .SetTarget(target).SetEase(DOTween.defaultEaseType); + yTween.OnUpdate(() => { + if (!offsetYSet) { + offsetYSet = true; + offsetY = s.isRelative ? endValue.y : endValue.y - startPosY; + } + Vector3 pos = target.position; + pos.y += DOVirtual.EasedValue(0, offsetY, yTween.ElapsedPercentage(), Ease.OutQuad); + target.MovePosition(pos); + }); + return s; + } + + /// Tweens a Rigidbody's position through the given path waypoints, using the chosen path algorithm. + /// Also stores the Rigidbody as the tween's target so it can be used for filtered operations. + /// NOTE: to tween a rigidbody correctly it should be set to kinematic at least while being tweened. + /// BEWARE: doesn't work on Windows Phone store (waiting for Unity to fix their own bug). + /// If you plan to publish there you should use a regular transform.DOPath. + /// The waypoints to go through + /// The duration of the tween + /// The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + /// The path mode: 3D, side-scroller 2D, top-down 2D + /// The resolution of the path (useless in case of Linear paths): higher resolutions make for more detailed curved paths but are more expensive. + /// Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + /// The color of the path (shown when gizmos are active in the Play panel and the tween is running) + public static TweenerCore DOPath( + this Rigidbody target, Vector3[] path, float duration, PathType pathType = PathType.Linear, + PathMode pathMode = PathMode.Full3D, int resolution = 10, Color? gizmoColor = null + ) + { + if (resolution < 1) resolution = 1; + TweenerCore t = DOTween.To(PathPlugin.Get(), () => target.position, target.MovePosition, new Path(pathType, path, resolution, gizmoColor), duration) + .SetTarget(target).SetUpdate(UpdateType.Fixed); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + return t; + } + /// Tweens a Rigidbody's localPosition through the given path waypoints, using the chosen path algorithm. + /// Also stores the Rigidbody as the tween's target so it can be used for filtered operations + /// NOTE: to tween a rigidbody correctly it should be set to kinematic at least while being tweened. + /// BEWARE: doesn't work on Windows Phone store (waiting for Unity to fix their own bug). + /// If you plan to publish there you should use a regular transform.DOLocalPath. + /// The waypoint to go through + /// The duration of the tween + /// The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + /// The path mode: 3D, side-scroller 2D, top-down 2D + /// The resolution of the path: higher resolutions make for more detailed curved paths but are more expensive. + /// Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + /// The color of the path (shown when gizmos are active in the Play panel and the tween is running) + public static TweenerCore DOLocalPath( + this Rigidbody target, Vector3[] path, float duration, PathType pathType = PathType.Linear, + PathMode pathMode = PathMode.Full3D, int resolution = 10, Color? gizmoColor = null + ) + { + if (resolution < 1) resolution = 1; + Transform trans = target.transform; + TweenerCore t = DOTween.To(PathPlugin.Get(), () => trans.localPosition, x => target.MovePosition(trans.parent == null ? x : trans.parent.TransformPoint(x)), new Path(pathType, path, resolution, gizmoColor), duration) + .SetTarget(target).SetUpdate(UpdateType.Fixed); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + t.plugOptions.useLocalPosition = true; + return t; + } + // Used by path editor when creating the actual tween, so it can pass a pre-compiled path + internal static TweenerCore DOPath( + this Rigidbody target, Path path, float duration, PathMode pathMode = PathMode.Full3D + ) + { + TweenerCore t = DOTween.To(PathPlugin.Get(), () => target.position, target.MovePosition, path, duration) + .SetTarget(target); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + return t; + } + internal static TweenerCore DOLocalPath( + this Rigidbody target, Path path, float duration, PathMode pathMode = PathMode.Full3D + ) + { + Transform trans = target.transform; + TweenerCore t = DOTween.To(PathPlugin.Get(), () => trans.localPosition, x => target.MovePosition(trans.parent == null ? x : trans.parent.TransformPoint(x)), path, duration) + .SetTarget(target); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + t.plugOptions.useLocalPosition = true; + return t; + } + + #endregion + + #endregion + + #endregion + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs.meta new file mode 100644 index 0000000..0ce0d75 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dae9aa560b4242648a3affa2bfabc365 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs new file mode 100644 index 0000000..eab2cbf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs @@ -0,0 +1,168 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +#if true && (UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER) // MODULE_MARKER +using System; +using DG.Tweening.Core; +using DG.Tweening.Plugins; +using DG.Tweening.Plugins.Core.PathCore; +using DG.Tweening.Plugins.Options; +using UnityEngine; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenModulePhysics2D + { + #region Shortcuts + + #region Rigidbody2D Shortcuts + + /// Tweens a Rigidbody2D's position to the given value. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMove(this Rigidbody2D target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody2D's X position to the given value. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMoveX(this Rigidbody2D target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, new Vector2(endValue, 0), duration); + t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody2D's Y position to the given value. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMoveY(this Rigidbody2D target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.position, target.MovePosition, new Vector2(0, endValue), duration); + t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); + return t; + } + + /// Tweens a Rigidbody2D's rotation to the given value. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DORotate(this Rigidbody2D target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.rotation, target.MoveRotation, endValue, duration); + t.SetTarget(target); + return t; + } + + #region Special + + /// Tweens a Rigidbody2D's position to the given value, while also applying a jump effect along the Y axis. + /// Returns a Sequence instead of a Tweener. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations. + /// IMPORTANT: a rigidbody2D can't be animated in a jump arc using MovePosition, so the tween will directly set the position + /// The end value to reach + /// Power of the jump (the max height of the jump is represented by this plus the final Y offset) + /// Total number of jumps + /// The duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Sequence DOJump(this Rigidbody2D target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false) + { + if (numJumps < 1) numJumps = 1; + float startPosY = 0; + float offsetY = -1; + bool offsetYSet = false; + Sequence s = DOTween.Sequence(); + Tween yTween = DOTween.To(() => target.position, x => target.position = x, new Vector2(0, jumpPower), duration / (numJumps * 2)) + .SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative() + .SetLoops(numJumps * 2, LoopType.Yoyo) + .OnStart(() => startPosY = target.position.y); + s.Append(DOTween.To(() => target.position, x => target.position = x, new Vector2(endValue.x, 0), duration) + .SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear) + ).Join(yTween) + .SetTarget(target).SetEase(DOTween.defaultEaseType); + yTween.OnUpdate(() => { + if (!offsetYSet) { + offsetYSet = true; + offsetY = s.isRelative ? endValue.y : endValue.y - startPosY; + } + Vector3 pos = target.position; + pos.y += DOVirtual.EasedValue(0, offsetY, yTween.ElapsedPercentage(), Ease.OutQuad); + target.MovePosition(pos); + }); + return s; + } + + /// Tweens a Rigidbody2D's position through the given path waypoints, using the chosen path algorithm. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations. + /// NOTE: to tween a Rigidbody2D correctly it should be set to kinematic at least while being tweened. + /// BEWARE: doesn't work on Windows Phone store (waiting for Unity to fix their own bug). + /// If you plan to publish there you should use a regular transform.DOPath. + /// The waypoints to go through + /// The duration of the tween + /// The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + /// The path mode: 3D, side-scroller 2D, top-down 2D + /// The resolution of the path (useless in case of Linear paths): higher resolutions make for more detailed curved paths but are more expensive. + /// Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + /// The color of the path (shown when gizmos are active in the Play panel and the tween is running) + public static TweenerCore DOPath( + this Rigidbody2D target, Vector2[] path, float duration, PathType pathType = PathType.Linear, + PathMode pathMode = PathMode.Full3D, int resolution = 10, Color? gizmoColor = null + ) + { + if (resolution < 1) resolution = 1; + int len = path.Length; + Vector3[] path3D = new Vector3[len]; + for (int i = 0; i < len; ++i) path3D[i] = path[i]; + TweenerCore t = DOTween.To(PathPlugin.Get(), () => target.position, x => target.MovePosition(x), new Path(pathType, path3D, resolution, gizmoColor), duration) + .SetTarget(target).SetUpdate(UpdateType.Fixed); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + return t; + } + /// Tweens a Rigidbody2D's localPosition through the given path waypoints, using the chosen path algorithm. + /// Also stores the Rigidbody2D as the tween's target so it can be used for filtered operations + /// NOTE: to tween a Rigidbody2D correctly it should be set to kinematic at least while being tweened. + /// BEWARE: doesn't work on Windows Phone store (waiting for Unity to fix their own bug). + /// If you plan to publish there you should use a regular transform.DOLocalPath. + /// The waypoint to go through + /// The duration of the tween + /// The type of path: Linear (straight path), CatmullRom (curved CatmullRom path) or CubicBezier (curved with control points) + /// The path mode: 3D, side-scroller 2D, top-down 2D + /// The resolution of the path: higher resolutions make for more detailed curved paths but are more expensive. + /// Defaults to 10, but a value of 5 is usually enough if you don't have dramatic long curves between waypoints + /// The color of the path (shown when gizmos are active in the Play panel and the tween is running) + public static TweenerCore DOLocalPath( + this Rigidbody2D target, Vector2[] path, float duration, PathType pathType = PathType.Linear, + PathMode pathMode = PathMode.Full3D, int resolution = 10, Color? gizmoColor = null + ) + { + if (resolution < 1) resolution = 1; + int len = path.Length; + Vector3[] path3D = new Vector3[len]; + for (int i = 0; i < len; ++i) path3D[i] = path[i]; + Transform trans = target.transform; + TweenerCore t = DOTween.To(PathPlugin.Get(), () => trans.localPosition, x => target.MovePosition(trans.parent == null ? x : trans.parent.TransformPoint(x)), new Path(pathType, path3D, resolution, gizmoColor), duration) + .SetTarget(target).SetUpdate(UpdateType.Fixed); + + t.plugOptions.isRigidbody = true; + t.plugOptions.mode = pathMode; + t.plugOptions.useLocalPosition = true; + return t; + } + + #endregion + + #endregion + + #endregion + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs.meta new file mode 100644 index 0000000..ca9ed29 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModulePhysics2D.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 230fe34542e175245ba74b4659dae700 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs new file mode 100644 index 0000000..549fff3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs @@ -0,0 +1,93 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +#if true && (UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER) // MODULE_MARKER +using System; +using UnityEngine; +using DG.Tweening.Core; +using DG.Tweening.Plugins.Options; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenModuleSprite + { + #region Shortcuts + + #region SpriteRenderer + + /// Tweens a SpriteRenderer's color to the given value. + /// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this SpriteRenderer target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Material's alpha color to the given value. + /// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this SpriteRenderer target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a SpriteRenderer's color using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to useThe duration of the tween + public static Sequence DOGradientColor(this SpriteRenderer target, Gradient gradient, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.color = c.color; + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + + #endregion + + #region Blendables + + #region SpriteRenderer + + /// Tweens a SpriteRenderer's color to the given value, + /// in a way that allows other DOBlendableColor tweens to work together on the same target, + /// instead than fight each other as multiple DOColor would do. + /// Also stores the SpriteRenderer as the tween's target so it can be used for filtered operations + /// The value to tween toThe duration of the tween + public static Tweener DOBlendableColor(this SpriteRenderer target, Color endValue, float duration) + { + endValue = endValue - target.color; + Color to = new Color(0, 0, 0, 0); + return DOTween.To(() => to, x => { + Color diff = x - to; + to = x; + target.color += diff; + }, endValue, duration) + .Blendable().SetTarget(target); + } + + #endregion + + #endregion + + #endregion + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs.meta new file mode 100644 index 0000000..a0c67c4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 188918ab119d93148aa0de59ccf5286b +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs new file mode 100644 index 0000000..ee32bed --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs @@ -0,0 +1,634 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +#if true && (UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER) // MODULE_MARKER + +using System; +using System.Globalization; +using UnityEngine; +using UnityEngine.UI; +using DG.Tweening.Core; +using DG.Tweening.Core.Enums; +using DG.Tweening.Plugins.Options; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenModuleUI + { + #region Shortcuts + + #region CanvasGroup + + /// Tweens a CanvasGroup's alpha color to the given value. + /// Also stores the canvasGroup as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this CanvasGroup target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.alpha, x => target.alpha = x, endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + + #region Graphic + + /// Tweens an Graphic's color to the given value. + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this Graphic target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens an Graphic's alpha color to the given value. + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this Graphic target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + + #region Image + + /// Tweens an Image's color to the given value. + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this Image target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens an Image's alpha color to the given value. + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this Image target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens an Image's fillAmount to the given value. + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The end value to reach (0 to 1)The duration of the tween + public static TweenerCore DOFillAmount(this Image target, float endValue, float duration) + { + if (endValue > 1) endValue = 1; + else if (endValue < 0) endValue = 0; + TweenerCore t = DOTween.To(() => target.fillAmount, x => target.fillAmount = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens an Image's colors using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to useThe duration of the tween + public static Sequence DOGradientColor(this Image target, Gradient gradient, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.color = c.color; + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + + #endregion + + #region LayoutElement + + /// Tweens an LayoutElement's flexibleWidth/Height to the given value. + /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOFlexibleSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => new Vector2(target.flexibleWidth, target.flexibleHeight), x => { + target.flexibleWidth = x.x; + target.flexibleHeight = x.y; + }, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens an LayoutElement's minWidth/Height to the given value. + /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOMinSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => new Vector2(target.minWidth, target.minHeight), x => { + target.minWidth = x.x; + target.minHeight = x.y; + }, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens an LayoutElement's preferredWidth/Height to the given value. + /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOPreferredSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => new Vector2(target.preferredWidth, target.preferredHeight), x => { + target.preferredWidth = x.x; + target.preferredHeight = x.y; + }, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + #endregion + + #region Outline + + /// Tweens a Outline's effectColor to the given value. + /// Also stores the Outline as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this Outline target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.effectColor, x => target.effectColor = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Outline's effectColor alpha to the given value. + /// Also stores the Outline as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this Outline target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.effectColor, x => target.effectColor = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Outline's effectDistance to the given value. + /// Also stores the Outline as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScale(this Outline target, Vector2 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.effectDistance, x => target.effectDistance = x, endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + + #region RectTransform + + /// Tweens a RectTransform's anchoredPosition to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPos(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + /// Tweens a RectTransform's anchoredPosition X to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPosX(this RectTransform target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue, 0), duration); + t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); + return t; + } + /// Tweens a RectTransform's anchoredPosition Y to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPosY(this RectTransform target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, endValue), duration); + t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); + return t; + } + + /// Tweens a RectTransform's anchoredPosition3D to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPos3D(this RectTransform target, Vector3 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + /// Tweens a RectTransform's anchoredPosition3D X to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPos3DX(this RectTransform target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(endValue, 0, 0), duration); + t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); + return t; + } + /// Tweens a RectTransform's anchoredPosition3D Y to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPos3DY(this RectTransform target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, endValue, 0), duration); + t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); + return t; + } + /// Tweens a RectTransform's anchoredPosition3D Z to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorPos3DZ(this RectTransform target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, 0, endValue), duration); + t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target); + return t; + } + + /// Tweens a RectTransform's anchorMax to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorMax(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchorMax, x => target.anchorMax = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens a RectTransform's anchorMin to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOAnchorMin(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.anchorMin, x => target.anchorMin = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Tweens a RectTransform's pivot to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOPivot(this RectTransform target, Vector2 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.pivot, x => target.pivot = x, endValue, duration); + t.SetTarget(target); + return t; + } + /// Tweens a RectTransform's pivot X to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOPivotX(this RectTransform target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(endValue, 0), duration); + t.SetOptions(AxisConstraint.X).SetTarget(target); + return t; + } + /// Tweens a RectTransform's pivot Y to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOPivotY(this RectTransform target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(0, endValue), duration); + t.SetOptions(AxisConstraint.Y).SetTarget(target); + return t; + } + + /// Tweens a RectTransform's sizeDelta to the given value. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOSizeDelta(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.sizeDelta, x => target.sizeDelta = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + /// Punches a RectTransform's anchoredPosition towards the given direction and then back to the starting one + /// as if it was connected to the starting position via an elastic. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The direction and strength of the punch (added to the RectTransform's current position) + /// The duration of the tween + /// Indicates how much will the punch vibrate + /// Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards. + /// 1 creates a full oscillation between the punch direction and the opposite direction, + /// while 0 oscillates only between the punch and the start position + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DOPunchAnchorPos(this RectTransform target, Vector2 punch, float duration, int vibrato = 10, float elasticity = 1, bool snapping = false) + { + return DOTween.Punch(() => target.anchoredPosition, x => target.anchoredPosition = x, punch, duration, vibrato, elasticity) + .SetTarget(target).SetOptions(snapping); + } + + /// Shakes a RectTransform's anchoredPosition with the given values. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the tween will smoothly snap all values to integers + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, float strength = 100, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true) + { + return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, true, fadeOut) + .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); + } + /// Shakes a RectTransform's anchoredPosition with the given values. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The duration of the tween + /// The shake strength on each axis + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the tween will smoothly snap all values to integers + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, Vector2 strength, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true) + { + return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, fadeOut) + .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); + } + + #region Special + + /// Tweens a RectTransform's anchoredPosition to the given value, while also applying a jump effect along the Y axis. + /// Returns a Sequence instead of a Tweener. + /// Also stores the RectTransform as the tween's target so it can be used for filtered operations + /// The end value to reach + /// Power of the jump (the max height of the jump is represented by this plus the final Y offset) + /// Total number of jumps + /// The duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Sequence DOJumpAnchorPos(this RectTransform target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false) + { + if (numJumps < 1) numJumps = 1; + float startPosY = 0; + float offsetY = -1; + bool offsetYSet = false; + + // Separate Y Tween so we can elaborate elapsedPercentage on that insted of on the Sequence + // (in case users add a delay or other elements to the Sequence) + Sequence s = DOTween.Sequence(); + Tween yTween = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, jumpPower), duration / (numJumps * 2)) + .SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative() + .SetLoops(numJumps * 2, LoopType.Yoyo) + .OnStart(()=> startPosY = target.anchoredPosition.y); + s.Append(DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue.x, 0), duration) + .SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear) + ).Join(yTween) + .SetTarget(target).SetEase(DOTween.defaultEaseType); + s.OnUpdate(() => { + if (!offsetYSet) { + offsetYSet = true; + offsetY = s.isRelative ? endValue.y : endValue.y - startPosY; + } + Vector2 pos = target.anchoredPosition; + pos.y += DOVirtual.EasedValue(0, offsetY, s.ElapsedDirectionalPercentage(), Ease.OutQuad); + target.anchoredPosition = pos; + }); + return s; + } + + #endregion + + #endregion + + #region ScrollRect + + /// Tweens a ScrollRect's horizontal/verticalNormalizedPosition to the given value. + /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DONormalizedPos(this ScrollRect target, Vector2 endValue, float duration, bool snapping = false) + { + return DOTween.To(() => new Vector2(target.horizontalNormalizedPosition, target.verticalNormalizedPosition), + x => { + target.horizontalNormalizedPosition = x.x; + target.verticalNormalizedPosition = x.y; + }, endValue, duration) + .SetOptions(snapping).SetTarget(target); + } + /// Tweens a ScrollRect's horizontalNormalizedPosition to the given value. + /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DOHorizontalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) + { + return DOTween.To(() => target.horizontalNormalizedPosition, x => target.horizontalNormalizedPosition = x, endValue, duration) + .SetOptions(snapping).SetTarget(target); + } + /// Tweens a ScrollRect's verticalNormalizedPosition to the given value. + /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DOVerticalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) + { + return DOTween.To(() => target.verticalNormalizedPosition, x => target.verticalNormalizedPosition = x, endValue, duration) + .SetOptions(snapping).SetTarget(target); + } + + #endregion + + #region Slider + + /// Tweens a Slider's value to the given value. + /// Also stores the Slider as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE the tween will smoothly snap all values to integers + public static TweenerCore DOValue(this Slider target, float endValue, float duration, bool snapping = false) + { + TweenerCore t = DOTween.To(() => target.value, x => target.value = x, endValue, duration); + t.SetOptions(snapping).SetTarget(target); + return t; + } + + #endregion + + #region Text + + /// Tweens a Text's color to the given value. + /// Also stores the Text as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this Text target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// + /// Tweens a Text's text from one integer to another, with options for thousands separators + /// + /// The value to start from + /// The end value to reach + /// The duration of the tween + /// If TRUE (default) also adds thousands separators + /// The to use (InvariantCulture if NULL) + public static TweenerCore DOCounter( + this Text target, int fromValue, int endValue, float duration, bool addThousandsSeparator = true, CultureInfo culture = null + ){ + int v = fromValue; + CultureInfo cInfo = !addThousandsSeparator ? null : culture ?? CultureInfo.InvariantCulture; + TweenerCore t = DOTween.To(() => v, x => { + v = x; + target.text = addThousandsSeparator + ? v.ToString("N0", cInfo) + : v.ToString(); + }, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Text's alpha color to the given value. + /// Also stores the Text as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this Text target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Text's text to the given value. + /// Also stores the Text as the tween's target so it can be used for filtered operations + /// The end string to tween toThe duration of the tween + /// If TRUE (default), rich text will be interpreted correctly while animated, + /// otherwise all tags will be considered as normal text + /// The type of scramble mode to use, if any + /// A string containing the characters to use for scrambling. + /// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. + /// Leave it to NULL (default) to use default ones + public static TweenerCore DOText(this Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null) + { + if (endValue == null) { + if (Debugger.logPriority > 0) Debugger.LogWarning("You can't pass a NULL string to DOText: an empty string will be used instead to avoid errors"); + endValue = ""; + } + TweenerCore t = DOTween.To(() => target.text, x => target.text = x, endValue, duration); + t.SetOptions(richTextEnabled, scrambleMode, scrambleChars) + .SetTarget(target); + return t; + } + + #endregion + + #region Blendables + + #region Graphic + + /// Tweens a Graphic's color to the given value, + /// in a way that allows other DOBlendableColor tweens to work together on the same target, + /// instead than fight each other as multiple DOColor would do. + /// Also stores the Graphic as the tween's target so it can be used for filtered operations + /// The value to tween toThe duration of the tween + public static Tweener DOBlendableColor(this Graphic target, Color endValue, float duration) + { + endValue = endValue - target.color; + Color to = new Color(0, 0, 0, 0); + return DOTween.To(() => to, x => { + Color diff = x - to; + to = x; + target.color += diff; + }, endValue, duration) + .Blendable().SetTarget(target); + } + + #endregion + + #region Image + + /// Tweens a Image's color to the given value, + /// in a way that allows other DOBlendableColor tweens to work together on the same target, + /// instead than fight each other as multiple DOColor would do. + /// Also stores the Image as the tween's target so it can be used for filtered operations + /// The value to tween toThe duration of the tween + public static Tweener DOBlendableColor(this Image target, Color endValue, float duration) + { + endValue = endValue - target.color; + Color to = new Color(0, 0, 0, 0); + return DOTween.To(() => to, x => { + Color diff = x - to; + to = x; + target.color += diff; + }, endValue, duration) + .Blendable().SetTarget(target); + } + + #endregion + + #region Text + + /// Tweens a Text's color BY the given value, + /// in a way that allows other DOBlendableColor tweens to work together on the same target, + /// instead than fight each other as multiple DOColor would do. + /// Also stores the Text as the tween's target so it can be used for filtered operations + /// The value to tween toThe duration of the tween + public static Tweener DOBlendableColor(this Text target, Color endValue, float duration) + { + endValue = endValue - target.color; + Color to = new Color(0, 0, 0, 0); + return DOTween.To(() => to, x => { + Color diff = x - to; + to = x; + target.color += diff; + }, endValue, duration) + .Blendable().SetTarget(target); + } + + #endregion + + #endregion + + #endregion + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + public static class Utils + { + /// + /// Converts the anchoredPosition of the first RectTransform to the second RectTransform, + /// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition + /// + public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to) + { + Vector2 localPoint; + Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin); + Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position); + screenP += fromPivotDerivedOffset; + RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint); + Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin); + return to.anchoredPosition + localPoint - pivotDerivedOffset; + } + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs.meta new file mode 100644 index 0000000..60d55ef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUI.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a060394c03331a64392db53a10e7f2d1 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs new file mode 100644 index 0000000..49a22bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs @@ -0,0 +1,403 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +using System; +using UnityEngine; +using DG.Tweening.Core; +using DG.Tweening.Plugins.Options; +#if UNITY_2018_1_OR_NEWER && (NET_4_6 || NET_STANDARD_2_0) +using System.Threading.Tasks; +#endif + +#pragma warning disable 1591 +namespace DG.Tweening +{ + /// + /// Shortcuts/functions that are not strictly related to specific Modules + /// but are available only on some Unity versions + /// + public static class DOTweenModuleUnityVersion + { +#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER + #region Unity 4.3 or Newer + + #region Material + + /// Tweens a Material's color using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to useThe duration of the tween + public static Sequence DOGradientColor(this Material target, Gradient gradient, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.color = c.color; + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + /// Tweens a Material's named color property using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to use + /// The name of the material property to tween (like _Tint or _SpecColor) + /// The duration of the tween + public static Sequence DOGradientColor(this Material target, Gradient gradient, string property, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.SetColor(property, c.color); + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, property, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + + #endregion + + #endregion +#endif + +#if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER + #region Unity 5.3 or Newer + + #region CustomYieldInstructions + + /// + /// Returns a that waits until the tween is killed or complete. + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForCompletion(true); + /// + public static CustomYieldInstruction WaitForCompletion(this Tween t, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForCompletion(t); + } + + /// + /// Returns a that waits until the tween is killed or rewinded. + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForRewind(); + /// + public static CustomYieldInstruction WaitForRewind(this Tween t, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForRewind(t); + } + + /// + /// Returns a that waits until the tween is killed. + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForKill(); + /// + public static CustomYieldInstruction WaitForKill(this Tween t, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForKill(t); + } + + /// + /// Returns a that waits until the tween is killed or has gone through the given amount of loops. + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForElapsedLoops(2); + /// + /// Elapsed loops to wait for + public static CustomYieldInstruction WaitForElapsedLoops(this Tween t, int elapsedLoops, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForElapsedLoops(t, elapsedLoops); + } + + /// + /// Returns a that waits until the tween is killed + /// or has reached the given time position (loops included, delays excluded). + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForPosition(2.5f); + /// + /// Position (loops included, delays excluded) to wait for + public static CustomYieldInstruction WaitForPosition(this Tween t, float position, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForPosition(t, position); + } + + /// + /// Returns a that waits until the tween is killed or started + /// (meaning when the tween is set in a playing state the first time, after any eventual delay). + /// It can be used inside a coroutine as a yield. + /// Example usage:yield return myTween.WaitForStart(); + /// + public static CustomYieldInstruction WaitForStart(this Tween t, bool returnCustomYieldInstruction) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return null; + } + return new DOTweenCYInstruction.WaitForStart(t); + } + + #endregion + + #endregion +#endif + +#if UNITY_2018_1_OR_NEWER + #region Unity 2018.1 or Newer + + #region Material + + /// Tweens a Material's named texture offset property with the given ID to the given value. + /// Also stores the material as the tween's target so it can be used for filtered operations + /// The end value to reach + /// The ID of the material property to tween (also called nameID in Unity's manual) + /// The duration of the tween + public static TweenerCore DOOffset(this Material target, Vector2 endValue, int propertyID, float duration) + { + if (!target.HasProperty(propertyID)) { + if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); + return null; + } + TweenerCore t = DOTween.To(() => target.GetTextureOffset(propertyID), x => target.SetTextureOffset(propertyID, x), endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a Material's named texture scale property with the given ID to the given value. + /// Also stores the material as the tween's target so it can be used for filtered operations + /// The end value to reach + /// The ID of the material property to tween (also called nameID in Unity's manual) + /// The duration of the tween + public static TweenerCore DOTiling(this Material target, Vector2 endValue, int propertyID, float duration) + { + if (!target.HasProperty(propertyID)) { + if (Debugger.logPriority > 0) Debugger.LogMissingMaterialProperty(propertyID); + return null; + } + TweenerCore t = DOTween.To(() => target.GetTextureScale(propertyID), x => target.SetTextureScale(propertyID, x), endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + + #region .NET 4.6 or Newer + +#if (NET_4_6 || NET_STANDARD_2_0) + + #region Async Instructions + + /// + /// Returns an async that waits until the tween is killed or complete. + /// It can be used inside an async operation. + /// Example usage:await myTween.WaitForCompletion(); + /// + public static async Task AsyncWaitForCompletion(this Tween t) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active && !t.IsComplete()) await Task.Yield(); + } + + /// + /// Returns an async that waits until the tween is killed or rewinded. + /// It can be used inside an async operation. + /// Example usage:await myTween.AsyncWaitForRewind(); + /// + public static async Task AsyncWaitForRewind(this Tween t) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0)) await Task.Yield(); + } + + /// + /// Returns an async that waits until the tween is killed. + /// It can be used inside an async operation. + /// Example usage:await myTween.AsyncWaitForKill(); + /// + public static async Task AsyncWaitForKill(this Tween t) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active) await Task.Yield(); + } + + /// + /// Returns an async that waits until the tween is killed or has gone through the given amount of loops. + /// It can be used inside an async operation. + /// Example usage:await myTween.AsyncWaitForElapsedLoops(); + /// + /// Elapsed loops to wait for + public static async Task AsyncWaitForElapsedLoops(this Tween t, int elapsedLoops) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active && t.CompletedLoops() < elapsedLoops) await Task.Yield(); + } + + /// + /// Returns an async that waits until the tween is killed or started + /// (meaning when the tween is set in a playing state the first time, after any eventual delay). + /// It can be used inside an async operation. + /// Example usage:await myTween.AsyncWaitForPosition(); + /// + /// Position (loops included, delays excluded) to wait for + public static async Task AsyncWaitForPosition(this Tween t, float position) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active && t.position * (t.CompletedLoops() + 1) < position) await Task.Yield(); + } + + /// + /// Returns an async that waits until the tween is killed. + /// It can be used inside an async operation. + /// Example usage:await myTween.AsyncWaitForKill(); + /// + public static async Task AsyncWaitForStart(this Tween t) + { + if (!t.active) { + if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t); + return; + } + while (t.active && !t.playedOnce) await Task.Yield(); + } + + #endregion +#endif + + #endregion + + #endregion +#endif + } + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ CLASSES █████████████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + +#if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER + public static class DOTweenCYInstruction + { + public class WaitForCompletion : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active && !t.IsComplete(); + }} + readonly Tween t; + public WaitForCompletion(Tween tween) + { + t = tween; + } + } + + public class WaitForRewind : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0); + }} + readonly Tween t; + public WaitForRewind(Tween tween) + { + t = tween; + } + } + + public class WaitForKill : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active; + }} + readonly Tween t; + public WaitForKill(Tween tween) + { + t = tween; + } + } + + public class WaitForElapsedLoops : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active && t.CompletedLoops() < elapsedLoops; + }} + readonly Tween t; + readonly int elapsedLoops; + public WaitForElapsedLoops(Tween tween, int elapsedLoops) + { + t = tween; + this.elapsedLoops = elapsedLoops; + } + } + + public class WaitForPosition : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active && t.position * (t.CompletedLoops() + 1) < position; + }} + readonly Tween t; + readonly float position; + public WaitForPosition(Tween tween, float position) + { + t = tween; + this.position = position; + } + } + + public class WaitForStart : CustomYieldInstruction + { + public override bool keepWaiting { get { + return t.active && !t.playedOnce; + }} + readonly Tween t; + public WaitForStart(Tween tween) + { + t = tween; + } + } + } +#endif +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs.meta new file mode 100644 index 0000000..290189f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUnityVersion.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 63c02322328255542995bd02b47b0457 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs new file mode 100644 index 0000000..8a1fb5f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs @@ -0,0 +1,155 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +using System; +using System.Reflection; +using UnityEngine; +using DG.Tweening.Core; +using DG.Tweening.Plugins.Core.PathCore; +using DG.Tweening.Plugins.Options; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + /// + /// Utility functions that deal with available Modules. + /// Modules defines: + /// - DOTAUDIO + /// - DOTPHYSICS + /// - DOTPHYSICS2D + /// - DOTSPRITE + /// - DOTUI + /// Extra defines set and used for implementation of external assets: + /// - DOTWEEN_TMP ► TextMesh Pro + /// - DOTWEEN_TK2D ► 2D Toolkit + /// + public static class DOTweenModuleUtils + { + static bool _initialized; + + #region Reflection + + /// + /// Called via Reflection by DOTweenComponent on Awake + /// +#if UNITY_2018_1_OR_NEWER + [UnityEngine.Scripting.Preserve] +#endif + public static void Init() + { + if (_initialized) return; + + _initialized = true; + DOTweenExternalCommand.SetOrientationOnPath += Physics.SetOrientationOnPath; + +#if UNITY_EDITOR +#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 + UnityEditor.EditorApplication.playmodeStateChanged += PlaymodeStateChanged; +#else + UnityEditor.EditorApplication.playModeStateChanged += PlaymodeStateChanged; +#endif +#endif + } + +#if UNITY_2018_1_OR_NEWER +#pragma warning disable + [UnityEngine.Scripting.Preserve] + // Just used to preserve methods when building, never called + static void Preserver() + { + Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); + MethodInfo mi = typeof(MonoBehaviour).GetMethod("Stub"); + } +#pragma warning restore +#endif + + #endregion + +#if UNITY_EDITOR + // Fires OnApplicationPause in DOTweenComponent even when Editor is paused (otherwise it's only fired at runtime) +#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1 + static void PlaymodeStateChanged() + #else + static void PlaymodeStateChanged(UnityEditor.PlayModeStateChange state) +#endif + { + if (DOTween.instance == null) return; + DOTween.instance.OnApplicationPause(UnityEditor.EditorApplication.isPaused); + } +#endif + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + public static class Physics + { + // Called via DOTweenExternalCommand callback + public static void SetOrientationOnPath(PathOptions options, Tween t, Quaternion newRot, Transform trans) + { +#if true // PHYSICS_MARKER + if (options.isRigidbody) ((Rigidbody)t.target).rotation = newRot; + else trans.rotation = newRot; +#else + trans.rotation = newRot; +#endif + } + + // Returns FALSE if the DOTween's Physics2D Module is disabled, or if there's no Rigidbody2D attached + public static bool HasRigidbody2D(Component target) + { +#if true // PHYSICS2D_MARKER + return target.GetComponent() != null; +#else + return false; +#endif + } + + #region Called via Reflection + + + // Called via Reflection by DOTweenPathInspector + // Returns FALSE if the DOTween's Physics Module is disabled, or if there's no rigidbody attached +#if UNITY_2018_1_OR_NEWER + [UnityEngine.Scripting.Preserve] +#endif + public static bool HasRigidbody(Component target) + { +#if true // PHYSICS_MARKER + return target.GetComponent() != null; +#else + return false; +#endif + } + + // Called via Reflection by DOTweenPath +#if UNITY_2018_1_OR_NEWER + [UnityEngine.Scripting.Preserve] +#endif + public static TweenerCore CreateDOTweenPathTween( + MonoBehaviour target, bool tweenRigidbody, bool isLocal, Path path, float duration, PathMode pathMode + ){ + TweenerCore t; +#if true // PHYSICS_MARKER + Rigidbody rBody = tweenRigidbody ? target.GetComponent() : null; + if (tweenRigidbody && rBody != null) { + t = isLocal + ? rBody.DOLocalPath(path, duration, pathMode) + : rBody.DOPath(path, duration, pathMode); + } else { + t = isLocal + ? target.transform.DOLocalPath(path, duration, pathMode) + : target.transform.DOPath(path, duration, pathMode); + } +#else + t = isLocal + ? target.transform.DOLocalPath(path, duration, pathMode) + : target.transform.DOPath(path, duration, pathMode); +#endif + return t; + } + + #endregion + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs.meta new file mode 100644 index 0000000..ab62186 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Modules/DOTweenModuleUtils.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7bcaf917d9cf5b84090421a5a2abe42e +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources.meta new file mode 100644 index 0000000..ea779af --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1d45f368f9767a844ad25329da61c55e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset new file mode 100644 index 0000000..61a3216 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset @@ -0,0 +1,50 @@ +%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: 16995157, guid: a811bde74b26b53498b4f6d872b09b6d, type: 3} + m_Name: DOTweenSettings + m_EditorClassIdentifier: + useSafeMode: 1 + safeModeOptions: + nestedTweenFailureBehaviour: 0 + timeScale: 1 + useSmoothDeltaTime: 0 + maxSmoothUnscaledTime: 0.15 + rewindCallbackMode: 0 + showUnityEditorReport: 0 + logBehaviour: 1 + drawGizmos: 1 + defaultRecyclable: 0 + defaultAutoPlay: 3 + defaultUpdateType: 0 + defaultTimeScaleIndependent: 0 + defaultEaseType: 6 + defaultEaseOvershootOrAmplitude: 1.70158 + defaultEasePeriod: 0 + defaultAutoKill: 1 + defaultLoopType: 0 + debugMode: 0 + debugStoreTargetId: 0 + showPreviewPanel: 1 + storeSettingsLocation: 1 + modules: + showPanel: 0 + audioEnabled: 1 + physicsEnabled: 1 + physics2DEnabled: 1 + spriteEnabled: 1 + uiEnabled: 1 + textMeshProEnabled: 1 + tk2DEnabled: 0 + deAudioEnabled: 0 + deUnityExtendedEnabled: 0 + showPlayingTweens: 0 + showPausedTweens: 0 diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset.meta new file mode 100644 index 0000000..3b2b69f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/Resources/DOTweenSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1c0cb3c94361544b85a847569b6491d +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt new file mode 100644 index 0000000..37ff7ef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt @@ -0,0 +1,29 @@ +DOTween and DOTween Pro are copyright (c) 2014-2018 Daniele Giardini - Demigiant + +// IMPORTANT!!! ///////////////////////////////////////////// +// Upgrading DOTween from versions older than 1.2.000 /////// +// (or DOTween Pro older than 1.0.000) ////////////////////// +------------------------------------------------------------- +If you're upgrading your project from a version of DOTween older than 1.2.000 (or DOTween Pro older than 1.0.000) please follow these instructions carefully. +1) Import the new version in the same folder as the previous one, overwriting old files. A lot of errors will appear but don't worry +2) Close and reopen Unity (and your project). This is fundamental: skipping this step will cause a bloodbath +3) Open DOTween's Utility Panel (Tools > Demigiant > DOTween Utility Panel) if it doesn't open automatically, then press "Setup DOTween...": this will run the upgrade setup +4) From the Add/Remove Modules panel that opens, activate/deactivate Modules for Unity systems and for external assets (Pro version only) + +// GET STARTED ////////////////////////////////////////////// + +- After importing a new DOTween update, select DOTween's Utility Panel from the "Tools/Demigiant" menu (if it doesn't open automatically) and press the "Setup DOTween..." button to activate/deactivate Modules. You can also access a Preferences Tab from there to choose default settings for DOTween. +- In your code, add "using DG.Tweening" to each class where you want to use DOTween. +- You're ready to tween. Check out the links below for full documentation and license info. + + +// LINKS /////////////////////////////////////////////////////// + +DOTween website (documentation, examples, etc): http://dotween.demigiant.com +DOTween license: http://dotween.demigiant.com/license.php +DOTween repository (Google Code): https://code.google.com/p/dotween/ +Demigiant website (documentation, examples, etc): http://www.demigiant.com + +// NOTES ////////////////////////////////////////////////////// + +- DOTween's Utility Panel can be found under "Tools > Demigiant > DOTween Utility Panel" and also contains other useful options, plus a tab to set DOTween's preferences \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt.meta new file mode 100644 index 0000000..3799165 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTween/readme.txt.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: fccfc62abf2eb0a4db614853430894fd +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro.meta new file mode 100644 index 0000000..659537c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: af55cfd0e7084ab4884c5a4f29b62d9f +labels: +- Tween +- Tweening +- Animation +- HOTween +- Paths +- VisualScripting +- VisualEditor +- iTween +- DFTween +- LeanTween +- Ease +- Easing +- Shake +- Punch +- 2DToolkit +- TextMeshPro +- Text +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs new file mode 100644 index 0000000..e130f06 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs @@ -0,0 +1,716 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/12 15:55 + +using System; +using System.Collections.Generic; +using DG.Tweening.Core; +using UnityEngine; +#if true // UI_MARKER +using UnityEngine.UI; +#endif +#if true // TEXTMESHPRO_MARKER +using TMPro; +#endif + +#pragma warning disable 1591 +namespace DG.Tweening +{ + /// + /// Attach this to a GameObject to create a tween + /// + [AddComponentMenu("DOTween/DOTween Animation")] + public class DOTweenAnimation : ABSAnimationComponent + { + public enum AnimationType + { + None, + Move, LocalMove, + Rotate, LocalRotate, + Scale, + Color, Fade, + Text, + PunchPosition, PunchRotation, PunchScale, + ShakePosition, ShakeRotation, ShakeScale, + CameraAspect, CameraBackgroundColor, CameraFieldOfView, CameraOrthoSize, CameraPixelRect, CameraRect, + UIWidthHeight + } + + public enum TargetType + { + Unset, + + Camera, + CanvasGroup, + Image, + Light, + RectTransform, + Renderer, SpriteRenderer, + Rigidbody, Rigidbody2D, + Text, + Transform, + + tk2dBaseSprite, + tk2dTextMesh, + + TextMeshPro, + TextMeshProUGUI + } + + #region EVENTS - EDITOR-ONLY + + /// Used internally by the editor + public static event Action OnReset; + static void Dispatch_OnReset(DOTweenAnimation anim) { if (OnReset != null) OnReset(anim); } + + #endregion + + public bool targetIsSelf = true; // If FALSE allows to set the target manually + public GameObject targetGO = null; // Used in case targetIsSelf is FALSE + // If TRUE always uses the GO containing this DOTweenAnimation (and not the one containing the target) as DOTween's SetTarget target + public bool tweenTargetIsTargetGO = true; + + public float delay; + public float duration = 1; + public Ease easeType = Ease.OutQuad; + public AnimationCurve easeCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1)); + public LoopType loopType = LoopType.Restart; + public int loops = 1; + public string id = ""; + public bool isRelative; + public bool isFrom; + public bool isIndependentUpdate = false; + public bool autoKill = true; + + public bool isActive = true; + public bool isValid; + public Component target; + public AnimationType animationType; + public TargetType targetType; + public TargetType forcedTargetType; // Used when choosing between multiple targets + public bool autoPlay = true; + public bool useTargetAsV3; + + public float endValueFloat; + public Vector3 endValueV3; + public Vector2 endValueV2; + public Color endValueColor = new Color(1, 1, 1, 1); + public string endValueString = ""; + public Rect endValueRect = new Rect(0, 0, 0, 0); + public Transform endValueTransform; + + public bool optionalBool0; + public float optionalFloat0; + public int optionalInt0; + public RotateMode optionalRotationMode = RotateMode.Fast; + public ScrambleMode optionalScrambleMode = ScrambleMode.None; + public string optionalString; + + bool _tweenCreated; // TRUE after the tweens have been created + int _playCount = -1; // Used when calling DOPlayNext + + #region Unity Methods + + void Awake() + { + if (!isActive || !isValid) return; + + if (animationType != AnimationType.Move || !useTargetAsV3) { + // Don't create tweens if we're using a RectTransform as a Move target, + // because that will work only inside Start + CreateTween(); + _tweenCreated = true; + } + } + + void Start() + { + if (_tweenCreated || !isActive || !isValid) return; + + CreateTween(); + _tweenCreated = true; + } + + void Reset() + { + Dispatch_OnReset(this); + } + + void OnDestroy() + { + if (tween != null && tween.IsActive()) tween.Kill(); + tween = null; + } + + // Used also by DOTweenAnimationInspector when applying runtime changes and restarting + public void CreateTween() + { +// if (target == null) { +// Debug.LogWarning(string.Format("{0} :: This DOTweenAnimation's target is NULL, because the animation was created with a DOTween Pro version older than 0.9.255. To fix this, exit Play mode then simply select this object, and it will update automatically", this.gameObject.name), this.gameObject); +// return; +// } + + GameObject tweenGO = GetTweenGO(); + if (target == null || tweenGO == null) { + if (targetIsSelf && target == null) { + // Old error caused during upgrade from DOTween Pro 0.9.255 + Debug.LogWarning(string.Format("{0} :: This DOTweenAnimation's target is NULL, because the animation was created with a DOTween Pro version older than 0.9.255. To fix this, exit Play mode then simply select this object, and it will update automatically", this.gameObject.name), this.gameObject); + } else { + // Missing non-self target + Debug.LogWarning(string.Format("{0} :: This DOTweenAnimation's target/GameObject is unset: the tween will not be created.", this.gameObject.name), this.gameObject); + } + return; + } + + if (forcedTargetType != TargetType.Unset) targetType = forcedTargetType; + if (targetType == TargetType.Unset) { + // Legacy DOTweenAnimation (made with a version older than 0.9.450) without stored targetType > assign it now + targetType = TypeToDOTargetType(target.GetType()); + } + + switch (animationType) { + case AnimationType.None: + break; + case AnimationType.Move: + if (useTargetAsV3) { + isRelative = false; + if (endValueTransform == null) { + Debug.LogWarning(string.Format("{0} :: This tween's TO target is NULL, a Vector3 of (0,0,0) will be used instead", this.gameObject.name), this.gameObject); + endValueV3 = Vector3.zero; + } else { +#if true // UI_MARKER + if (targetType == TargetType.RectTransform) { + RectTransform endValueT = endValueTransform as RectTransform; + if (endValueT == null) { + Debug.LogWarning(string.Format("{0} :: This tween's TO target should be a RectTransform, a Vector3 of (0,0,0) will be used instead", this.gameObject.name), this.gameObject); + endValueV3 = Vector3.zero; + } else { + RectTransform rTarget = target as RectTransform; + if (rTarget == null) { + Debug.LogWarning(string.Format("{0} :: This tween's target and TO target are not of the same type. Please reassign the values", this.gameObject.name), this.gameObject); + } else { + // Problem: doesn't work inside Awake (ararargh!) + endValueV3 = DOTweenModuleUI.Utils.SwitchToRectTransform(endValueT, rTarget); + } + } + } else +#endif + endValueV3 = endValueTransform.position; + } + } + switch (targetType) { + case TargetType.Transform: + tween = ((Transform)target).DOMove(endValueV3, duration, optionalBool0); + break; + case TargetType.RectTransform: +#if true // UI_MARKER + tween = ((RectTransform)target).DOAnchorPos3D(endValueV3, duration, optionalBool0); +#else + tween = ((Transform)target).DOMove(endValueV3, duration, optionalBool0); +#endif + break; + case TargetType.Rigidbody: +#if true // PHYSICS_MARKER + tween = ((Rigidbody)target).DOMove(endValueV3, duration, optionalBool0); +#else + tween = ((Transform)target).DOMove(endValueV3, duration, optionalBool0); +#endif + break; + case TargetType.Rigidbody2D: +#if true // PHYSICS2D_MARKER + tween = ((Rigidbody2D)target).DOMove(endValueV3, duration, optionalBool0); +#else + tween = ((Transform)target).DOMove(endValueV3, duration, optionalBool0); +#endif + break; + } + break; + case AnimationType.LocalMove: + tween = tweenGO.transform.DOLocalMove(endValueV3, duration, optionalBool0); + break; + case AnimationType.Rotate: + switch (targetType) { + case TargetType.Transform: + tween = ((Transform)target).DORotate(endValueV3, duration, optionalRotationMode); + break; + case TargetType.Rigidbody: +#if true // PHYSICS_MARKER + tween = ((Rigidbody)target).DORotate(endValueV3, duration, optionalRotationMode); +#else + tween = ((Transform)target).DORotate(endValueV3, duration, optionalRotationMode); +#endif + break; + case TargetType.Rigidbody2D: +#if true // PHYSICS2D_MARKER + tween = ((Rigidbody2D)target).DORotate(endValueFloat, duration); +#else + tween = ((Transform)target).DORotate(endValueV3, duration, optionalRotationMode); +#endif + break; + } + break; + case AnimationType.LocalRotate: + tween = tweenGO.transform.DOLocalRotate(endValueV3, duration, optionalRotationMode); + break; + case AnimationType.Scale: + switch (targetType) { +#if false // TK2D_MARKER + case TargetType.tk2dTextMesh: + tween = ((tk2dTextMesh)target).DOScale(optionalBool0 ? new Vector3(endValueFloat, endValueFloat, endValueFloat) : endValueV3, duration); + break; + case TargetType.tk2dBaseSprite: + tween = ((tk2dBaseSprite)target).DOScale(optionalBool0 ? new Vector3(endValueFloat, endValueFloat, endValueFloat) : endValueV3, duration); + break; +#endif + default: + tween = tweenGO.transform.DOScale(optionalBool0 ? new Vector3(endValueFloat, endValueFloat, endValueFloat) : endValueV3, duration); + break; + } + break; +#if true // UI_MARKER + case AnimationType.UIWidthHeight: + tween = ((RectTransform)target).DOSizeDelta(optionalBool0 ? new Vector2(endValueFloat, endValueFloat) : endValueV2, duration); + break; +#endif + case AnimationType.Color: + isRelative = false; + switch (targetType) { + case TargetType.Renderer: + tween = ((Renderer)target).material.DOColor(endValueColor, duration); + break; + case TargetType.Light: + tween = ((Light)target).DOColor(endValueColor, duration); + break; +#if true // SPRITE_MARKER + case TargetType.SpriteRenderer: + tween = ((SpriteRenderer)target).DOColor(endValueColor, duration); + break; +#endif +#if true // UI_MARKER + case TargetType.Image: + tween = ((Graphic)target).DOColor(endValueColor, duration); + break; + case TargetType.Text: + tween = ((Text)target).DOColor(endValueColor, duration); + break; +#endif +#if false // TK2D_MARKER + case TargetType.tk2dTextMesh: + tween = ((tk2dTextMesh)target).DOColor(endValueColor, duration); + break; + case TargetType.tk2dBaseSprite: + tween = ((tk2dBaseSprite)target).DOColor(endValueColor, duration); + break; +#endif +#if true // TEXTMESHPRO_MARKER + case TargetType.TextMeshProUGUI: + tween = ((TextMeshProUGUI)target).DOColor(endValueColor, duration); + break; + case TargetType.TextMeshPro: + tween = ((TextMeshPro)target).DOColor(endValueColor, duration); + break; +#endif + } + break; + case AnimationType.Fade: + isRelative = false; + switch (targetType) { + case TargetType.Renderer: + tween = ((Renderer)target).material.DOFade(endValueFloat, duration); + break; + case TargetType.Light: + tween = ((Light)target).DOIntensity(endValueFloat, duration); + break; +#if true // SPRITE_MARKER + case TargetType.SpriteRenderer: + tween = ((SpriteRenderer)target).DOFade(endValueFloat, duration); + break; +#endif +#if true // UI_MARKER + case TargetType.Image: + tween = ((Graphic)target).DOFade(endValueFloat, duration); + break; + case TargetType.Text: + tween = ((Text)target).DOFade(endValueFloat, duration); + break; + case TargetType.CanvasGroup: + tween = ((CanvasGroup)target).DOFade(endValueFloat, duration); + break; +#endif +#if false // TK2D_MARKER + case TargetType.tk2dTextMesh: + tween = ((tk2dTextMesh)target).DOFade(endValueFloat, duration); + break; + case TargetType.tk2dBaseSprite: + tween = ((tk2dBaseSprite)target).DOFade(endValueFloat, duration); + break; +#endif +#if true // TEXTMESHPRO_MARKER + case TargetType.TextMeshProUGUI: + tween = ((TextMeshProUGUI)target).DOFade(endValueFloat, duration); + break; + case TargetType.TextMeshPro: + tween = ((TextMeshPro)target).DOFade(endValueFloat, duration); + break; +#endif + } + break; + case AnimationType.Text: +#if true // UI_MARKER + switch (targetType) { + case TargetType.Text: + tween = ((Text)target).DOText(endValueString, duration, optionalBool0, optionalScrambleMode, optionalString); + break; + } +#endif +#if false // TK2D_MARKER + switch (targetType) { + case TargetType.tk2dTextMesh: + tween = ((tk2dTextMesh)target).DOText(endValueString, duration, optionalBool0, optionalScrambleMode, optionalString); + break; + } +#endif +#if true // TEXTMESHPRO_MARKER + switch (targetType) { + case TargetType.TextMeshProUGUI: + tween = ((TextMeshProUGUI)target).DOText(endValueString, duration, optionalBool0, optionalScrambleMode, optionalString); + break; + case TargetType.TextMeshPro: + tween = ((TextMeshPro)target).DOText(endValueString, duration, optionalBool0, optionalScrambleMode, optionalString); + break; + } +#endif + break; + case AnimationType.PunchPosition: + switch (targetType) { + case TargetType.Transform: + tween = ((Transform)target).DOPunchPosition(endValueV3, duration, optionalInt0, optionalFloat0, optionalBool0); + break; +#if true // UI_MARKER + case TargetType.RectTransform: + tween = ((RectTransform)target).DOPunchAnchorPos(endValueV3, duration, optionalInt0, optionalFloat0, optionalBool0); + break; +#endif + } + break; + case AnimationType.PunchScale: + tween = tweenGO.transform.DOPunchScale(endValueV3, duration, optionalInt0, optionalFloat0); + break; + case AnimationType.PunchRotation: + tween = tweenGO.transform.DOPunchRotation(endValueV3, duration, optionalInt0, optionalFloat0); + break; + case AnimationType.ShakePosition: + switch (targetType) { + case TargetType.Transform: + tween = ((Transform)target).DOShakePosition(duration, endValueV3, optionalInt0, optionalFloat0, optionalBool0); + break; +#if true // UI_MARKER + case TargetType.RectTransform: + tween = ((RectTransform)target).DOShakeAnchorPos(duration, endValueV3, optionalInt0, optionalFloat0, optionalBool0); + break; +#endif + } + break; + case AnimationType.ShakeScale: + tween = tweenGO.transform.DOShakeScale(duration, endValueV3, optionalInt0, optionalFloat0); + break; + case AnimationType.ShakeRotation: + tween = tweenGO.transform.DOShakeRotation(duration, endValueV3, optionalInt0, optionalFloat0); + break; + case AnimationType.CameraAspect: + tween = ((Camera)target).DOAspect(endValueFloat, duration); + break; + case AnimationType.CameraBackgroundColor: + tween = ((Camera)target).DOColor(endValueColor, duration); + break; + case AnimationType.CameraFieldOfView: + tween = ((Camera)target).DOFieldOfView(endValueFloat, duration); + break; + case AnimationType.CameraOrthoSize: + tween = ((Camera)target).DOOrthoSize(endValueFloat, duration); + break; + case AnimationType.CameraPixelRect: + tween = ((Camera)target).DOPixelRect(endValueRect, duration); + break; + case AnimationType.CameraRect: + tween = ((Camera)target).DORect(endValueRect, duration); + break; + } + + if (tween == null) return; + + if (isFrom) { + ((Tweener)tween).From(isRelative); + } else { + tween.SetRelative(isRelative); + } + GameObject setTarget = targetIsSelf || !tweenTargetIsTargetGO ? this.gameObject : targetGO; + tween.SetTarget(setTarget).SetDelay(delay).SetLoops(loops, loopType).SetAutoKill(autoKill) + .OnKill(()=> tween = null); + if (isSpeedBased) tween.SetSpeedBased(); + if (easeType == Ease.INTERNAL_Custom) tween.SetEase(easeCurve); + else tween.SetEase(easeType); + if (!string.IsNullOrEmpty(id)) tween.SetId(id); + tween.SetUpdate(isIndependentUpdate); + + if (hasOnStart) { + if (onStart != null) tween.OnStart(onStart.Invoke); + } else onStart = null; + if (hasOnPlay) { + if (onPlay != null) tween.OnPlay(onPlay.Invoke); + } else onPlay = null; + if (hasOnUpdate) { + if (onUpdate != null) tween.OnUpdate(onUpdate.Invoke); + } else onUpdate = null; + if (hasOnStepComplete) { + if (onStepComplete != null) tween.OnStepComplete(onStepComplete.Invoke); + } else onStepComplete = null; + if (hasOnComplete) { + if (onComplete != null) tween.OnComplete(onComplete.Invoke); + } else onComplete = null; + if (hasOnRewind) { + if (onRewind != null) tween.OnRewind(onRewind.Invoke); + } else onRewind = null; + + if (autoPlay) tween.Play(); + else tween.Pause(); + + if (hasOnTweenCreated && onTweenCreated != null) onTweenCreated.Invoke(); + } + + #endregion + + #region Public Methods + + // These methods are here so they can be called directly via Unity's UGUI event system + + public override void DOPlay() + { + DOTween.Play(this.gameObject); + } + + public override void DOPlayBackwards() + { + DOTween.PlayBackwards(this.gameObject); + } + + public override void DOPlayForward() + { + DOTween.PlayForward(this.gameObject); + } + + public override void DOPause() + { + DOTween.Pause(this.gameObject); + } + + public override void DOTogglePause() + { + DOTween.TogglePause(this.gameObject); + } + + public override void DORewind() + { + _playCount = -1; + // Rewind using Components order (in case there are multiple animations on the same property) + DOTweenAnimation[] anims = this.gameObject.GetComponents(); + for (int i = anims.Length - 1; i > -1; --i) { + Tween t = anims[i].tween; + if (t != null && t.IsInitialized()) anims[i].tween.Rewind(); + } + // DOTween.Rewind(this.gameObject); + } + + /// + /// Restarts the tween + /// + public override void DORestart() + { DORestart(false); } + /// + /// Restarts the tween + /// + /// If TRUE, re-evaluates the tween's start and end values from its current position. + /// Set it to TRUE when spawning the same DOTweenAnimation in different positions (like when using a pooling system) + public override void DORestart(bool fromHere) + { + _playCount = -1; + if (tween == null) { + if (Debugger.logPriority > 1) Debugger.LogNullTween(tween); return; + } + if (fromHere && isRelative) ReEvaluateRelativeTween(); + DOTween.Restart(this.gameObject); + } + + public override void DOComplete() + { + DOTween.Complete(this.gameObject); + } + + public override void DOKill() + { + DOTween.Kill(this.gameObject); + tween = null; + } + + #region Specifics + + public void DOPlayById(string id) + { + DOTween.Play(this.gameObject, id); + } + public void DOPlayAllById(string id) + { + DOTween.Play(id); + } + + public void DOPauseAllById(string id) + { + DOTween.Pause(id); + } + + public void DOPlayBackwardsById(string id) + { + DOTween.PlayBackwards(this.gameObject, id); + } + public void DOPlayBackwardsAllById(string id) + { + DOTween.PlayBackwards(id); + } + + public void DOPlayForwardById(string id) + { + DOTween.PlayForward(this.gameObject, id); + } + public void DOPlayForwardAllById(string id) + { + DOTween.PlayForward(id); + } + + public void DOPlayNext() + { + DOTweenAnimation[] anims = this.GetComponents(); + while (_playCount < anims.Length - 1) { + _playCount++; + DOTweenAnimation anim = anims[_playCount]; + if (anim != null && anim.tween != null && !anim.tween.IsPlaying() && !anim.tween.IsComplete()) { + anim.tween.Play(); + break; + } + } + } + + public void DORewindAndPlayNext() + { + _playCount = -1; + DOTween.Rewind(this.gameObject); + DOPlayNext(); + } + + public void DORewindAllById(string id) + { + _playCount = -1; + DOTween.Rewind(id); + } + + public void DORestartById(string id) + { + _playCount = -1; + DOTween.Restart(this.gameObject, id); + } + public void DORestartAllById(string id) + { + _playCount = -1; + DOTween.Restart(id); + } + + /// + /// Returns the tweens created by this DOTweenAnimation, in the same order as they appear in the Inspector (top to bottom) + /// + public List GetTweens() + { +// return DOTween.TweensByTarget(this.gameObject); + + List result = new List(); + DOTweenAnimation[] anims = this.GetComponents(); + foreach (DOTweenAnimation anim in anims) result.Add(anim.tween); + return result; + } + + #endregion + + #region Internal (also used by Inspector) + + public static TargetType TypeToDOTargetType(Type t) + { + string str = t.ToString(); + int dotIndex = str.LastIndexOf("."); + if (dotIndex != -1) str = str.Substring(dotIndex + 1); + if (str.IndexOf("Renderer") != -1 && (str != "SpriteRenderer")) str = "Renderer"; +//#if true // PHYSICS_MARKER +// if (str == "Rigidbody") str = "Transform"; +//#endif +//#if true // PHYSICS2D_MARKER +// if (str == "Rigidbody2D") str = "Transform"; +//#endif +#if true // UI_MARKER +// if (str == "RectTransform") str = "Transform"; + if (str == "RawImage" || str == "Graphic") str = "Image"; // RawImages/Graphics are managed like Images for DOTweenAnimation (color and fade use Graphic target anyway) +#endif + return (TargetType)Enum.Parse(typeof(TargetType), str); + } + + // Editor preview system + /// + /// Previews the tween in the editor. Only for DOTween internal usage: don't use otherwise. + /// + public Tween CreateEditorPreview() + { + if (Application.isPlaying) return null; + + CreateTween(); + return tween; + } + + #endregion + + #endregion + + #region Private + + // Returns the gameObject whose target component should be animated + GameObject GetTweenGO() + { + return targetIsSelf ? this.gameObject : targetGO; + } + + // Re-evaluate relative position of path + void ReEvaluateRelativeTween() + { + GameObject tweenGO = GetTweenGO(); + if (tweenGO == null) { + Debug.LogWarning(string.Format("{0} :: This DOTweenAnimation's target/GameObject is unset: the tween will not be created.", this.gameObject.name), this.gameObject); + return; + } + if (animationType == AnimationType.Move) { + ((Tweener)tween).ChangeEndValue(tweenGO.transform.position + endValueV3, true); + } else if (animationType == AnimationType.LocalMove) { + ((Tweener)tween).ChangeEndValue(tweenGO.transform.localPosition + endValueV3, true); + } + } + + #endregion + } + + public static class DOTweenAnimationExtensions + { +// // Doesn't work on Win 8.1 +// public static bool IsSameOrSubclassOf(this Type t, Type tBase) +// { +// return t.IsSubclassOf(tBase) || t == tBase; +// } + + public static bool IsSameOrSubclassOf(this Component t) + { + return t is T; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs.meta new file mode 100644 index 0000000..a10ceea --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenAnimation.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4d0390bd8b8ffd640b34fe25065ff1df +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs new file mode 100644 index 0000000..c9df396 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs @@ -0,0 +1,9 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/27 19:02 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php + + +#if false // MODULE_MARKER +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs.meta new file mode 100644 index 0000000..32c1ec8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeAudio.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1d1aa01bacf85c04ea18116651a7f0db +timeCreated: 1587116610 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs new file mode 100644 index 0000000..c9df396 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs @@ -0,0 +1,9 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/27 19:02 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php + + +#if false // MODULE_MARKER +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs.meta new file mode 100644 index 0000000..9cba4ea --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenDeUnityExtended.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0a0cc3e90c4a6ea41bb14d7f35c577c3 +timeCreated: 1587116610 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef new file mode 100644 index 0000000..866e9a8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef @@ -0,0 +1,7 @@ +{ + "name": "DOTweenPro.Scripts", + "references": [ + "Unity.TextMeshPro", + "DOTween.Modules" + ] +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef.meta new file mode 100644 index 0000000..833fae6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.Scripts.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2157b4cab20f85f4bb0d8cd683dc4229 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML new file mode 100644 index 0000000..14c2bb0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML @@ -0,0 +1,62 @@ + + + + DOTweenPro + + + + + Restarts the tween + + + + + Restarts the tween + + If TRUE, re-evaluates the tween's start and end values from its current position. + Set it to TRUE when spawning the same DOTweenPath in different positions (like when using a pooling system) + + + + Attach this to a GameObject to create and assign a path to it + + + + Used internally by the editor + + + + Restarts the tween + + + + + Restarts the tween + + If TRUE, re-evaluates the tween's start and end values from its current position. + Set it to TRUE when spawning the same DOTweenPath in different positions (like when using a pooling system) + + + + Returns a list of points that are used to draw the path inside the editor. + + + + + Tweens a Vector3 along a spiral. + EndValue represents the direction of the spiral + + + + + Spiral tween mode + + + + The spiral motion will expand outwards for the whole the tween + + + The spiral motion will expand outwards for half the tween and then will spiral back to the starting position + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML.meta new file mode 100644 index 0000000..ddc78e5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.XML.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: db7d7ef84c388bc4fbc3835d31a15306 +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll new file mode 100644 index 0000000..429a151 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb new file mode 100644 index 0000000..5128fdb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb.meta new file mode 100644 index 0000000..6979090 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: d719ed2e2c87eae4e8dd520e2df659c1 +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.meta new file mode 100644 index 0000000..4b9d81f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenPro.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: aa0b1eebb5db27a419fa4564bbe5c9c5 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs new file mode 100644 index 0000000..12ee7ef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs @@ -0,0 +1,90 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2018/07/13 + +using System; +using DG.Tweening.Core; +using DG.Tweening.Plugins; +using UnityEngine; + +#pragma warning disable 1591 +namespace DG.Tweening +{ + public static class DOTweenProShortcuts + { + static DOTweenProShortcuts() + { + // Create stub instances of custom plugins, in order to allow IL2CPP to understand they must be included in the build +#pragma warning disable 219 + SpiralPlugin stub = new SpiralPlugin(); +#pragma warning restore 219 + } + + #region Shortcuts + + #region Transform + + /// Tweens a Transform's localPosition in a spiral shape. + /// Also stores the transform as the tween's target so it can be used for filtered operations + /// The duration of the tween + /// The axis around which the spiral will rotate + /// The type of spiral movement + /// Speed of the rotations + /// Frequency of the rotation. Lower values lead to wider spirals + /// Indicates how much the tween should move along the spiral's axis + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DOSpiral( + this Transform target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand, + float speed = 1, float frequency = 10, float depth = 0, bool snapping = false + ) { + if (Mathf.Approximately(speed, 0)) speed = 1; + if (axis == null || axis == Vector3.zero) axis = Vector3.forward; + + TweenerCore t = DOTween.To(SpiralPlugin.Get(), () => target.localPosition, x => target.localPosition = x, (Vector3)axis, duration) + .SetTarget(target); + + t.plugOptions.mode = mode; + t.plugOptions.speed = speed; + t.plugOptions.frequency = frequency; + t.plugOptions.depth = depth; + t.plugOptions.snapping = snapping; + return t; + } + + #endregion + +#if true // PHYSICS_MARKER + #region Rigidbody + + /// Tweens a Rigidbody's position in a spiral shape. + /// Also stores the transform as the tween's target so it can be used for filtered operations + /// The duration of the tween + /// The axis around which the spiral will rotate + /// The type of spiral movement + /// Speed of the rotations + /// Frequency of the rotation. Lower values lead to wider spirals + /// Indicates how much the tween should move along the spiral's axis + /// If TRUE the tween will smoothly snap all values to integers + public static Tweener DOSpiral( + this Rigidbody target, float duration, Vector3? axis = null, SpiralMode mode = SpiralMode.Expand, + float speed = 1, float frequency = 10, float depth = 0, bool snapping = false + ) { + if (Mathf.Approximately(speed, 0)) speed = 1; + if (axis == null || axis == Vector3.zero) axis = Vector3.forward; + + TweenerCore t = DOTween.To(SpiralPlugin.Get(), () => target.position, target.MovePosition, (Vector3)axis, duration) + .SetTarget(target); + + t.plugOptions.mode = mode; + t.plugOptions.speed = speed; + t.plugOptions.frequency = frequency; + t.plugOptions.depth = depth; + t.plugOptions.snapping = snapping; + return t; + } + + #endregion +#endif + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs.meta new file mode 100644 index 0000000..bc6e863 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenProShortcuts.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1c3190a1a1c53f449926f6d5542b4ce5 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs new file mode 100644 index 0000000..0dbe782 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs @@ -0,0 +1,1005 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/27 19:02 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php + + +#if true // MODULE_MARKER +using System; +using System.Globalization; +using System.Collections.Generic; +using DG.Tweening.Core; +using DG.Tweening.Plugins.Options; +using UnityEngine; +using TMPro; +using Object = UnityEngine.Object; + +namespace DG.Tweening +{ + public enum TMPSkewSpanMode + { + /// Applies the skew as-is (like normal skew works): the longer the text-span the higher the last character will be + Default, + /// Applies the skew scaled by the size of the text-span: the max skew/displacement will be the given skew factor + AsMaxSkewFactor + } + + /// + /// Methods that extend TMP_Text objects and allow to directly create and control tweens from their instances. + /// + public static class ShortcutExtensionsTMPText + { + #region Colors + + /// Tweens a TextMeshPro's color to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this TMP_Text target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's faceColor to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFaceColor(this TMP_Text target, Color32 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.faceColor, x => target.faceColor = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's outlineColor to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOOutlineColor(this TMP_Text target, Color32 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.outlineColor, x => target.outlineColor = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's glow color to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + /// If TRUE will use the fontSharedMaterial instead than the fontMaterial + public static TweenerCore DOGlowColor(this TMP_Text target, Color endValue, float duration, bool useSharedMaterial = false) + { + TweenerCore t = useSharedMaterial + ? target.fontSharedMaterial.DOColor(endValue, "_GlowColor", duration) + : target.fontMaterial.DOColor(endValue, "_GlowColor", duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's alpha color to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this TMP_Text target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro faceColor's alpha to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFaceFade(this TMP_Text target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.faceColor, x => target.faceColor = x, endValue, duration); + t.SetTarget(target); + return t; + } + + #endregion + + #region Other + + /// Tweens a TextMeshPro's scale to the given value (using correct uniform scale as TMP requires). + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScale(this TMP_Text target, float endValue, float duration) + { + Transform trans = target.transform; + Vector3 endValueV3 = new Vector3(endValue, endValue, endValue); + TweenerCore t = DOTween.To(() => trans.localScale, x => trans.localScale = x, endValueV3, duration); + t.SetTarget(target); + return t; + } + + /// + /// Tweens a TextMeshPro's text from one integer to another, with options for thousands separators + /// + /// The value to start from + /// The end value to reach + /// The duration of the tween + /// If TRUE (default) also adds thousands separators + /// The to use (InvariantCulture if NULL) + public static TweenerCore DOCounter( + this TMP_Text target, int fromValue, int endValue, float duration, bool addThousandsSeparator = true, CultureInfo culture = null + ){ + int v = fromValue; + CultureInfo cInfo = !addThousandsSeparator ? null : culture ?? CultureInfo.InvariantCulture; + TweenerCore t = DOTween.To(() => v, x => { + v = x; + target.text = addThousandsSeparator + ? v.ToString("N0", cInfo) + : v.ToString(); + }, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's fontSize to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFontSize(this TMP_Text target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.fontSize, x => target.fontSize = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's maxVisibleCharacters to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOMaxVisibleCharacters(this TMP_Text target, int endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.maxVisibleCharacters, x => target.maxVisibleCharacters = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a TextMeshPro's text to the given value. + /// Also stores the TextMeshPro as the tween's target so it can be used for filtered operations + /// The end string to tween toThe duration of the tween + /// If TRUE (default), rich text will be interpreted correctly while animated, + /// otherwise all tags will be considered as normal text + /// The type of scramble mode to use, if any + /// A string containing the characters to use for scrambling. + /// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. + /// Leave it to NULL (default) to use default ones + public static TweenerCore DOText(this TMP_Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null) + { + TweenerCore t = DOTween.To(() => target.text, x => target.text = x, endValue, duration); + t.SetOptions(richTextEnabled, scrambleMode, scrambleChars) + .SetTarget(target); + return t; + } + + #endregion + } + + #region DOTweenTMPAnimator + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ CLASS ███████████████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + /// + /// Wrapper for objects that enables per-character tweening + /// (you don't need this if instead you want to animate the whole text object). + /// It also contains various handy methods to simply deform text without animating it ;) + /// EXAMPLE: + /// DOTweenTMPAnimator animator = new DOTweenTMPAnimator(myTextMeshProTextField); + /// Tween tween = animator.DOCharScale(characterIndex, scaleValue, duration); + /// + /// + public class DOTweenTMPAnimator : IDisposable + { + /// that this animator is linked to + public TMP_Text target { get; private set; } + public TMP_TextInfo textInfo { get; private set; } + readonly List _charTransforms = new List(); + TMP_MeshInfo[] _cachedMeshInfos; + bool _ignoreTextChangedEvent; + + /// + /// Creates a new instance of the , which is necessary to animate by single characters. + /// If you want to animate the whole text object you don't need this, and you can use direct DO shortcuts instead. + /// IMPORTANT: the target must have been enabled/activated at least once before you can use it with this + /// + /// The that will be linked to this animator + public DOTweenTMPAnimator(TMP_Text target) + { + if (!target.gameObject.activeInHierarchy) { + Debugger.LogError("You can't create a DOTweenTMPAnimator if its target is disabled"); + return; + } + this.target = target; + Refresh(); + // Listeners + TMPro_EventManager.TEXT_CHANGED_EVENT.Add(OnTextChanged); + } + + /// + /// Clears and disposes of this object + /// + public void Dispose() + { + target = null; + _charTransforms.Clear(); + textInfo = null; + _cachedMeshInfos = null; + TMPro_EventManager.TEXT_CHANGED_EVENT.Remove(OnTextChanged); + } + + /// + /// Refreshes the animator text data and resets all transformation data. Call this after you change the target + /// + public void Refresh() + { + _ignoreTextChangedEvent = true; + target.ForceMeshUpdate(true); + textInfo = target.textInfo; + _cachedMeshInfos = textInfo.CopyMeshInfoVertexData(); + int totChars = textInfo.characterCount; + int totCurrent = _charTransforms.Count; + if (totCurrent > totChars) { + _charTransforms.RemoveRange(totChars, totCurrent - totChars); + totCurrent = totChars; + } + for (int i = 0; i < totCurrent; ++i) { + CharTransform c = _charTransforms[i]; + c.ResetTransformationData(); + c.Refresh(textInfo, _cachedMeshInfos); + _charTransforms[i] = c; + } + for (int i = totCurrent; i < totChars; ++i) _charTransforms.Add(new CharTransform(i, textInfo, _cachedMeshInfos)); + _ignoreTextChangedEvent = false; + } + + /// + /// Resets all deformations + /// + public void Reset() + { + int totCurrent = _charTransforms.Count; + for (int i = 0; i < totCurrent; ++i) _charTransforms[i].ResetAll(target, textInfo.meshInfo, _cachedMeshInfos); + } + + void OnTextChanged(Object obj) + { + if (_ignoreTextChangedEvent || target == null || obj != target) return; + Refresh(); + } + + bool ValidateChar(int charIndex, bool isTween = true) + { + if (textInfo.characterCount <= charIndex) { + Debugger.LogError(string.Format("CharIndex {0} doesn't exist", charIndex)); + return false; + } + if (!textInfo.characterInfo[charIndex].isVisible) { + if (Debugger.logPriority > 1) { + if (isTween) { + Debugger.Log(string.Format( + "CharIndex {0} isn't visible, ignoring it and returning an empty tween (TextMesh Pro will behave weirdly if invisible chars are included in the animation)", + charIndex + )); + } else { + Debugger.Log(string.Format("CharIndex {0} isn't visible, ignoring it", charIndex)); + } + } + return false; + } + return true; + } + + bool ValidateSpan(int fromCharIndex, int toCharIndex, out int firstVisibleCharIndex, out int lastVisibleCharIndex) + { + firstVisibleCharIndex = -1; // First visible/existing charIndex from given index + lastVisibleCharIndex = -1; // Last visible/existing charIndex backwards from given index + int charCount = textInfo.characterCount; + if (fromCharIndex >= charCount) return false; + if (toCharIndex >= charCount) toCharIndex = charCount - 1; + for (int i = fromCharIndex; i < toCharIndex + 1; ++i) { + if (!_charTransforms[i].isVisible) continue; + firstVisibleCharIndex = i; + break; + } + if (firstVisibleCharIndex == -1) return false; + for (int i = toCharIndex; i > firstVisibleCharIndex - 1; --i) { + if (!_charTransforms[i].isVisible) continue; + lastVisibleCharIndex = i; + break; + } + if (lastVisibleCharIndex == -1) return false; + return true; + } + + #region Word Setters + + /// + /// Skews a span of characters uniformly (like normal skew works in graphic applications) + /// + /// First char index of the span to skew + /// Last char index of the span to skew + /// Skew factor + /// If TRUE skews the top side of the span, otherwise the bottom one + public void SkewSpanX(int fromCharIndex, int toCharIndex, float skewFactor, bool skewTop = true) + { + int firstVisibleCharIndex, lastVisibleCharIndex; + if (!ValidateSpan(fromCharIndex, toCharIndex, out firstVisibleCharIndex, out lastVisibleCharIndex)) return; + for (int i = firstVisibleCharIndex; i < lastVisibleCharIndex + 1; ++i) { + if (!_charTransforms[i].isVisible) continue; + CharVertices v = _charTransforms[i].GetVertices(); + float skew = SkewCharX(i, skewFactor, skewTop); + } + } + + /// + /// Skews a span of characters uniformly (like normal skew works in graphic applications) + /// + /// First char index of the span to skew + /// Last char index of the span to skew + /// Skew factor + /// Skew mode + /// If TRUE skews the right side of the span, otherwise the left one + public void SkewSpanY( + int fromCharIndex, int toCharIndex, float skewFactor, + TMPSkewSpanMode mode = TMPSkewSpanMode.Default, bool skewRight = true + ){ + int firstVisibleCharIndex, lastVisibleCharIndex; + if (!ValidateSpan(fromCharIndex, toCharIndex, out firstVisibleCharIndex, out lastVisibleCharIndex)) return; + if (mode == TMPSkewSpanMode.AsMaxSkewFactor) { + CharVertices firstVisibleCharVertices = _charTransforms[firstVisibleCharIndex].GetVertices(); + CharVertices lastVisibleCharVertices = _charTransforms[lastVisibleCharIndex].GetVertices(); + float spanW = Mathf.Abs(lastVisibleCharVertices.bottomRight.x - firstVisibleCharVertices.bottomLeft.x); + float spanH = Mathf.Abs(lastVisibleCharVertices.topRight.y - lastVisibleCharVertices.bottomRight.y); + float ratio = spanH / spanW; + skewFactor *= ratio; + } + float offsetY = 0; + CharVertices prevCharVertices = new CharVertices(); + float prevCharSkew = 0; + if (skewRight) { + for (int i = firstVisibleCharIndex; i < lastVisibleCharIndex + 1; ++i) { + if (!_charTransforms[i].isVisible) continue; + CharVertices v = _charTransforms[i].GetVertices(); + float skew = SkewCharY(i, skewFactor, skewRight); + if (i > firstVisibleCharIndex) { + float prevCharW = Mathf.Abs(prevCharVertices.bottomLeft.x - prevCharVertices.bottomRight.x); + float charsDist = Mathf.Abs(v.bottomLeft.x - prevCharVertices.bottomRight.x); + offsetY += prevCharSkew + (prevCharSkew * charsDist) / prevCharW; + SetCharOffset(i, new Vector3(0, _charTransforms[i].offset.y + offsetY, 0)); + } + prevCharVertices = v; + prevCharSkew = skew; + } + } else { + for (int i = lastVisibleCharIndex; i > firstVisibleCharIndex - 1; --i) { + if (!_charTransforms[i].isVisible) continue; + CharVertices v = _charTransforms[i].GetVertices(); + float skew = SkewCharY(i, skewFactor, skewRight); + if (i < lastVisibleCharIndex) { + float prevCharW = Mathf.Abs(prevCharVertices.bottomLeft.x - prevCharVertices.bottomRight.x); + float charsDist = Mathf.Abs(v.bottomRight.x - prevCharVertices.bottomLeft.x); + offsetY += prevCharSkew + (prevCharSkew * charsDist) / prevCharW; + SetCharOffset(i, new Vector3(0, _charTransforms[i].offset.y + offsetY, 0)); + } + prevCharVertices = v; + prevCharSkew = skew; + } + } + } + + #endregion + + #region Char Getters + + /// + /// Returns the current color of the given character, if it exists and is visible. + /// + /// Character index + public Color GetCharColor(int charIndex) + { + if (!ValidateChar(charIndex)) return Color.white; + return _charTransforms[charIndex].GetColor(textInfo.meshInfo); + } + + /// + /// Returns the current offset of the given character, if it exists and is visible. + /// + /// Character index + public Vector3 GetCharOffset(int charIndex) + { + if (!ValidateChar(charIndex)) return Vector3.zero; + return _charTransforms[charIndex].offset; + } + + /// + /// Returns the current rotation of the given character, if it exists and is visible. + /// + /// Character index + public Vector3 GetCharRotation(int charIndex) + { + if (!ValidateChar(charIndex)) return Vector3.zero; + return _charTransforms[charIndex].rotation.eulerAngles; + } + + /// + /// Returns the current scale of the given character, if it exists and is visible. + /// + /// Character index + public Vector3 GetCharScale(int charIndex) + { + if (!ValidateChar(charIndex)) return Vector3.zero; + return _charTransforms[charIndex].scale; + } + + #endregion + + #region Char Setters + + /// + /// Immediately sets the color of the given character. + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + /// Color to set + public void SetCharColor(int charIndex, Color32 color) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.UpdateColor(target, color, textInfo.meshInfo); + _charTransforms[charIndex] = c; + } + + /// + /// Immediately sets the offset of the given character. + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + /// Offset to set + public void SetCharOffset(int charIndex, Vector3 offset) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.UpdateGeometry(target, offset, c.rotation, c.scale, _cachedMeshInfos); + _charTransforms[charIndex] = c; + } + + /// + /// Immediately sets the rotation of the given character. + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + /// Rotation to set + public void SetCharRotation(int charIndex, Vector3 rotation) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.UpdateGeometry(target, c.offset, Quaternion.Euler(rotation), c.scale, _cachedMeshInfos); + _charTransforms[charIndex] = c; + } + + /// + /// Immediately sets the scale of the given character. + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + /// Scale to set + public void SetCharScale(int charIndex, Vector3 scale) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.UpdateGeometry(target, c.offset, c.rotation, scale, _cachedMeshInfos); + _charTransforms[charIndex] = c; + } + + /// + /// Immediately shifts the vertices of the given character by the given factor. + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + /// Top left offset + /// Top right offset + /// Bottom left offset + /// Bottom right offset + public void ShiftCharVertices(int charIndex, Vector3 topLeftShift, Vector3 topRightShift, Vector3 bottomLeftShift, Vector3 bottomRightShift) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.ShiftVertices(target, topLeftShift, topRightShift, bottomLeftShift, bottomRightShift); + _charTransforms[charIndex] = c; + } + + /// + /// Skews the given character horizontally along the X axis and returns the skew amount applied (based on the character's size) + /// + /// Character index + /// skew amount + /// If TRUE skews the top side of the character, otherwise the bottom one + public float SkewCharX(int charIndex, float skewFactor, bool skewTop = true) + { + if (!ValidateChar(charIndex)) return 0; + Vector3 skewV = new Vector3(skewFactor, 0, 0); + CharTransform c = _charTransforms[charIndex]; + if (skewTop) c.ShiftVertices(target, skewV, skewV, Vector3.zero, Vector3.zero); + else c.ShiftVertices(target, Vector3.zero, Vector3.zero, skewV, skewV); + _charTransforms[charIndex] = c; + return skewFactor; + } + + /// + /// Skews the given character vertically along the Y axis and returns the skew amount applied (based on the character's size) + /// + /// Character index + /// skew amount + /// If TRUE skews the right side of the character, otherwise the left one + /// If TRUE applies exactly the given , + /// otherwise modifies it based on the aspectRation of the character + public float SkewCharY(int charIndex, float skewFactor, bool skewRight = true, bool fixedSkew = false) + { + if (!ValidateChar(charIndex)) return 0; + float skew = fixedSkew ? skewFactor : skewFactor * textInfo.characterInfo[charIndex].aspectRatio; + Vector3 skewV = new Vector3(0, skew, 0); + CharTransform c = _charTransforms[charIndex]; + if (skewRight) c.ShiftVertices(target, Vector3.zero, skewV, Vector3.zero, skewV); + else c.ShiftVertices(target, skewV, Vector3.zero, skewV, Vector3.zero); + _charTransforms[charIndex] = c; + return skew; + } + + /// + /// Resets the eventual vertices shift applied to the given character via . + /// Will do nothing if the is invalid or the character isn't visible + /// + /// Character index + public void ResetVerticesShift(int charIndex) + { + if (!ValidateChar(charIndex)) return; + CharTransform c = _charTransforms[charIndex]; + c.ResetVerticesShift(target); + _charTransforms[charIndex] = c; + } + + #endregion + + #region Char Tweens + + /// Tweens a character's alpha to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + public TweenerCore DOFadeChar(int charIndex, float endValue, float duration) + { + if (!ValidateChar(charIndex)) return null; + TweenerCore t = DOTween.ToAlpha(() => _charTransforms[charIndex].GetColor(textInfo.meshInfo), x => { + _charTransforms[charIndex].UpdateAlpha(target, x, textInfo.meshInfo); + }, endValue, duration); + return t; + } + + /// Tweens a character's color to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + public TweenerCore DOColorChar(int charIndex, Color endValue, float duration) + { + if (!ValidateChar(charIndex)) return null; + TweenerCore t = DOTween.To(() => _charTransforms[charIndex].GetColor(textInfo.meshInfo), x => { + _charTransforms[charIndex].UpdateColor(target, x, textInfo.meshInfo); + }, endValue, duration); + return t; + } + + /// Tweens a character's offset to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + public TweenerCore DOOffsetChar(int charIndex, Vector3 endValue, float duration) + { + if (!ValidateChar(charIndex)) return null; + TweenerCore t = DOTween.To(() => _charTransforms[charIndex].offset, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, x, charT.rotation, charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, endValue, duration); + return t; + } + + /// Tweens a character's rotation to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + /// Rotation mode + public TweenerCore DORotateChar(int charIndex, Vector3 endValue, float duration, RotateMode mode = RotateMode.Fast) + { + if (!ValidateChar(charIndex)) return null; + TweenerCore t = DOTween.To(() => _charTransforms[charIndex].rotation, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, x, charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, endValue, duration); + t.plugOptions.rotateMode = mode; + return t; + } + + /// Tweens a character's scale to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + public TweenerCore DOScaleChar(int charIndex, float endValue, float duration) + { + return DOScaleChar(charIndex, new Vector3(endValue, endValue, endValue), duration); + } + /// Tweens a character's color to the given value and returns the . + /// Will return NULL if the is invalid or the character isn't visible. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The end value to reachThe duration of the tween + public TweenerCore DOScaleChar(int charIndex, Vector3 endValue, float duration) + { + if (!ValidateChar(charIndex)) return null; + TweenerCore t = DOTween.To(() => _charTransforms[charIndex].scale, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, charT.rotation, x, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, endValue, duration); + return t; + } + + /// Punches a character's offset towards the given direction and then back to the starting one + /// as if it was connected to the starting position via an elastic. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The punch strength + /// The duration of the tween + /// Indicates how much will the punch vibrate per second + /// Represents how much (0 to 1) the vector will go beyond the starting size when bouncing backwards. + /// 1 creates a full oscillation between the punch offset and the opposite offset, + /// while 0 oscillates only between the punch offset and the start offset + public Tweener DOPunchCharOffset(int charIndex, Vector3 punch, float duration, int vibrato = 10, float elasticity = 1) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Punch(() => _charTransforms[charIndex].offset, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, x, charT.rotation, charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, punch, duration, vibrato, elasticity); + } + + /// Punches a character's rotation towards the given direction and then back to the starting one + /// as if it was connected to the starting position via an elastic. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The punch strength + /// The duration of the tween + /// Indicates how much will the punch vibrate per second + /// Represents how much (0 to 1) the vector will go beyond the starting size when bouncing backwards. + /// 1 creates a full oscillation between the punch rotation and the opposite rotation, + /// while 0 oscillates only between the punch rotation and the start rotation + public Tweener DOPunchCharRotation(int charIndex, Vector3 punch, float duration, int vibrato = 10, float elasticity = 1) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Punch(() => _charTransforms[charIndex].rotation.eulerAngles, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, Quaternion.Euler(x), charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, punch, duration, vibrato, elasticity); + } + + /// Punches a character's scale towards the given direction and then back to the starting one + /// as if it was connected to the starting position via an elastic. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The punch strength (added to the character's current scale) + /// The duration of the tween + /// Indicates how much will the punch vibrate per second + /// Represents how much (0 to 1) the vector will go beyond the starting size when bouncing backwards. + /// 1 creates a full oscillation between the punch scale and the opposite scale, + /// while 0 oscillates only between the punch scale and the start scale + public Tweener DOPunchCharScale(int charIndex, float punch, float duration, int vibrato = 10, float elasticity = 1) + { + return DOPunchCharScale(charIndex, new Vector3(punch, punch, punch), duration, vibrato, elasticity); + } + /// Punches a character's scale towards the given direction and then back to the starting one + /// as if it was connected to the starting position via an elastic. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The punch strength (added to the character's current scale) + /// The duration of the tween + /// Indicates how much will the punch vibrate per second + /// Represents how much (0 to 1) the vector will go beyond the starting size when bouncing backwards. + /// 1 creates a full oscillation between the punch scale and the opposite scale, + /// while 0 oscillates only between the punch scale and the start scale + public Tweener DOPunchCharScale(int charIndex, Vector3 punch, float duration, int vibrato = 10, float elasticity = 1) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Punch(() => _charTransforms[charIndex].scale, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, charT.rotation, x, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, punch, duration, vibrato, elasticity); + } + + /// Shakes a character's offset with the given values. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public Tweener DOShakeCharOffset(int charIndex, float duration, float strength, int vibrato = 10, float randomness = 90, bool fadeOut = true) + { + return DOShakeCharOffset(charIndex, duration, new Vector3(strength, strength, strength), vibrato, randomness, fadeOut); + } + /// Shakes a character's offset with the given values. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public Tweener DOShakeCharOffset(int charIndex, float duration, Vector3 strength, int vibrato = 10, float randomness = 90, bool fadeOut = true) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Shake(() => _charTransforms[charIndex].offset, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, x, charT.rotation, charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, duration, strength, vibrato, randomness, fadeOut); + } + + /// Shakes a character's rotation with the given values. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public Tweener DOShakeCharRotation(int charIndex, float duration, Vector3 strength, int vibrato = 10, float randomness = 90, bool fadeOut = true) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Shake(() => _charTransforms[charIndex].rotation.eulerAngles, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, Quaternion.Euler(x), charT.scale, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, duration, strength, vibrato, randomness, fadeOut); + } + + /// Shakes a character's scale with the given values. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public Tweener DOShakeCharScale(int charIndex, float duration, float strength, int vibrato = 10, float randomness = 90, bool fadeOut = true) + { + return DOShakeCharScale(charIndex, duration, new Vector3(strength, strength, strength), vibrato, randomness, fadeOut); + } + /// Shakes a character's scale with the given values. + /// The index of the character to tween (will throw an error if it doesn't exist) + /// The duration of the tween + /// The shake strength + /// Indicates how much will the shake vibrate + /// Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). + /// Setting it to 0 will shake along a single direction. + /// If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not + public Tweener DOShakeCharScale(int charIndex, float duration, Vector3 strength, int vibrato = 10, float randomness = 90, bool fadeOut = true) + { + if (!ValidateChar(charIndex)) return null; + if (duration <= 0) { + if (Debugger.logPriority > 0) Debug.LogWarning("Duration can't be 0, returning NULL without creating a tween"); + return null; + } + return DOTween.Shake(() => _charTransforms[charIndex].scale, x => { + CharTransform charT = _charTransforms[charIndex]; + charT.UpdateGeometry(target, charT.offset, charT.rotation, x, _cachedMeshInfos); + _charTransforms[charIndex] = charT; + }, duration, strength, vibrato, randomness, fadeOut); + } + + #endregion + + // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ + + struct CharVertices + { + public Vector3 bottomLeft, topLeft, topRight, bottomRight; + + public CharVertices(Vector3 bottomLeft, Vector3 topLeft, Vector3 topRight, Vector3 bottomRight) + { + this.bottomLeft = bottomLeft; + this.topLeft = topLeft; + this.topRight = topRight; + this.bottomRight = bottomRight; + } + } + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + // Vertices of each character are: + // 0 : bottom left, 1 : top left, 2 : top right, 3 : bottom right + struct CharTransform + { + public int charIndex; + public bool isVisible { get; private set; } // FALSE both if it's invisible or if it's a space + public Vector3 offset; + public Quaternion rotation; + public Vector3 scale; + Vector3 _topLeftShift, _topRightShift, _bottomLeftShift, _bottomRightShift; + Vector3 _charMidBaselineOffset; + int _matIndex, _firstVertexIndex; + TMP_MeshInfo _meshInfo; + + public CharTransform(int charIndex, TMP_TextInfo textInfo, TMP_MeshInfo[] cachedMeshInfos) : this() + { + this.charIndex = charIndex; + offset = Vector3.zero; + rotation = Quaternion.identity; + scale = Vector3.one; + Refresh(textInfo, cachedMeshInfos); + } + + public void Refresh(TMP_TextInfo textInfo, TMP_MeshInfo[] cachedMeshInfos) + { + TMP_CharacterInfo charInfo = textInfo.characterInfo[charIndex]; + bool isSpaceChar = charInfo.character == ' '; + isVisible = charInfo.isVisible && !isSpaceChar; + _matIndex = charInfo.materialReferenceIndex; + _firstVertexIndex = charInfo.vertexIndex; + _meshInfo = textInfo.meshInfo[_matIndex]; + Vector3[] cachedVertices = cachedMeshInfos[_matIndex].vertices; + _charMidBaselineOffset = isSpaceChar + ? Vector3.zero + : (cachedVertices[_firstVertexIndex] + cachedVertices[_firstVertexIndex + 2]) * 0.5f; + } + + public void ResetAll(TMP_Text target, TMP_MeshInfo[] meshInfos, TMP_MeshInfo[] cachedMeshInfos) + { + ResetGeometry(target, cachedMeshInfos); + ResetColors(target, meshInfos); + } + + public void ResetTransformationData() + { + offset = Vector3.zero; + rotation = Quaternion.identity; + scale = Vector3.one; + _topLeftShift = _topRightShift = _bottomLeftShift = _bottomRightShift = Vector3.zero; + } + + public void ResetGeometry(TMP_Text target, TMP_MeshInfo[] cachedMeshInfos) + { + ResetTransformationData(); + Vector3[] destinationVertices = _meshInfo.vertices; + Vector3[] cachedVertices = cachedMeshInfos[_matIndex].vertices; + destinationVertices[_firstVertexIndex + 0] = cachedVertices[_firstVertexIndex + 0]; + destinationVertices[_firstVertexIndex + 1] = cachedVertices[_firstVertexIndex + 1]; + destinationVertices[_firstVertexIndex + 2] = cachedVertices[_firstVertexIndex + 2]; + destinationVertices[_firstVertexIndex + 3] = cachedVertices[_firstVertexIndex + 3]; + _meshInfo.mesh.vertices = _meshInfo.vertices; + target.UpdateGeometry(_meshInfo.mesh, _matIndex); + } + + public void ResetColors(TMP_Text target, TMP_MeshInfo[] meshInfos) + { + Color color = target.color; + Color32[] vertexCols = meshInfos[_matIndex].colors32; + vertexCols[_firstVertexIndex] = color; + vertexCols[_firstVertexIndex + 1] = color; + vertexCols[_firstVertexIndex + 2] = color; + vertexCols[_firstVertexIndex + 3] = color; + target.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); + } + + public Color32 GetColor(TMP_MeshInfo[] meshInfos) + { + return meshInfos[_matIndex].colors32[_firstVertexIndex]; + } + + public CharVertices GetVertices() + { + return new CharVertices( + _meshInfo.vertices[_firstVertexIndex], _meshInfo.vertices[_firstVertexIndex + 1], + _meshInfo.vertices[_firstVertexIndex + 2], _meshInfo.vertices[_firstVertexIndex + 3] + ); + } + + public void UpdateAlpha(TMP_Text target, Color alphaColor, TMP_MeshInfo[] meshInfos, bool apply = true) + { + byte alphaByte = (byte)(alphaColor.a * 255); + Color32[] vertexCols = meshInfos[_matIndex].colors32; + vertexCols[_firstVertexIndex].a = alphaByte; + vertexCols[_firstVertexIndex + 1].a = alphaByte; + vertexCols[_firstVertexIndex + 2].a = alphaByte; + vertexCols[_firstVertexIndex + 3].a = alphaByte; + if (apply) target.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); + } + + public void UpdateColor(TMP_Text target, Color32 color, TMP_MeshInfo[] meshInfos, bool apply = true) + { + Color32[] vertexCols = meshInfos[_matIndex].colors32; + vertexCols[_firstVertexIndex] = color; + vertexCols[_firstVertexIndex + 1] = color; + vertexCols[_firstVertexIndex + 2] = color; + vertexCols[_firstVertexIndex + 3] = color; + if (apply) target.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); + } + + public void UpdateGeometry(TMP_Text target, Vector3 offset, Quaternion rotation, Vector3 scale, TMP_MeshInfo[] cachedMeshInfos, bool apply = true) + { + this.offset = offset; + this.rotation = rotation; + this.scale = scale; + + if (!apply) return; + + Vector3[] destinationVertices = _meshInfo.vertices; + Vector3[] cachedVertices = cachedMeshInfos[_matIndex].vertices; + destinationVertices[_firstVertexIndex] = cachedVertices[_firstVertexIndex + 0] - _charMidBaselineOffset; + destinationVertices[_firstVertexIndex + 1] = cachedVertices[_firstVertexIndex + 1] - _charMidBaselineOffset; + destinationVertices[_firstVertexIndex + 2] = cachedVertices[_firstVertexIndex + 2] - _charMidBaselineOffset; + destinationVertices[_firstVertexIndex + 3] = cachedVertices[_firstVertexIndex + 3] - _charMidBaselineOffset; + Matrix4x4 matrix = Matrix4x4.TRS(this.offset, this.rotation, this.scale); + destinationVertices[_firstVertexIndex] + = matrix.MultiplyPoint3x4(destinationVertices[_firstVertexIndex + 0]) + _charMidBaselineOffset + _bottomLeftShift; + destinationVertices[_firstVertexIndex + 1] + = matrix.MultiplyPoint3x4(destinationVertices[_firstVertexIndex + 1]) + _charMidBaselineOffset + _topLeftShift; + destinationVertices[_firstVertexIndex + 2] + = matrix.MultiplyPoint3x4(destinationVertices[_firstVertexIndex + 2]) + _charMidBaselineOffset + _topRightShift; + destinationVertices[_firstVertexIndex + 3] + = matrix.MultiplyPoint3x4(destinationVertices[_firstVertexIndex + 3]) + _charMidBaselineOffset + _bottomRightShift; + _meshInfo.mesh.vertices = _meshInfo.vertices; + target.UpdateGeometry(_meshInfo.mesh, _matIndex); + } + + public void ShiftVertices(TMP_Text target, Vector3 topLeftShift, Vector3 topRightShift, Vector3 bottomLeftShift, Vector3 bottomRightShift) + { + _topLeftShift += topLeftShift; + _topRightShift += topRightShift; + _bottomLeftShift += bottomLeftShift; + _bottomRightShift += bottomRightShift; + Vector3[] destinationVertices = _meshInfo.vertices; + destinationVertices[_firstVertexIndex] = destinationVertices[_firstVertexIndex] + _bottomLeftShift; + destinationVertices[_firstVertexIndex + 1] = destinationVertices[_firstVertexIndex + 1] + _topLeftShift; + destinationVertices[_firstVertexIndex + 2] = destinationVertices[_firstVertexIndex + 2] + _topRightShift; + destinationVertices[_firstVertexIndex + 3] = destinationVertices[_firstVertexIndex + 3] + _bottomRightShift; + _meshInfo.mesh.vertices = _meshInfo.vertices; + target.UpdateGeometry(_meshInfo.mesh, _matIndex); + } + + public void ResetVerticesShift(TMP_Text target) + { + Vector3[] destinationVertices = _meshInfo.vertices; + destinationVertices[_firstVertexIndex] = destinationVertices[_firstVertexIndex] - _bottomLeftShift; + destinationVertices[_firstVertexIndex + 1] = destinationVertices[_firstVertexIndex + 1] - _topLeftShift; + destinationVertices[_firstVertexIndex + 2] = destinationVertices[_firstVertexIndex + 2] - _topRightShift; + destinationVertices[_firstVertexIndex + 3] = destinationVertices[_firstVertexIndex + 3] - _bottomRightShift; + _meshInfo.mesh.vertices = _meshInfo.vertices; + target.UpdateGeometry(_meshInfo.mesh, _matIndex); + _topLeftShift = _topRightShift = _bottomLeftShift = _bottomRightShift = Vector3.zero; + } + } + } + + #endregion +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs.meta new file mode 100644 index 0000000..613cdbc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTextMeshPro.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8fb0d65aa5b048649a3a785b82b8f8db +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs new file mode 100644 index 0000000..0c57bfe --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs @@ -0,0 +1,247 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2014/10/27 15:59 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php + +#if false // MODULE_MARKER +using DG.Tweening.Core; +using DG.Tweening.Plugins.Options; +using UnityEngine; + +namespace DG.Tweening +{ + /// + /// Methods that extend 2D Toolkit objects and allow to directly create and control tweens from their instances. + /// + public static class ShortcutExtensionsTk2d + { + #region Sprite + + /// Tweens a 2D Toolkit Sprite's dimensions to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScale(this tk2dBaseSprite target, Vector3 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, endValue, duration); + t.SetTarget(target); + return t; + } + /// Tweens a Sprite's dimensions to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleX(this tk2dBaseSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(endValue, 0, 0), duration); + t.SetOptions(AxisConstraint.X) + .SetTarget(target); + return t; + } + /// Tweens a Sprite's dimensions to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleY(this tk2dBaseSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(0, endValue, 0), duration); + t.SetOptions(AxisConstraint.Y) + .SetTarget(target); + return t; + } + /// Tweens a Sprite's dimensions to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleZ(this tk2dBaseSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(0, 0, endValue), duration); + t.SetOptions(AxisConstraint.Z) + .SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit Sprite's color to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this tk2dBaseSprite target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit Sprite's alpha color to the given value. + /// Also stores the Sprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this tk2dBaseSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit Sprite's color using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to useThe duration of the tween + public static Sequence DOGradientColor(this tk2dBaseSprite target, Gradient gradient, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.color = c.color; + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + + #endregion + + #region tk2dSlicedSprite + + /// Tweens a 2D Toolkit SlicedSprite's dimensions to the given value. + /// Also stores the SlicedSprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleDimensions(this tk2dSlicedSprite target, Vector2 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.dimensions, x => target.dimensions = x, endValue, duration); + t.SetTarget(target); + return t; + } + /// Tweens a SlicedSprite's dimensions to the given value. + /// Also stores the SlicedSprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleDimensionsX(this tk2dSlicedSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.dimensions, x => target.dimensions = x, new Vector2(endValue, 0), duration); + t.SetOptions(AxisConstraint.X) + .SetTarget(target); + return t; + } + /// Tweens a SlicedSprite's dimensions to the given value. + /// Also stores the SlicedSprite as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleDimensionsY(this tk2dSlicedSprite target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.dimensions, x => target.dimensions = x, new Vector2(0, endValue), duration); + t.SetOptions(AxisConstraint.Y) + .SetTarget(target); + return t; + } + + #endregion + + #region TextMesh + + /// Tweens a 2D Toolkit TextMesh's dimensions to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScale(this tk2dTextMesh target, Vector3 endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, endValue, duration); + t.SetTarget(target); + return t; + } + /// Tweens a 2D Toolkit TextMesh's dimensions to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleX(this tk2dTextMesh target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(endValue, 0, 0), duration); + t.SetOptions(AxisConstraint.X) + .SetTarget(target); + return t; + } + /// Tweens a 2D Toolkit TextMesh's dimensions to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleY(this tk2dTextMesh target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(0, endValue, 0), duration); + t.SetOptions(AxisConstraint.Y) + .SetTarget(target); + return t; + } + /// Tweens a 2D Toolkit TextMesh's dimensions to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOScaleZ(this tk2dTextMesh target, float endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.scale, x => target.scale = x, new Vector3(0, 0, endValue), duration); + t.SetOptions(AxisConstraint.Z) + .SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit TextMesh's color to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOColor(this tk2dTextMesh target, Color endValue, float duration) + { + TweenerCore t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit TextMesh's alpha color to the given value. + /// Also stores the TextMesh as the tween's target so it can be used for filtered operations + /// The end value to reachThe duration of the tween + public static TweenerCore DOFade(this tk2dTextMesh target, float endValue, float duration) + { + TweenerCore t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); + t.SetTarget(target); + return t; + } + + /// Tweens a 2D Toolkit TextMesh's color using the given gradient + /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). + /// Also stores the image as the tween's target so it can be used for filtered operations + /// The gradient to useThe duration of the tween + public static Sequence DOGradientColor(this tk2dTextMesh target, Gradient gradient, float duration) + { + Sequence s = DOTween.Sequence(); + GradientColorKey[] colors = gradient.colorKeys; + int len = colors.Length; + for (int i = 0; i < len; ++i) { + GradientColorKey c = colors[i]; + if (i == 0 && c.time <= 0) { + target.color = c.color; + continue; + } + float colorDuration = i == len - 1 + ? duration - s.Duration(false) // Verifies that total duration is correct + : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); + s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); + } + s.SetTarget(target); + return s; + } + + /// Tweens a tk2dTextMesh's text to the given value. + /// Also stores the tk2dTextMesh as the tween's target so it can be used for filtered operations + /// The end string to tween toThe duration of the tween + /// If TRUE (default), rich text will be interpreted correctly while animated, + /// otherwise all tags will be considered as normal text + /// The type of scramble mode to use, if any + /// A string containing the characters to use for scrambling. + /// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. + /// Leave it to NULL (default) to use default ones + public static TweenerCore DOText(this tk2dTextMesh target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null) + { + TweenerCore t = DOTween.To(() => target.text, x => target.text = x, endValue, duration); + t.SetOptions(richTextEnabled, scrambleMode, scrambleChars) + .SetTarget(target); + return t; + } + + #endregion + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs.meta new file mode 100644 index 0000000..c909f96 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/DOTweenTk2d.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b590cd7c24ffa5d4faa5b6fa993cccad +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor.meta new file mode 100644 index 0000000..e9164f7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 34ca5bde92f87fa4dbeb9593d201fde2 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs new file mode 100644 index 0000000..4f550c0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs @@ -0,0 +1,745 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/12 16:03 + +using System; +using System.Collections.Generic; +using System.IO; +using DG.DemiEditor; +using DG.DOTweenEditor.Core; +using DG.DOTweenEditor.UI; +using DG.Tweening; +using DG.Tweening.Core; +using UnityEditor; +using UnityEngine; +using DOTweenSettings = DG.Tweening.Core.DOTweenSettings; +#if true // UI_MARKER +using UnityEngine.UI; +#endif +#if true // TEXTMESHPRO_MARKER + using TMPro; +#endif + +namespace DG.DOTweenEditor +{ + [CustomEditor(typeof(DOTweenAnimation))] + public class DOTweenAnimationInspector : ABSAnimationInspector + { + enum FadeTargetType + { + CanvasGroup, + Image + } + + enum ChooseTargetMode + { + None, + BetweenCanvasGroupAndImage + } + + static readonly Dictionary _AnimationTypeToComponent = new Dictionary() { + { DOTweenAnimation.AnimationType.Move, new[] { +#if true // PHYSICS_MARKER + typeof(Rigidbody), +#endif +#if true // PHYSICS2D_MARKER + typeof(Rigidbody2D), +#endif +#if true // UI_MARKER + typeof(RectTransform), +#endif + typeof(Transform) + }}, + { DOTweenAnimation.AnimationType.Rotate, new[] { +#if true // PHYSICS_MARKER + typeof(Rigidbody), +#endif +#if true // PHYSICS2D_MARKER + typeof(Rigidbody2D), +#endif + typeof(Transform) + }}, + { DOTweenAnimation.AnimationType.LocalMove, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.LocalRotate, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.Scale, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.Color, new[] { + typeof(Light), +#if true // SPRITE_MARKER + typeof(SpriteRenderer), +#endif +#if true // UI_MARKER + typeof(Image), typeof(Text), typeof(RawImage), typeof(Graphic), +#endif + typeof(Renderer), + }}, + { DOTweenAnimation.AnimationType.Fade, new[] { + typeof(Light), +#if true // SPRITE_MARKER + typeof(SpriteRenderer), +#endif +#if true // UI_MARKER + typeof(Image), typeof(Text), typeof(CanvasGroup), typeof(RawImage), typeof(Graphic), +#endif + typeof(Renderer), + }}, +#if true // UI_MARKER + { DOTweenAnimation.AnimationType.Text, new[] { typeof(Text) } }, +#endif + { DOTweenAnimation.AnimationType.PunchPosition, new[] { +#if true // UI_MARKER + typeof(RectTransform), +#endif + typeof(Transform) + }}, + { DOTweenAnimation.AnimationType.PunchRotation, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.PunchScale, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.ShakePosition, new[] { +#if true // UI_MARKER + typeof(RectTransform), +#endif + typeof(Transform) + }}, + { DOTweenAnimation.AnimationType.ShakeRotation, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.ShakeScale, new[] { typeof(Transform) } }, + { DOTweenAnimation.AnimationType.CameraAspect, new[] { typeof(Camera) } }, + { DOTweenAnimation.AnimationType.CameraBackgroundColor, new[] { typeof(Camera) } }, + { DOTweenAnimation.AnimationType.CameraFieldOfView, new[] { typeof(Camera) } }, + { DOTweenAnimation.AnimationType.CameraOrthoSize, new[] { typeof(Camera) } }, + { DOTweenAnimation.AnimationType.CameraPixelRect, new[] { typeof(Camera) } }, + { DOTweenAnimation.AnimationType.CameraRect, new[] { typeof(Camera) } }, +#if true // UI_MARKER + { DOTweenAnimation.AnimationType.UIWidthHeight, new[] { typeof(RectTransform) } }, +#endif + }; + +#if false // TK2D_MARKER + static readonly Dictionary _Tk2dAnimationTypeToComponent = new Dictionary() { + { DOTweenAnimation.AnimationType.Scale, new[] { typeof(tk2dBaseSprite), typeof(tk2dTextMesh) } }, + { DOTweenAnimation.AnimationType.Color, new[] { typeof(tk2dBaseSprite), typeof(tk2dTextMesh) } }, + { DOTweenAnimation.AnimationType.Fade, new[] { typeof(tk2dBaseSprite), typeof(tk2dTextMesh) } }, + { DOTweenAnimation.AnimationType.Text, new[] { typeof(tk2dTextMesh) } } + }; +#endif +#if true // TEXTMESHPRO_MARKER + static readonly Dictionary _TMPAnimationTypeToComponent = new Dictionary() { + { DOTweenAnimation.AnimationType.Color, new[] { typeof(TextMeshPro), typeof(TextMeshProUGUI) } }, + { DOTweenAnimation.AnimationType.Fade, new[] { typeof(TextMeshPro), typeof(TextMeshProUGUI) } }, + { DOTweenAnimation.AnimationType.Text, new[] { typeof(TextMeshPro), typeof(TextMeshProUGUI) } } + }; +#endif + + static readonly string[] _AnimationType = new[] { + "None", + "Move", "LocalMove", + "Rotate", "LocalRotate", + "Scale", + "Color", "Fade", +#if true // UI_MARKER + "Text", +#endif +#if false // TK2D_MARKER + "Text", +#endif +#if true // TEXTMESHPRO_MARKER + "Text", +#endif +#if true // UI_MARKER + "UIWidthHeight", +#endif + "Punch/Position", "Punch/Rotation", "Punch/Scale", + "Shake/Position", "Shake/Rotation", "Shake/Scale", + "Camera/Aspect", "Camera/BackgroundColor", "Camera/FieldOfView", "Camera/OrthoSize", "Camera/PixelRect", "Camera/Rect" + }; + static string[] _animationTypeNoSlashes; // _AnimationType list without slashes in values + static string[] _datString; // String representation of DOTweenAnimation enum (here for caching reasons) + + DOTweenAnimation _src; + DOTweenSettings _settings; + bool _runtimeEditMode; // If TRUE allows to change and save stuff at runtime + bool _refreshRequired; // If TRUE refreshes components data + int _totComponentsOnSrc; // Used to determine if a Component is added or removed from the source + bool _isLightSrc; // Used to determine if we're tweening a Light, to set the max Fade value to more than 1 +#pragma warning disable 414 + ChooseTargetMode _chooseTargetMode = ChooseTargetMode.None; +#pragma warning restore 414 + + static readonly GUIContent _GuiC_selfTarget_true = new GUIContent( + "SELF", "Will animate components on this gameObject" + ); + static readonly GUIContent _GuiC_selfTarget_false = new GUIContent( + "OTHER", "Will animate components on the given gameObject instead than on this one" + ); + static readonly GUIContent _GuiC_tweenTargetIsTargetGO_true = new GUIContent( + "Use As Tween Target", "Will set the tween target (via SetTarget, used to control a tween directly from a target) to the \"OTHER\" gameObject" + ); + static readonly GUIContent _GuiC_tweenTargetIsTargetGO_false = new GUIContent( + "Use As Tween Target", "Will set the tween target (via SetTarget, used to control a tween directly from a target) to the gameObject containing this animation, not the \"OTHER\" one" + ); + + #region MonoBehaviour Methods + + void OnEnable() + { + _src = target as DOTweenAnimation; + _settings = DOTweenUtilityWindow.GetDOTweenSettings(); + + onStartProperty = base.serializedObject.FindProperty("onStart"); + onPlayProperty = base.serializedObject.FindProperty("onPlay"); + onUpdateProperty = base.serializedObject.FindProperty("onUpdate"); + onStepCompleteProperty = base.serializedObject.FindProperty("onStepComplete"); + onCompleteProperty = base.serializedObject.FindProperty("onComplete"); + onRewindProperty = base.serializedObject.FindProperty("onRewind"); + onTweenCreatedProperty = base.serializedObject.FindProperty("onTweenCreated"); + + // Convert _AnimationType to _animationTypeNoSlashes + int len = _AnimationType.Length; + _animationTypeNoSlashes = new string[len]; + for (int i = 0; i < len; ++i) { + string a = _AnimationType[i]; + a = a.Replace("/", ""); + _animationTypeNoSlashes[i] = a; + } + } + + void OnDisable() + { + DOTweenPreviewManager.StopAllPreviews(); + } + + override public void OnInspectorGUI() + { + base.OnInspectorGUI(); + + GUILayout.Space(3); + EditorGUIUtils.SetGUIStyles(); + + bool playMode = Application.isPlaying; + _runtimeEditMode = _runtimeEditMode && playMode; + + GUILayout.BeginHorizontal(); + EditorGUIUtils.InspectorLogo(); + GUILayout.Label(_src.animationType.ToString() + (string.IsNullOrEmpty(_src.id) ? "" : " [" + _src.id + "]"), EditorGUIUtils.sideLogoIconBoldLabelStyle); + // Up-down buttons + GUILayout.FlexibleSpace(); + if (GUILayout.Button("▲", DeGUI.styles.button.toolIco)) UnityEditorInternal.ComponentUtility.MoveComponentUp(_src); + if (GUILayout.Button("▼", DeGUI.styles.button.toolIco)) UnityEditorInternal.ComponentUtility.MoveComponentDown(_src); + GUILayout.EndHorizontal(); + + if (playMode) { + if (_runtimeEditMode) { + + } else { + GUILayout.Space(8); + GUILayout.Label("Animation Editor disabled while in play mode", EditorGUIUtils.wordWrapLabelStyle); + if (!_src.isActive) { + GUILayout.Label("This animation has been toggled as inactive and won't be generated", EditorGUIUtils.wordWrapLabelStyle); + GUI.enabled = false; + } + if (GUILayout.Button(new GUIContent("Activate Edit Mode", "Switches to Runtime Edit Mode, where you can change animations values and restart them"))) { + _runtimeEditMode = true; + } + GUILayout.Label("NOTE: when using DOPlayNext, the sequence is determined by the DOTweenAnimation Components order in the target GameObject's Inspector", EditorGUIUtils.wordWrapLabelStyle); + GUILayout.Space(10); + if (!_runtimeEditMode) return; + } + } + + Undo.RecordObject(_src, "DOTween Animation"); + Undo.RecordObject(_settings, "DOTween Animation"); + +// _src.isValid = Validate(); // Moved down + + EditorGUIUtility.labelWidth = 110; + + if (playMode) { + GUILayout.Space(4); + DeGUILayout.Toolbar("Edit Mode Commands"); + DeGUILayout.BeginVBox(DeGUI.styles.box.stickyTop); + GUILayout.BeginHorizontal(); + if (GUILayout.Button("TogglePause")) _src.tween.TogglePause(); + if (GUILayout.Button("Rewind")) _src.tween.Rewind(); + if (GUILayout.Button("Restart")) _src.tween.Restart(); + GUILayout.EndHorizontal(); + if (GUILayout.Button("Commit changes and restart")) { + _src.tween.Rewind(); + _src.tween.Kill(); + if (_src.isValid) { + _src.CreateTween(); + _src.tween.Play(); + } + } + GUILayout.Label("To apply your changes when exiting Play mode, use the Component's upper right menu and choose \"Copy Component\", then \"Paste Component Values\" after exiting Play mode", DeGUI.styles.label.wordwrap); + DeGUILayout.EndVBox(); + } else { + GUILayout.BeginHorizontal(); + bool hasManager = _src.GetComponent() != null; + EditorGUI.BeginChangeCheck(); + _settings.showPreviewPanel = hasManager + ? DeGUILayout.ToggleButton(_settings.showPreviewPanel, "Preview Controls", styles.custom.inlineToggle) + : DeGUILayout.ToggleButton(_settings.showPreviewPanel, "Preview Controls", styles.custom.inlineToggle, GUILayout.Width(120)); + if (EditorGUI.EndChangeCheck()) { + EditorUtility.SetDirty(_settings); + DOTweenPreviewManager.StopAllPreviews(); + } + if (!hasManager) { + if (GUILayout.Button(new GUIContent("Add Manager", "Adds a manager component which allows you to choose additional options for this gameObject"))) { + _src.gameObject.AddComponent(); + } + } + GUILayout.EndHorizontal(); + } + + // Preview in editor + bool isPreviewing = _settings.showPreviewPanel ? DOTweenPreviewManager.PreviewGUI(_src) : false; + + EditorGUI.BeginDisabledGroup(isPreviewing); + // Choose target + GUILayout.BeginHorizontal(); + _src.isActive = EditorGUILayout.Toggle(new GUIContent("", "If unchecked, this animation will not be created"), _src.isActive, GUILayout.Width(14)); + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginChangeCheck(); + _src.targetIsSelf = DeGUILayout.ToggleButton( + _src.targetIsSelf, _src.targetIsSelf ? _GuiC_selfTarget_true : _GuiC_selfTarget_false, + new Color(1f, 0.78f, 0f), DeGUI.colors.bg.toggleOn, new Color(0.33f, 0.14f, 0.02f), DeGUI.colors.content.toggleOn, + null, GUILayout.Width(47) + ); + bool innerChanged = EditorGUI.EndChangeCheck(); + if (innerChanged) { + _src.targetGO = null; + GUI.changed = true; + } + if (_src.targetIsSelf) GUILayout.Label(_GuiC_selfTarget_true.tooltip); + else { + using (new DeGUI.ColorScope(null, null, _src.targetGO == null ? Color.red : Color.white)) { + _src.targetGO = (GameObject)EditorGUILayout.ObjectField(_src.targetGO, typeof(GameObject), true); + } + _src.tweenTargetIsTargetGO = DeGUILayout.ToggleButton( + _src.tweenTargetIsTargetGO, _src.tweenTargetIsTargetGO ? _GuiC_tweenTargetIsTargetGO_true : _GuiC_tweenTargetIsTargetGO_false, + GUILayout.Width(131) + ); + } + bool check = EditorGUI.EndChangeCheck(); + if (check) _refreshRequired = true; + GUILayout.EndHorizontal(); + + GameObject targetGO = _src.targetIsSelf ? _src.gameObject : _src.targetGO; + + if (targetGO == null) { + // Uses external target gameObject but it's not set + if (_src.targetGO != null || _src.target != null) { + _src.targetGO = null; + _src.target = null; + GUI.changed = true; + } + } else { + GUILayout.BeginHorizontal(); + DOTweenAnimation.AnimationType prevAnimType = _src.animationType; +// _src.animationType = (DOTweenAnimation.AnimationType)EditorGUILayout.EnumPopup(_src.animationType, EditorGUIUtils.popupButton); + GUI.enabled = GUI.enabled && _src.isActive; + _src.animationType = AnimationToDOTweenAnimationType(_AnimationType[EditorGUILayout.Popup(DOTweenAnimationTypeToPopupId(_src.animationType), _AnimationType)]); + _src.autoPlay = DeGUILayout.ToggleButton(_src.autoPlay, new GUIContent("AutoPlay", "If selected, the tween will play automatically")); + _src.autoKill = DeGUILayout.ToggleButton(_src.autoKill, new GUIContent("AutoKill", "If selected, the tween will be killed when it completes, and won't be reusable")); + GUILayout.EndHorizontal(); + if (prevAnimType != _src.animationType) { + // Set default optional values based on animation type + _src.endValueTransform = null; + _src.useTargetAsV3 = false; + switch (_src.animationType) { + case DOTweenAnimation.AnimationType.Move: + case DOTweenAnimation.AnimationType.LocalMove: + case DOTweenAnimation.AnimationType.Rotate: + case DOTweenAnimation.AnimationType.LocalRotate: + case DOTweenAnimation.AnimationType.Scale: + _src.endValueV3 = Vector3.zero; + _src.endValueFloat = 0; + _src.optionalBool0 = _src.animationType == DOTweenAnimation.AnimationType.Scale; + break; + case DOTweenAnimation.AnimationType.UIWidthHeight: + _src.endValueV3 = Vector3.zero; + _src.endValueFloat = 0; + _src.optionalBool0 = _src.animationType == DOTweenAnimation.AnimationType.UIWidthHeight; + break; + case DOTweenAnimation.AnimationType.Color: + case DOTweenAnimation.AnimationType.Fade: + _isLightSrc = targetGO.GetComponent() != null; + _src.endValueFloat = 0; + break; + case DOTweenAnimation.AnimationType.Text: + _src.optionalBool0 = true; + break; + case DOTweenAnimation.AnimationType.PunchPosition: + case DOTweenAnimation.AnimationType.PunchRotation: + case DOTweenAnimation.AnimationType.PunchScale: + _src.endValueV3 = _src.animationType == DOTweenAnimation.AnimationType.PunchRotation ? new Vector3(0, 180, 0) : Vector3.one; + _src.optionalFloat0 = 1; + _src.optionalInt0 = 10; + _src.optionalBool0 = false; + break; + case DOTweenAnimation.AnimationType.ShakePosition: + case DOTweenAnimation.AnimationType.ShakeRotation: + case DOTweenAnimation.AnimationType.ShakeScale: + _src.endValueV3 = _src.animationType == DOTweenAnimation.AnimationType.ShakeRotation ? new Vector3(90, 90, 90) : Vector3.one; + _src.optionalInt0 = 10; + _src.optionalFloat0 = 90; + _src.optionalBool0 = false; + break; + case DOTweenAnimation.AnimationType.CameraAspect: + case DOTweenAnimation.AnimationType.CameraFieldOfView: + case DOTweenAnimation.AnimationType.CameraOrthoSize: + _src.endValueFloat = 0; + break; + case DOTweenAnimation.AnimationType.CameraPixelRect: + case DOTweenAnimation.AnimationType.CameraRect: + _src.endValueRect = new Rect(0, 0, 0, 0); + break; + } + } + if (_src.animationType == DOTweenAnimation.AnimationType.None) { + _src.isValid = false; + if (GUI.changed) EditorUtility.SetDirty(_src); + return; + } + + if (_refreshRequired || prevAnimType != _src.animationType || ComponentsChanged()) { + _refreshRequired = false; + _src.isValid = Validate(targetGO); + // See if we need to choose between multiple targets +#if true // UI_MARKER + if (_src.animationType == DOTweenAnimation.AnimationType.Fade && targetGO.GetComponent() != null && targetGO.GetComponent() != null) { + _chooseTargetMode = ChooseTargetMode.BetweenCanvasGroupAndImage; + // Reassign target and forcedTargetType if lost + if (_src.forcedTargetType == DOTweenAnimation.TargetType.Unset) _src.forcedTargetType = _src.targetType; + switch (_src.forcedTargetType) { + case DOTweenAnimation.TargetType.CanvasGroup: + _src.target = targetGO.GetComponent(); + break; + case DOTweenAnimation.TargetType.Image: + _src.target = targetGO.GetComponent(); + break; + } + } else { +#endif + _chooseTargetMode = ChooseTargetMode.None; + _src.forcedTargetType = DOTweenAnimation.TargetType.Unset; +#if true // UI_MARKER + } +#endif + } + + if (!_src.isValid) { + GUI.color = Color.red; + GUILayout.BeginVertical(GUI.skin.box); + GUILayout.Label("No valid Component was found for the selected animation", EditorGUIUtils.wordWrapLabelStyle); + GUILayout.EndVertical(); + GUI.color = Color.white; + if (GUI.changed) EditorUtility.SetDirty(_src); + return; + } + +#if true // UI_MARKER + // Special cases in which multiple target types could be used (set after validation) + if (_chooseTargetMode == ChooseTargetMode.BetweenCanvasGroupAndImage && _src.forcedTargetType != DOTweenAnimation.TargetType.Unset) { + FadeTargetType fadeTargetType = (FadeTargetType)Enum.Parse(typeof(FadeTargetType), _src.forcedTargetType.ToString()); + DOTweenAnimation.TargetType prevTargetType = _src.forcedTargetType; + _src.forcedTargetType = (DOTweenAnimation.TargetType)Enum.Parse(typeof(DOTweenAnimation.TargetType), EditorGUILayout.EnumPopup(_src.animationType + " Target", fadeTargetType).ToString()); + if (_src.forcedTargetType != prevTargetType) { + // Target type change > assign correct target + switch (_src.forcedTargetType) { + case DOTweenAnimation.TargetType.CanvasGroup: + _src.target = targetGO.GetComponent(); + break; + case DOTweenAnimation.TargetType.Image: + _src.target = targetGO.GetComponent(); + break; + } + } + } +#endif + + GUILayout.BeginHorizontal(); + _src.duration = EditorGUILayout.FloatField("Duration", _src.duration); + if (_src.duration < 0) _src.duration = 0; + _src.isSpeedBased = DeGUILayout.ToggleButton(_src.isSpeedBased, new GUIContent("SpeedBased", "If selected, the duration will count as units/degree x second"), DeGUI.styles.button.tool, GUILayout.Width(75)); + GUILayout.EndHorizontal(); + _src.delay = EditorGUILayout.FloatField("Delay", _src.delay); + if (_src.delay < 0) _src.delay = 0; + _src.isIndependentUpdate = EditorGUILayout.Toggle("Ignore TimeScale", _src.isIndependentUpdate); + _src.easeType = EditorGUIUtils.FilteredEasePopup("Ease", _src.easeType); + if (_src.easeType == Ease.INTERNAL_Custom) { + _src.easeCurve = EditorGUILayout.CurveField(" Ease Curve", _src.easeCurve); + } + _src.loops = EditorGUILayout.IntField(new GUIContent("Loops", "Set to -1 for infinite loops"), _src.loops); + if (_src.loops < -1) _src.loops = -1; + if (_src.loops > 1 || _src.loops == -1) + _src.loopType = (LoopType)EditorGUILayout.EnumPopup(" Loop Type", _src.loopType); + _src.id = EditorGUILayout.TextField("ID", _src.id); + + bool canBeRelative = true; + // End value and eventual specific options + switch (_src.animationType) { + case DOTweenAnimation.AnimationType.Move: + case DOTweenAnimation.AnimationType.LocalMove: + GUIEndValueV3(targetGO, _src.animationType == DOTweenAnimation.AnimationType.Move); + _src.optionalBool0 = EditorGUILayout.Toggle(" Snapping", _src.optionalBool0); + canBeRelative = !_src.useTargetAsV3; + break; + case DOTweenAnimation.AnimationType.Rotate: + case DOTweenAnimation.AnimationType.LocalRotate: + bool isRigidbody2D = DOTweenModuleUtils.Physics.HasRigidbody2D(_src); + if (isRigidbody2D) GUIEndValueFloat(); + else { + GUIEndValueV3(targetGO); + _src.optionalRotationMode = (RotateMode)EditorGUILayout.EnumPopup(" Rotation Mode", _src.optionalRotationMode); + } + break; + case DOTweenAnimation.AnimationType.Scale: + if (_src.optionalBool0) GUIEndValueFloat(); + else GUIEndValueV3(targetGO); + _src.optionalBool0 = EditorGUILayout.Toggle("Uniform Scale", _src.optionalBool0); + break; + case DOTweenAnimation.AnimationType.UIWidthHeight: + if (_src.optionalBool0) GUIEndValueFloat(); + else GUIEndValueV2(); + _src.optionalBool0 = EditorGUILayout.Toggle("Uniform Scale", _src.optionalBool0); + break; + case DOTweenAnimation.AnimationType.Color: + GUIEndValueColor(); + canBeRelative = false; + break; + case DOTweenAnimation.AnimationType.Fade: + GUIEndValueFloat(); + if (_src.endValueFloat < 0) _src.endValueFloat = 0; + if (!_isLightSrc && _src.endValueFloat > 1) _src.endValueFloat = 1; + canBeRelative = false; + break; + case DOTweenAnimation.AnimationType.Text: + GUIEndValueString(); + _src.optionalBool0 = EditorGUILayout.Toggle("Rich Text Enabled", _src.optionalBool0); + _src.optionalScrambleMode = (ScrambleMode)EditorGUILayout.EnumPopup("Scramble Mode", _src.optionalScrambleMode); + _src.optionalString = EditorGUILayout.TextField(new GUIContent("Custom Scramble", "Custom characters to use in case of ScrambleMode.Custom"), _src.optionalString); + break; + case DOTweenAnimation.AnimationType.PunchPosition: + case DOTweenAnimation.AnimationType.PunchRotation: + case DOTweenAnimation.AnimationType.PunchScale: + GUIEndValueV3(targetGO); + canBeRelative = false; + _src.optionalInt0 = EditorGUILayout.IntSlider(new GUIContent(" Vibrato", "How much will the punch vibrate"), _src.optionalInt0, 1, 50); + _src.optionalFloat0 = EditorGUILayout.Slider(new GUIContent(" Elasticity", "How much the vector will go beyond the starting position when bouncing backwards"), _src.optionalFloat0, 0, 1); + if (_src.animationType == DOTweenAnimation.AnimationType.PunchPosition) _src.optionalBool0 = EditorGUILayout.Toggle(" Snapping", _src.optionalBool0); + break; + case DOTweenAnimation.AnimationType.ShakePosition: + case DOTweenAnimation.AnimationType.ShakeRotation: + case DOTweenAnimation.AnimationType.ShakeScale: + GUIEndValueV3(targetGO); + canBeRelative = false; + _src.optionalInt0 = EditorGUILayout.IntSlider(new GUIContent(" Vibrato", "How much will the shake vibrate"), _src.optionalInt0, 1, 50); + _src.optionalFloat0 = EditorGUILayout.Slider(new GUIContent(" Randomness", "The shake randomness"), _src.optionalFloat0, 0, 90); + if (_src.animationType == DOTweenAnimation.AnimationType.ShakePosition) _src.optionalBool0 = EditorGUILayout.Toggle(" Snapping", _src.optionalBool0); + break; + case DOTweenAnimation.AnimationType.CameraAspect: + case DOTweenAnimation.AnimationType.CameraFieldOfView: + case DOTweenAnimation.AnimationType.CameraOrthoSize: + GUIEndValueFloat(); + canBeRelative = false; + break; + case DOTweenAnimation.AnimationType.CameraBackgroundColor: + GUIEndValueColor(); + canBeRelative = false; + break; + case DOTweenAnimation.AnimationType.CameraPixelRect: + case DOTweenAnimation.AnimationType.CameraRect: + GUIEndValueRect(); + canBeRelative = false; + break; + } + + // Final settings + if (canBeRelative) _src.isRelative = EditorGUILayout.Toggle(" Relative", _src.isRelative); + + // Events + AnimationInspectorGUI.AnimationEvents(this, _src); + } + EditorGUI.EndDisabledGroup(); + + if (GUI.changed) EditorUtility.SetDirty(_src); + } + + #endregion + + #region Methods + + // Returns TRUE if the Component layout on the src gameObject changed (a Component was added or removed) + bool ComponentsChanged() + { + int prevTotComponentsOnSrc = _totComponentsOnSrc; + _totComponentsOnSrc = _src.gameObject.GetComponents().Length; + return prevTotComponentsOnSrc != _totComponentsOnSrc; + } + + // Checks if a Component that can be animated with the given animationType is attached to the src + bool Validate(GameObject targetGO) + { + if (_src.animationType == DOTweenAnimation.AnimationType.None) return false; + + Component srcTarget; + // First check for external plugins +#if false // TK2D_MARKER + if (_Tk2dAnimationTypeToComponent.ContainsKey(_src.animationType)) { + foreach (Type t in _Tk2dAnimationTypeToComponent[_src.animationType]) { + srcTarget = targetGO.GetComponent(t); + if (srcTarget != null) { + _src.target = srcTarget; + _src.targetType = DOTweenAnimation.TypeToDOTargetType(t); + return true; + } + } + } +#endif +#if true // TEXTMESHPRO_MARKER + if (_TMPAnimationTypeToComponent.ContainsKey(_src.animationType)) { + foreach (Type t in _TMPAnimationTypeToComponent[_src.animationType]) { + srcTarget = targetGO.GetComponent(t); + if (srcTarget != null) { + _src.target = srcTarget; + _src.targetType = DOTweenAnimation.TypeToDOTargetType(t); + return true; + } + } + } +#endif + // Then check for regular stuff + if (_AnimationTypeToComponent.ContainsKey(_src.animationType)) { + foreach (Type t in _AnimationTypeToComponent[_src.animationType]) { + srcTarget = targetGO.GetComponent(t); + if (srcTarget != null) { + _src.target = srcTarget; + _src.targetType = DOTweenAnimation.TypeToDOTargetType(t); + return true; + } + } + } + return false; + } + + DOTweenAnimation.AnimationType AnimationToDOTweenAnimationType(string animation) + { + if (_datString == null) _datString = Enum.GetNames(typeof(DOTweenAnimation.AnimationType)); + animation = animation.Replace("/", ""); + return (DOTweenAnimation.AnimationType)(Array.IndexOf(_datString, animation)); + } + int DOTweenAnimationTypeToPopupId(DOTweenAnimation.AnimationType animation) + { + return Array.IndexOf(_animationTypeNoSlashes, animation.ToString()); + } + + #endregion + + #region GUI Draw Methods + + void GUIEndValueFloat() + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + _src.endValueFloat = EditorGUILayout.FloatField(_src.endValueFloat); + GUILayout.EndHorizontal(); + } + + void GUIEndValueColor() + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + _src.endValueColor = EditorGUILayout.ColorField(_src.endValueColor); + GUILayout.EndHorizontal(); + } + + void GUIEndValueV3(GameObject targetGO, bool optionalTransform = false) + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + if (_src.useTargetAsV3) { + Transform prevT = _src.endValueTransform; + _src.endValueTransform = EditorGUILayout.ObjectField(_src.endValueTransform, typeof(Transform), true) as Transform; + if (_src.endValueTransform != prevT && _src.endValueTransform != null) { +#if true // UI_MARKER + // Check that it's a Transform for a Transform or a RectTransform for a RectTransform + if (targetGO.GetComponent() != null) { + if (_src.endValueTransform.GetComponent() == null) { + EditorUtility.DisplayDialog("DOTween Pro", "For Unity UI elements, the target must also be a UI element", "Ok"); + _src.endValueTransform = null; + } + } else if (_src.endValueTransform.GetComponent() != null) { + EditorUtility.DisplayDialog("DOTween Pro", "You can't use a UI target for a non UI object", "Ok"); + _src.endValueTransform = null; + } +#endif + } + } else { + _src.endValueV3 = EditorGUILayout.Vector3Field("", _src.endValueV3, GUILayout.Height(16)); + } + if (optionalTransform) { + if (GUILayout.Button(_src.useTargetAsV3 ? "target" : "value", EditorGUIUtils.sideBtStyle, GUILayout.Width(44))) _src.useTargetAsV3 = !_src.useTargetAsV3; + } + GUILayout.EndHorizontal(); +#if true // UI_MARKER + if (_src.useTargetAsV3 && _src.endValueTransform != null && _src.target is RectTransform) { + EditorGUILayout.HelpBox("NOTE: when using a UI target, the tween will be created during Start instead of Awake", MessageType.Info); + } +#endif + } + + void GUIEndValueV2() + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + _src.endValueV2 = EditorGUILayout.Vector2Field("", _src.endValueV2, GUILayout.Height(16)); + GUILayout.EndHorizontal(); + } + + void GUIEndValueString() + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + _src.endValueString = EditorGUILayout.TextArea(_src.endValueString, EditorGUIUtils.wordWrapTextArea); + GUILayout.EndHorizontal(); + } + + void GUIEndValueRect() + { + GUILayout.BeginHorizontal(); + GUIToFromButton(); + _src.endValueRect = EditorGUILayout.RectField(_src.endValueRect); + GUILayout.EndHorizontal(); + } + + void GUIToFromButton() + { + if (GUILayout.Button(_src.isFrom ? "FROM" : "TO", EditorGUIUtils.sideBtStyle, GUILayout.Width(90))) _src.isFrom = !_src.isFrom; + GUILayout.Space(16); + } + + #endregion + } + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + [InitializeOnLoad] + static class Initializer + { + static Initializer() + { + DOTweenAnimation.OnReset += OnReset; + } + + static void OnReset(DOTweenAnimation src) + { + DOTweenSettings settings = DOTweenUtilityWindow.GetDOTweenSettings(); + if (settings == null) return; + + Undo.RecordObject(src, "DOTweenAnimation"); + src.autoPlay = settings.defaultAutoPlay == AutoPlay.All || settings.defaultAutoPlay == AutoPlay.AutoPlayTweeners; + src.autoKill = settings.defaultAutoKill; + EditorUtility.SetDirty(src); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs.meta new file mode 100644 index 0000000..d2d7eee --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenAnimationInspector.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e0203fd81362bab4d842d87ad09ee76e +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs new file mode 100644 index 0000000..e607979 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs @@ -0,0 +1,263 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2015/03/12 16:03 + +using System; +using System.Collections.Generic; +using DG.DemiEditor; +using DG.DemiLib; +using DG.Tweening; +using DG.Tweening.Core; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace DG.DOTweenEditor +{ + public static class DOTweenPreviewManager + { + static bool _previewOnlyIfSetToAutoPlay = true; + static readonly Dictionary _AnimationToTween = new Dictionary(); + static readonly List _TmpKeys = new List(); + + #region Public Methods & GUI + + /// + /// Returns TRUE if its actually previewing animations + /// + public static bool PreviewGUI(DOTweenAnimation src) + { + if (EditorApplication.isPlaying) return false; + + Styles.Init(); + + bool isPreviewing = _AnimationToTween.Count > 0; + bool isPreviewingThis = isPreviewing && _AnimationToTween.ContainsKey(src); + + // Preview in editor + GUI.backgroundColor = isPreviewing + ? new DeSkinColor(new Color(0.49f, 0.8f, 0.86f), new Color(0.15f, 0.26f, 0.35f)) + : new DeSkinColor(Color.white, new Color(0.13f, 0.13f, 0.13f)); + GUILayout.BeginVertical(Styles.previewBox); + DeGUI.ResetGUIColors(); + GUILayout.BeginHorizontal(); + GUILayout.Label("Preview Mode - Experimental", Styles.previewLabel); + _previewOnlyIfSetToAutoPlay = DeGUILayout.ToggleButton( + _previewOnlyIfSetToAutoPlay, + new GUIContent("AutoPlay only", "If toggled only previews animations that have AutoPlay turned ON"), + Styles.btOption + ); + GUILayout.EndHorizontal(); + GUILayout.Space(1); + // Preview - Play + GUILayout.BeginHorizontal(); + EditorGUI.BeginDisabledGroup( + isPreviewingThis || src.animationType == DOTweenAnimation.AnimationType.None + || !src.isActive || _previewOnlyIfSetToAutoPlay && !src.autoPlay + ); + if (GUILayout.Button("► Play", Styles.btPreview)) { + if (!isPreviewing) StartupGlobalPreview(); + AddAnimationToGlobalPreview(src); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(isPreviewing); + if (GUILayout.Button("► Play All on GameObject", Styles.btPreview)) { + if (!isPreviewing) StartupGlobalPreview(); + DOTweenAnimation[] anims = src.gameObject.GetComponents(); + foreach (DOTweenAnimation anim in anims) AddAnimationToGlobalPreview(anim); + } + if (GUILayout.Button("► Play All in Scene", Styles.btPreview)) { + if (!isPreviewing) StartupGlobalPreview(); + DOTweenAnimation[] anims = Object.FindObjectsOfType(); + foreach (DOTweenAnimation anim in anims) AddAnimationToGlobalPreview(anim); + } + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + // Preview - Stop + GUILayout.BeginHorizontal(); + EditorGUI.BeginDisabledGroup(!isPreviewingThis); + if (GUILayout.Button("■ Stop", Styles.btPreview)) { + if (_AnimationToTween.ContainsKey(src)) StopPreview(_AnimationToTween[src].tween); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!isPreviewing); + if (GUILayout.Button("■ Stop All on GameObject", Styles.btPreview)) { + StopPreview(src.gameObject); + } + if (GUILayout.Button("■ Stop All in Scene", Styles.btPreview)) { + StopAllPreviews(); + } + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + if (isPreviewing) { + int playingTweens = 0; + int completedTweens = 0; + int pausedTweens = 0; + foreach (KeyValuePair kvp in _AnimationToTween) { + Tween t = kvp.Value.tween; + if (t.IsPlaying()) playingTweens++; + else if (t.IsComplete()) completedTweens++; + else pausedTweens++; + } + GUILayout.Label("Playing Tweens: " + playingTweens, Styles.previewStatusLabel); + GUILayout.Label("Completed Tweens: " + completedTweens, Styles.previewStatusLabel); +// GUILayout.Label("Paused Tweens: " + playingTweens); + } + GUILayout.EndVertical(); + + return isPreviewing; + } + +#if !(UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5) + public static void StopAllPreviews(PlayModeStateChange state) + { + StopAllPreviews(); + } +#endif + + public static void StopAllPreviews() + { + _TmpKeys.Clear(); + foreach (KeyValuePair kvp in _AnimationToTween) { + _TmpKeys.Add(kvp.Key); + } + StopPreview(_TmpKeys); + _TmpKeys.Clear(); + _AnimationToTween.Clear(); + + DOTweenEditorPreview.Stop(); +#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 + UnityEditor.EditorApplication.playmodeStateChanged -= StopAllPreviews; +#else + UnityEditor.EditorApplication.playModeStateChanged -= StopAllPreviews; +#endif +// EditorApplication.playmodeStateChanged -= StopAllPreviews; + + InternalEditorUtility.RepaintAllViews(); + } + +#endregion + +#region Methods + + static void StartupGlobalPreview() + { + DOTweenEditorPreview.Start(); +#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 + UnityEditor.EditorApplication.playmodeStateChanged += StopAllPreviews; +#else + UnityEditor.EditorApplication.playModeStateChanged += StopAllPreviews; +#endif +// EditorApplication.playmodeStateChanged += StopAllPreviews; + } + + static void AddAnimationToGlobalPreview(DOTweenAnimation src) + { + if (!src.isActive) return; // Ignore sources whose tweens have been set to inactive + if (_previewOnlyIfSetToAutoPlay && !src.autoPlay) return; + + Tween t = src.CreateEditorPreview(); + _AnimationToTween.Add(src, new TweenInfo(src, t, src.isFrom)); + // Tween setup + DOTweenEditorPreview.PrepareTweenForPreview(t); + } + + static void StopPreview(GameObject go) + { + _TmpKeys.Clear(); + foreach (KeyValuePair kvp in _AnimationToTween) { + if (kvp.Key.gameObject != go) continue; + _TmpKeys.Add(kvp.Key); + } + StopPreview(_TmpKeys); + _TmpKeys.Clear(); + + if (_AnimationToTween.Count == 0) StopAllPreviews(); + else InternalEditorUtility.RepaintAllViews(); + } + + static void StopPreview(Tween t) + { + TweenInfo tInfo = null; + foreach (KeyValuePair kvp in _AnimationToTween) { + if (kvp.Value.tween != t) continue; + tInfo = kvp.Value; + _AnimationToTween.Remove(kvp.Key); + break; + } + if (tInfo == null) { + Debug.LogWarning("DOTween Preview ► Couldn't find tween to stop"); + return; + } + if (tInfo.isFrom) { + int totLoops = tInfo.tween.Loops(); + if (totLoops < 0 || totLoops > 1) { + tInfo.tween.Goto(tInfo.tween.Duration(false)); + } else tInfo.tween.Complete(); + } else tInfo.tween.Rewind(); + tInfo.tween.Kill(); + EditorUtility.SetDirty(tInfo.animation); // Refresh views + + if (_AnimationToTween.Count == 0) StopAllPreviews(); + else InternalEditorUtility.RepaintAllViews(); + } + + // Stops while iterating inversely, which deals better with tweens that overwrite each other + static void StopPreview(List keys) + { + for (int i = keys.Count - 1; i > -1; --i) { + DOTweenAnimation anim = keys[i]; + TweenInfo tInfo = _AnimationToTween[anim]; + if (tInfo.isFrom) { + int totLoops = tInfo.tween.Loops(); + if (totLoops < 0 || totLoops > 1) { + tInfo.tween.Goto(tInfo.tween.Duration(false)); + } else tInfo.tween.Complete(); + } else tInfo.tween.Rewind(); + tInfo.tween.Kill(); + EditorUtility.SetDirty(anim); // Refresh views + _AnimationToTween.Remove(anim); + } + } + +#endregion + + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ + // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ + + class TweenInfo + { + public DOTweenAnimation animation; + public Tween tween; + public bool isFrom; + public TweenInfo(DOTweenAnimation animation, Tween tween, bool isFrom) + { + this.animation = animation; + this.tween = tween; + this.isFrom = isFrom; + } + } + + static class Styles + { + static bool _initialized; + + public static GUIStyle previewBox, previewLabel, btOption, btPreview, previewStatusLabel; + + public static void Init() + { + if (_initialized) return; + + _initialized = true; + + previewBox = new GUIStyle(GUI.skin.box).Clone().Padding(1, 1, 0, 3) + .Background(DeStylePalette.squareBorderCurved_darkBorders).Border(7, 7, 7, 7); + previewLabel = new GUIStyle(GUI.skin.label).Clone(10, FontStyle.Bold).Padding(1, 0, 3, 0).Margin(3, 6, 0, 0).StretchWidth(false); + btOption = DeGUI.styles.button.bBlankBorderCompact.MarginBottom(2).MarginRight(4); + btPreview = EditorStyles.miniButton.Clone(Format.RichText); + previewStatusLabel = EditorStyles.miniLabel.Clone().Padding(4, 0, 0, 0).Margin(0); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs.meta new file mode 100644 index 0000000..53780cc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPreviewManager.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 22292a5f27a9a644ba9e6ad1bf863531 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef new file mode 100644 index 0000000..da82d7e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef @@ -0,0 +1,12 @@ +{ + "name": "DOTweenPro.EditorScripts", + "references": [ + "Unity.TextMeshPro", + "DOTween.Modules", + "DOTweenPro.Scripts" + ], + "includePlatforms": [ + "Editor" + ], + "autoReferenced": false +} diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef.meta new file mode 100644 index 0000000..0737f5a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenPro.EditorScripts.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4a0c20e561919dc458cbce91f0dddc50 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML new file mode 100644 index 0000000..ad80aef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML @@ -0,0 +1,18 @@ + + + + DOTweenProEditor + + + + + Custom colors + + + + + Needs to be overridden in order to initialize new styles added from inherited classes + + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML.meta new file mode 100644 index 0000000..f37a133 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.XML.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 753a4f4ed73b17143923101226957756 +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll new file mode 100644 index 0000000..04feefd Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb new file mode 100644 index 0000000..8f32388 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb.meta new file mode 100644 index 0000000..f7149bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: ee3a420017f129443896310d9fab256b +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.meta new file mode 100644 index 0000000..62ab8c0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.dll.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: a6402d4311c862b4eb1325590d6466af +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip new file mode 100644 index 0000000..3d5eff9 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip.meta new file mode 100644 index 0000000..d38445e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/Editor/DOTweenProEditor.zip.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7d8319d7443886d43af20da7db38d51b +timeCreated: 1594632147 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt new file mode 100644 index 0000000..9837c95 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt @@ -0,0 +1,35 @@ +DOTween and DOTween Pro are copyright (c) 2014-2018 Daniele Giardini - Demigiant + +// IMPORTANT!!! ///////////////////////////////////////////// +// Upgrading DOTween from versions older than 1.2.000 /////// +// (or DOTween Pro older than 1.0.000) ////////////////////// +------------------------------------------------------------- +If you're upgrading your project from a version of DOTween older than 1.2.000 (or DOTween Pro older than 1.0.000) please follow these instructions carefully. +1) Import the new version in the same folder as the previous one, overwriting old files. A lot of errors will appear but don't worry +2) Close and reopen Unity (and your project). This is fundamental: skipping this step will cause a bloodbath +3) Open DOTween's Utility Panel (Tools > Demigiant > DOTween Utility Panel) if it doesn't open automatically, then press "Setup DOTween...": this will run the upgrade setup +4) From the Add/Remove Modules panel that opens, activate/deactivate Modules for Unity systems and for external assets (like TextMesh Pro) + +// GET STARTED ////////////////////////////////////////////// + +- After importing a new DOTween update, select DOTween's Utility Panel from the "Tools/Demigiant" menu (if it doesn't open automatically) and press the "Setup DOTween..." button to activate/deactivate Modules. You can also access a Preferences Tab from there to choose default settings for DOTween. + +// VISUAL SCRIPTING (PRO ONLY) +- To animate a gameObject, select it and choose "Add Component > DOTween > DOTween Animation" +- To animate a gameObject along a path, select it and choose "Add Component > DOTween > DOTween Path" + +// SCRIPTING +- In your code, add "using DG.Tweening" to each class where you want to use DOTween. +- You're ready to tween. Check out the links below for full documentation and license info. + + +// LINKS /////////////////////////////////////////////////////// + +DOTween website (documentation, examples, etc): http://dotween.demigiant.com +DOTween license: http://dotween.demigiant.com/license.php +DOTween repository (Google Code): https://code.google.com/p/dotween/ +Demigiant website (documentation, examples, etc): http://www.demigiant.com + +// NOTES ////////////////////////////////////////////////////// + +- DOTween's Utility Panel can be found under "Tools > Demigiant > DOTween Utility Panel" and also contains other useful options, plus a tab to set DOTween's preferences \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt.meta b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt.meta new file mode 100644 index 0000000..6a87c35 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DOTweenPro/readme.txt.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: aa8f07903bf128e44a7d0b91a63dedab +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib.meta new file mode 100644 index 0000000..edcf2cc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib.meta @@ -0,0 +1,21 @@ +fileFormatVersion: 2 +guid: 5a499e4809836274eb38cd99b370a2c1 +labels: +- Tween +- Tweening +- Animation +- HOTween +- Paths +- iTween +- DFTween +- LeanTween +- Ease +- Easing +- Shake +- Punch +- 2DToolkit +- TextMeshPro +- Text +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core.meta new file mode 100644 index 0000000..86e5075 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 03513cf143bb144409fbb3a51ec77b1b +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll new file mode 100644 index 0000000..bb5dc5e Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb new file mode 100644 index 0000000..9af8a2a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb.meta new file mode 100644 index 0000000..de5f720 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 995cf2d9b4a41f840b3a41712e9b3bc0 +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.meta new file mode 100644 index 0000000..1ed9199 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.dll.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: 54be29b67d0d29a478da2c6e5c62f091 +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Any: + enabled: 1 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml new file mode 100644 index 0000000..f5d8520 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml @@ -0,0 +1,200 @@ + + + + DemiLib + + + + + Class attribute + Sets the script execution order index + + + + + Sets the script execution order for this class + + Script execution order index + + + + Set when calling DeGUI.BeginGUI + + + + + Stores a color palette, which can be passed to default DeGUI layouts when calling DeGUI.BeginGUI, + and changed at any time by calling DeGUI.ChangePalette. + You can inherit from this class to create custom color palettes with more hColor options. + + + + + Converts a HEX color to a Unity Color and returns it + + The HEX color, either with or without the initial # (accepts both regular and short format) + + + + Global colors + + + + + Background colors + + + + Editor background color + + + + Content colors + + + + + Various Input utils + + + + + Returns a number key int if a number key was pressed in this frame, or -1 otherwise + + + + + + Extend this to replicate Unity's Scope system with any Unity version. + Thanks to Dmitriy Yukhanov for pointing this out and creating an initial version. + Expand this class to create scopes. + Example: + public class VBoxScope : DeScope + { + public VBoxScope(GUIStyle style) + { + BeginVBox(style); + } + + protected override void CloseScope() + { + EndVBox(); + } + } + Usage: + using (new VBoxScope(myStyle) { + // Do something + } + + + + + Contains both free and pro skins color variations, + and automatically returns the correct one when converted to Color + + + + + Used by DeHierarchy + + + + + Returns a list of all items whose gameObject is NULL, or NULL if there's no missing gameObjects. + + + + + If the item exists sets it, otherwise first creates it and then sets it + + + + + If the item exists sets it, otherwise first creates it and then sets it + + + + + If the item exists sets it, otherwise first creates it and then sets it + + + + + Returns TRUE if the item existed and was removed. + + + + + Returns TRUE if the item existed and was changed. + + + + + Returns the customizedItem for the given gameObject, or NULL if none was found + + + + + Returns the color corresponding to the given + + + + Must be univocal + + + Node position in editor GUI + + + Ids of all forward connected nodes. Length indicates how many forward connections are allowed. + Min length represents available connections from node. + + + + A serializable struct including a min and a max int value + + + + Min value + + + Max value + + + + Creates a new Range + + + + + Returns a random value within this range (min/max included) + + + + + + + + A serializable struct including a min and a max float value + + + + Min value + + + Max value + + + + Creates a new Range + + + + + Returns a random value within this range (min/max included) + + + + + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml.meta new file mode 100644 index 0000000..473a9b5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/DemiLib.xml.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 9bf2564c9817bb34988453ae948954d2 +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor.meta new file mode 100644 index 0000000..11f8e33 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 77fbbad1c51d68f4c844d26743104b07 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll new file mode 100644 index 0000000..938cafe Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb new file mode 100644 index 0000000..86b2467 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb.meta new file mode 100644 index 0000000..b640c3e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.mdb.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 2c20a7b4db3cd0a4a99bcf6218f92860 +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.meta new file mode 100644 index 0000000..aa20ddf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.dll.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: 202f9ddaf2c1a8a429504f7f3cd7b84f +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml new file mode 100644 index 0000000..5f7ef46 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml @@ -0,0 +1,2117 @@ + + + + DemiEditor + + + + + Utils to use he correct method based on Unity's version + + + + + Encodes to PNG using reflection to use correct method depending if editor is version 2017 or earlier + + + + + Returns the prefab parent by using different code on Unity 2018 or later + + + + + + + Starts an editor coroutine. You can't use normal yield new WaitFor methods because + those are Unity runtime, but you can instead use . + Other than that, you can use normal yield null/etc. + Returns an which you can use with to cancel the coroutine. + + + + + Stops the given coroutine generated by + + + + + To be used inside a coroutine as a yield instruction: waits for the given seconds + (replaces Unity's yield new WaitForSeconds because it's not available in-editor). + Example usage: + yield return DeEditorCoroutines.WaitForSeconds(1); + + + + + File utils + + + + Path slash for AssetDatabase format + + + Path slash to replace for AssetDatabase format + + + Current OS path slash + + + Path slash to replace on current OS + + + + Full path to project directory, without final slash. + + + + + Full path to project's Assets directory, without final slash. + + + + + Returns TRUE if the given path is an absolute path + + + + + Returns TRUE if the given path is an AssetDatabase path + + + + + Returns TRUE if the given GUID refers to a valid and existing project folder + + + + + Converts the given project-relative path to a full path + + + + + Converts the given full path to a project-relative path + + + + + Returns TRUE if the file/directory at the given path exists. + + Path, relative to Unity's project folder + + + + Validates the string as a valid fileName + (uses commonly accepted characters an all systems instead of system-specific ones). + BEWARE: doesn't check for reserved words + + string to replace + Minimum length for considering the string valid + + + + Returns TRUE if the given filepath is within this Unity project Assets folder + + Full file path + + + + Returns the given string stripped of any invalid filename characters. + BEWARE: doesn't check for reserved words + + string to replace + Character to use as replacement for invalid ones + + + + Returns the given path with all slashes converted to the correct ones used by the system + + + + + Returns the asset path of the given GUID (relative to Unity project's folder), + or an empty string if either the GUID is invalid or the related path doesn't exist. + + + + + Checks if the given directory (full path) is empty or not + + + + + Deletes all files and subdirectories from the given directory + + + + Returns the adb path to the given ScriptableObject + + + Returns the adb path to the given MonoBehaviour + + + Returns the adb directory that contains the given ScriptableObject without final slash + + + Returns the adb directory that contains the given MonoBehaviour without final slash + + + + Returns the adb paths to the selected folders in the Project panel, or NULL if there is none. + Contrary to Selection.activeObject, which only returns folders selected in the right side of the panel, + this method also works with folders selected in the left side. + + + + + Sets the script execution order of the given MonoBehaviour + + + + + Gets the script execution order of the given MonoBehaviour + + + + + Precisely returns the last controlId assigned to a GUI element + + + + + Utils to manage UnityPackages import/export and file mirroring + + + + + Stores all file paths (excluding metas) found in the given AssetDatabase directory and subdirectory + into the given AssetDatabase file (which will be created if missing), + writing them as relative to the given directory. + EXAMPLE: + adbReadFromDirPath = "Plugins/DOTween" + file "Assets/Plugins/DOTween/aScript.cs" stored as "aScript.cs" + file "Assets/Plugins/DOTween/Subdir/aScript.cs" stored as "Subdir/aScript.cs" + + + AssetDatabase path ("Assets/...") where the list should be written + AssetDatabase path ("Assets/...") from which the list of files should be retrieved, without final slash + + + + Parses a file list created via and removes any files not present in the list from the given directory + + Label to use when logging the result + AssetDatabase path ("Assets/...") to the file containing the list + AssetDatabase path ("Assets/...") to the directory to parse for extra files to remove + If TRUE only returns a report log and doesn't actually delete the files + + + + Utilities for Editor Panels. + + + + + Connects to a asset. + If the asset already exists at the given path, loads it and returns it. + Otherwise, depending on the given parameters, either returns NULL or automatically creates it before loading and returning it. + + Asset type + File path (relative to Unity's project folder) + If TRUE and the requested asset doesn't exist, forces its creation + If TRUE also creates the path folders if they don't exist + + + + Check if the at the given path exists and eventually if it's available + + File path (relative to Unity's project folder) + If TRUE also check if the file is available + (file can be unavailable if it was deleted outside Unity, or if Unity is just starting) + + + + + Returns TRUE if the given is dockable, FALSE if instead it's a utility window + + + + + + + Sets the icon and title of an editor window. Works with older versions of Unity, where the titleContent property wasn't available. + + Reference to the editor panel whose icon to set + Icon to apply + Title. If NULL doesn't change it + + + + Repaints the currently focues editor + + + + + Prefab utilities + + + + + Behaves as the Inspector's Apply button, applying any modification of this instance to the prefab parent + + + + + + Returns TRUe if a prefab instance has unapplied modifications, ignoring any modifications applied to the transform. + NOTE: this a somehow costly operation (since it generates GC) + + + + + Completely removes any prefab connection from the given prefab instances, by desotroing the original object and recreating it. + Returns a list with all the new elements created. + + Based on RodGreen's method (http://forum.unity3d.com/threads/82883-Breaking-connection-from-gameObject-to-prefab-for-good.?p=726602&viewfull=1#post726602) + + + + + + Completely removes any prefab connection from the given prefab instance, by desotroing the original object and recreating it. + + Based on RodGreen's method (http://forum.unity3d.com/threads/82883-Breaking-connection-from-gameObject-to-prefab-for-good.?p=726602&viewfull=1#post726602) + + + + + Calls the given action after the given delay + + + + Return the size of the editor game view, eventual extra bars excluded (meaning the true size of the game area) + + + + + Returns a value from 1 to N (2 for 200% scaling) indicating the UI Scaling of Unity's editor. + The first time this is called it will store the scaling and keep it without refreshing, + since you need to restart Unity in order to apply a scaling change + + + + + Clears all logs from Unity's console + + + + + Adds the given global define (if it's not already present) to all the + or only to the given , depending on passed parameters, + and returns TRUE if it was added, FALSE otherwise. + NOTE: when adding to all of them some legacy warnings might appear, which you can ignore. + + + to use. Leave NULL to add to all of them. + + + + Removes the given global define (if present) from all the + or only from the given , depending on passed parameters, + and returns TRUE if it was removed, FALSE otherwise. + NOTE: when removing from all of them some legacy warnings might appear, which you can ignore. + + + to use. Leave NULL to remove from all of them. + + + + Returns TRUE if the given global define is present in all the + or only in the given , depending on passed parameters. + + + to use. Leave NULL to check in all of them. + + + + Sets the gizmos icon visibility in the Scene and Game view for the given class names + + Visibility + Class names (no namespace), as many as you want separated by a comma + + + + Sets the gizmos icon visibility in the Scene and Game view for all custom icons + (for example icons created with HOTools) + + Visibility + + + + Returns all components of type T in the currently open scene, or NULL if none could be found. + If you're on Unity 5 or later, and have DeEditorTools, use DeEditorToolsUtils.FindAllComponentsOfType + instead, which is more efficient. + + + + + Shifts an item from an index to another, without modifying the list except than by moving elements around + + + + + Expands the given array and adds the given element as the last one + + + + + Removes the element at index from the given array, shifts everything after by -1 position and resizes the array + + + + Nothing is being dragged + + + Dragging + + + Dragging concluced and accepted + + + Dragging concluced but item position didn't change + + + Dragging canceled + + + Dragging concluced but not accepted because too short + + + Automatically determines if dragged elements are horizontal, vertical, or both + + + Forces vertical drag + + + Forces horizontal drag (useful to avoid initial wrong drag indicators + if the users starts dragging an horizontal system vertically) + + + + Manages the dragging of GUI elements + + + + + True if a GUI element is currently being dragged + + + + + Return the current item being dragged, or NULL if there is none + + + + + Type of current item being dragged, or NULL if there is none + + + + + Starting index of current item being dragged, or NULL if there is none + + + + + Retrieves the eventual optional data stored via the StartDrag method + + + + + Starts a drag operation on a GUI element. + + Reference to the current editor drawing the GUI (used when a Repaint is needed) + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Optional data that can be retrieved via the static property + + + + Starts a drag operation on a GUI element. + + ID for this drag operation (must be the same for both StartDrag and Drag + Reference to the current editor drawing the GUI (used when a Repaint is needed) + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Optional data that can be retrieved via the static property + + + + Starts a drag operation on a GUI element. + + Reference to the current editor drawing the GUI (used when a Repaint is needed) + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Optional data that can be retrieved via the static property + + + + Starts a drag operation on a GUI element. + + ID for this drag operation (must be the same for both StartDrag and Drag + Reference to the current editor drawing the GUI (used when a Repaint is needed) + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Optional data that can be retrieved via the static property + + + + Call this after each draggable GUI block, to calculate and draw the current drag state + (or complete it if the mouse was released). + + ID for this drag operation (must be the same for both StartDrag and Drag + List containing the draggable item and all other relative draggable items + Current index of the draggable item being drawn + If NULL will calculate this automatically using . + Pass this if you're creating a drag between elements that don't use GUILayout + Drag direction. You can leave it to + unless you want to skip eventual layout calculations + + + + Call this after each draggable GUI block, to calculate and draw the current drag state + (or complete it if the mouse was released). + + List containing the draggable item and all other relative draggable items + Current index of the draggable item being drawn + If NULL will calculate this automatically using . + Pass this if you're creating a drag between elements that don't use GUILayout + Drag direction. You can leave it to + unless you want to skip eventual layout calculations + + + + Call this after each draggable GUI block, to calculate and draw the current drag state + (or complete it if the mouse was released). + + ID for this drag operation (must be the same for both StartDrag and Drag + List containing the draggable item and all other relative draggable items + Current index of the draggable item being drawn + Color to use for drag divider and selection + If NULL will calculate this automatically using . + Pass this if you're creating a drag between elements that don't use GUILayout + Drag direction. You can leave it to + unless you want to skip eventual layout calculations + + + + Call this after each draggable GUI block, to calculate and draw the current drag state + (or complete it if the mouse was released). + + List containing the draggable item and all other relative draggable items + Current index of the draggable item being drawn + Color to use for drag divider and selection + If NULL will calculate this automatically using . + Pass this if you're creating a drag between elements that don't use GUILayout + Drag direction. You can leave it to + unless you want to skip eventual layout calculations + + + + Ends the drag operations, and eventually applies the drag outcome. + Returns TRUE if the position of the dragged item actually changed. + Called automatically by Drag method. Use it only if you want to force the end of a drag operation. + + If TRUE applies the drag results, otherwise simply cancels the drag + + + + Abstract dynamic class used for every node of the same type + (meaning there is only a single recycled instance for all same-type nodes) + + + + Used to fill + + + Called when the node needs to be drawn + + + + The connectedNodesIds list will be automatically increased/decreased when adding/removing connections + (otherwise connectedNodesIds will have to be increased via custom code) + + + + + Requires only two connectedNodesIds (no more, no less), + uses regular CTRL+Drag to connect connection 0, CTRL+SPACE+Drag to connect connection 1 + + + + + Like , but with an extra connection as a last extra index, which is set when pressing CTRL+SPACE+Drag. + Must always have at least one element in connectedNodesIds + + + + Layout, Repaint, LayoutAndRepaint + + + + Stores cloned nodes for pasting + + + + + Returns a list of pasteable nodes, with their GUID recreated and their connections adapted + + + + + + Returns a deep clone of the given node but doesn't clone UnityEngine references. + A new ID will be automatically generated. + + + + + Always connects a node from BottomOrRight side to TopOrLeft side + + + + + Always connects from BottomOrRight side to TopOrLeft side. + If ALT is pressed shows the delete connection button. + Called during Repaint or MouseDown/Up. + Returns TRUE if the connection was deleted using the delete connection button. + + + + + Always connects a node from BottomOrRight side to TopOrLeft side + + + + + Always connects from BottomOrRight side to TopOrLeft side. + If ALT is pressed shows the delete connection button. + Called during Repaint or MouseDown/Up. + Returns TRUE if the connection was deleted using the delete connection button. + + + + + You can attach to this + + + + + Use this to add a content group to the Help Panel + + + + Regular note + + + Editable note (activated by setting to TRUE + (but you will have to save the result somewhere yourself) + + + If TRUE shows the textArea + + + + Add definition. Supports rich-text but also these special tags: + - [b][/b] + + + + + Add key, automatically formatting these special keys: + / + + + → + + If TRUE and there's other keys/targets, adds the new key on a new line preceded by a comma + + + + Recalculates all rects based on the given Y shift + + + + + One per . + Partially independent, mainly controlled by process. + + + + TRUE when read-to or dragging nodes + + + Returns TRUE if the given node is currently being dragged + + + + Returns TRUE if a repaint is required + + + + + + Main class for DeGUI Node system. + Create it, then enclose your GUI node calls inside a . + CODING ORDER: + - Create a to use for your node system (create it once, obviously) + - Inside OnGUI, write all your nodes GUI code inside a + - To draw the nodes, loop through the list and call for each node + + + + Distance at which nodes will be placed when snapping next to each other + + + Full area without zeroed coordinates + + + Position with zeroed coordinates (used by all node GUI since it's inside a GUILayout(area)) + + + Contains the nodes passed to NodeProcessScope ordered by depth. + You should loop through this list when drawing nodes + + + + Creates a new NodeProcess. + + EditorWindow for this process + Callback called when one or more nodes are going to be deleted. + Return FALSE if you want the deletion to be canceled. + Can be NULL, in which case it will be ignored + Callback called when a node is cloned. + Return FALSE if you want the cloning to be canceled. + Can be NULL, in which case it will be ignored + + + + Needs to be called when loading a complete new series of nodes + + + + + Call this when the layout/size of one or more nodes changed because of external intervention + (if a whole new range of nodes has been loaded, just call instead) + + + + + Forces the refresh of the area calculations. Useful if you need them before the first GUI call has run + + + + + Shifts the visible are to the given coordinates and repaints on end + + + + + Shifts the visible are to the given coordinates and repaints on end + + + + + Tells the process to repaint once the process has ended. + Calling this + + + + + Draws the given node using the given T editor GUINode type. + Returns the full area of the node + + + + + Opens the Help Panel + + + + + Closes the Help Panel + + + + + Opens or closes the Help panel based on its current state + + + + + Returns TRUE if the given area is visible (even if partially) inside the current nodeProcess area + + + + + Captures a screenshot of the node editor area and returns it when calling the onComplete method. + Sadly this requires a callback because if called immediately the capture will fail + with a "[d3d11] attempting to ReadPixels outside of RenderTexture bounds!" error in most cases + + Screenshot mode + A callback that accepts the generated Texture2D object + Screenshot scale factor (only used if screenshotMode is set to ) + If TRUE (default) displays a progress bar during the operation. + You'll want to set this to FALSE when you're already using a custom progressBar + and the screenshot is only part of a larger queue of operations + + + + Use this to encapsulate node GUI operations. + Automatically manages various operations (press F1 to see them). + Sets GUI.changed to TRUE if the area is panned, a node is dragged, controlNodes change sorting or are deleted. + Wraps all content inside a GUILayout Area (nodeArea). + + The to use + Area within which the nodes will be drawn + Area shift (caused by dragging) + This list will be sorted based on current node draw order, + and changed in case one of its nodes is deleted. + IMPORTANT: this list should be part of your serialized class (MonoBehaviour or ScriptableObject), + so it will be stored as a reference and modifying one will modify the other. + Usually you want to pass all nodes to this except the eventual start node (or nodes that can't be sorted nor deleted). + + + + Set automatically when a selection ends up selecting a single node, + reset when deselecting all nodes, selecting multiple nodes, or resetting the + + + + + Returns TRUE if something was actually deselected, FALSE if there were no selected nodes + + + + + + Returns key modifiers currently pressed. + Requires to be updated at the beginning of every GUI call. + + + + + Call this method to update data required by softCtrl calculations. + Automatically called from within a . + Returns a object with the keys that were just pressed and just released + + Required to have the correct for the given target call + + + + Returns the given as an int, or -1 if it's not a number + + + + + Used code from Celtc on StackOverflow: https://stackoverflow.com/a/54044197/10151925 + + + + + Gets all fields from an object and its hierarchy inheritance + + + + + Perform a deep copy of the class + + + + + Does the copy + + + + + Returns by . + Contains properties and methods to manage non-layout scrollview better. + Remember to use or to increase or set the full content height + + + + Area used by ScrollView and its content + + + Full content area regardless if visible or not. Its height should be set manually based on the contents' height + + + Content area currently visible (scroll bars excluded) + + + Current scrollPosition + + + + Returns the current open, or an empty one if none is open. + + + + + Sets the height + + + + + + Increase the height by the given amount + + + + + + Returns a Rect for a single line at the current scrollView yMax + + If less than 0 uses default line height, otherwise the value passed + if TRUE (default) automatically increases the height of the accordingly + + + + + Returns TRUE if the given rect is at least partially visible in the displayed scroll area + + + + + Contains both free and pro skins GUIStyle variations, + and automatically returns the correct one when converted to GUIStyle + + + + + Plays the given clip in the Editor + + + + + Stops playing the given clip. + + + + + Stops all clips playing. + + + + + A stopwatch whose time can be changed manually via + + + + + Start or resume playing + + + + + Stop the watch and reset the time + + + + + Restart measuring from zero + + + + + Pause the watch + + + + + Send the watch to the given time + + + + + Util to determine Unity editor version and store them as comparable numbers + + + + Full major version + first minor version (ex: 2018.1f) + + + Major version + + + First minor version (ex: in 2018.1 it would be 1) + + + + Assembly extensions + + + + + Full path to the assembly directory, without final slash + + + + + AssetDatabase path to the assembly directory, without final slash + + + + + GUI extension methods + + + + + Clones the style and adds the given formats to it. You can pass any of these types of values: + + Format:Rich-text, wordwrap + FontStyle:Font style + TextAnchor:Content anchor + int:Font size + Color/DeSkinColor:Font color + + + + + + Adds the given formats to the style. You can pass any of these types of values: + + Format:RichText, WordWrap + FontStyle:Font style + TextAnchor:Content anchor + int:Font size + Color/DeSkinColor:Font color + + + + + + Sets the border of the style + + + + + Sets the border of the style + + + + + Sets the background of the style + + + + + Sets the background of the style + + + + + Sets the contentOffset of the style + + + + + Sets the contentOffset of the style + + + + + Sets the X contentOffset of the style + + + + + Sets the Y contentOffset of the style + + + + + Sets the margin of the style + + + + + Sets the margin of the style + + + + + Sets the margin of the style + + + + + Sets the left margin of the style + + + + + Sets the right margin of the style + + + + + Sets the top margin of the style + + + + + Sets the bottom margin of the style + + + + + Sets the overflow of the style + + + + + Sets the overflow of the style + + + + + Sets the overflow of the style + + + + + Sets the left overflow of the style + + + + + Sets the right overflow of the style + + + + + Sets the top overflow of the style + + + + + Sets the bottom overflow of the style + + + + + Sets the padding of the style + + + + + Sets the padding of the style + + + + + Sets the padding of the style + + + + + Sets the left padding of the style + + + + + Sets the right padding of the style + + + + + Sets the top padding of the style + + + + + Sets the bottom padding of the style + + + + + Sets the Y fixedWidth of the style + + + + + Sets the fixedHeight of the style + + + + + Sets the stretchHeight property of the style + + + + + Sets the stretchWidth property of the style + + + + + Stores a GUIStyle palette, which can be passed to default DeGUI layouts when calling DeGUI.BeginGUI, + and changed at any time by calling DeGUI.ChangePalette. + You can inherit from this class to create custom GUIStyle palettes with more options. + Each of the sub-options require a public Init method to initialize the styles, which will be called via Reflection. + + + + + Called automatically by DeGUI.BeginGUI. + Override when adding new style subclasses. + Returns TRUE if the styles were initialized or re-initialized + + + + + Extend any custom subpalettes from this, so they will be initialized correctly + + + + + GUILayout methods + + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you set a background to the button's GUIStyle). + Requires to be activated. + + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you set a background to the button's GUIStyle) + and also assigns different GUI colors based on the button's state and the given one. + Requires to be activated. + + Content + Default color + Style + GUILayout options + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you set a background to the button's GUIStyle) + and also assigns different GUI colors based on the button's state with options to eventually auto-generate them. + Requires to be activated. + + Content + Default color + Hover color (if NULL auto-generates it from the given one by making it brighter + Pressed color (if NULL auto-generates it from the given one by making it even brighter + Style + GUILayout options + + + Shaded button + + + Shaded button + + + Shaded button + + + Shaded button + + + Colored button + + + Colored button + + + Colored button + + + Colored button + + + + Draws a button that returns TRUE the first time it's pressed, instead than when its released. + + + + + Draws a button that returns TRUE the first time it's pressed, instead than when its released. + + + + Toolbar foldout button + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Begins an horizontal toolbar layout + + + Begins an horizontal toolbar layout + + + Begins an horizontal toolbar layout + + + Begins an horizontal toolbar layout + + + Ends an horizontal toolbar layout + + + A toolbar with a label + + + A toolbar with a label + + + A toolbar with a label + + + A toolbar with a label + + + A toolbar with a label + + + A toolbar with a label + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values. Auto-determines object type from the field's type + + + Returns TRUE if there's mixed values. Forces field to accept only objects of the given type + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Vertical box layout with style and color options + + + Vertical box layout with style and color options + + + End vertical box layout + + + Horizontal Divider + + + + A text field that becomes editable only on double-click + + EditorWindow reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + + A text field that becomes editable only on double-click + + Editor reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + + A text field that becomes editable only on double-click and can also be dragged + + EditorWindow reference + A unique ID to use in order to determine if the text is selected or not + Text + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Style for default (non-editing mode) appearance + Style for editing mode + + + + + A text field that becomes editable only on double-click and can also be dragged + + Editor reference + A unique ID to use in order to determine if the text is selected or not + Text + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Style for default (non-editing mode) appearance + Style for editing mode + + + + + Creates a Gradient field by using Unity 4.x hidden default one and Reflection. + + + + Scene field + + + + Global Demigiant GUI manager. Call to initialize it inside GUI calls. + + + + + Default color palette + + + + + Default style palette + + + + TRUE if we're using the PRO skin + + + + Call this at the beginning of GUI methods. + Returns TRUE if the styles were initialized or re-initialized + + Eventual to use + Eventual to use + + + + Better implementation of GUI.BeginScrollView. + Returns the modified scrollView struct. + Must be closed by a DeGUI.. + + Area used by the scrollView + target + If TRUE (default) resets .height to 0 + after beginning the ScrollView + + + + Closes a DeGUI. correctly + + + + + Exits the current event correctly, also taking care of eventual drag operations + + + + + Changes the active palettes to the given ones + (or resets them to the default ones if NULL). + Returns TRUE if the styles were initialized or re-initialized + + + + + Resets the GUI colors to the default ones (only available if BeginGUI was called first) + + + + + Sets the GUI colors to the given ones + + + + + Opens a panel that previews the given texture (if not NULL) + + + + + Sets the GUI cursor color to the given ones + + + + + Sets the GUI matrix to the given ones + + + + + Wrapper to set serialized fields with multiple sources selected: automatically sets GUI to show mixed values when necessary + and contains a fieldInfo which is set within the wrapper. + Note that you must set the property within the wrapper so that it's assigned correctly when closing the scope. + + + + Multi property scope + Name of the field so it can be found and set/get via Reflection + List of the sources containing the given field + If TRUE validates EditorGUI.EndChangeCheck before calling it + (fixes an issue which happens with advanced Undo usage in DOTween Timeline and ColorFields) + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you apply a background to the button's GUIStyle). + Requires to be activated. + + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you apply a background to the button's GUIStyle) + and also assigns different GUI colors based on the button's state and the given one. + Requires to be activated. + + Rect + Content + Default color + Style + + + + A button that triggers an immediate repaint when hovered/pressed/unhovered + (which otherwise doesn't happen if you apply a background to the button's GUIStyle) + and also assigns different GUI colors based on the button's state with options to eventually auto-generate them. + Requires to be activated. + + Rect + Content + Default color + Hover color (if NULL auto-generates it from the given one by making it brighter + Pressed color (if NULL auto-generates it from the given one by making it even brighter + Style + + + Shaded button + + + Shaded button + + + Shaded button + + + Shaded button + + + Colored button + + + Colored button + + + Colored button + + + Colored button + + + Toolbar foldout button which allows clicking even on its label + + + Foldout button + label (not intended to be used in toolbar) which allows click-to-foldout/foldin + + + + Draws a button that returns TRUE the first time it's pressed, instead than when its released. + + + + + Draws a button that returns TRUE the first time it's pressed, instead than when its released. + + + + Toolbar foldout button + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Button that can be toggled on and off + + + Scene field + + + + Draws a background grid using the given grid texture + + Area rect + Offset from 0, 0 position (used when area has been dragged) + Texture to use for the grid + Eventual scale to apply to the grid + + + + Draws a background grid using default grid textures + + Area rect + Offset from 0, 0 position (used when area has been dragged) + If TRUE forces a dark skin, otherwise uses a skin that fits with the current Unity's one + Eventual scale to apply to the grid + + + Box with style and color options + + + + Can be used instead of EditorGUI.PropertyField, to draw a serializedProperty without its attributes + (very useful in case you want to use this from within a PropertyDrawer for that same property, + since otherwise bad infinite loops might happen) + + + + Draws a colored square + + + Draws the given texture tiled within the given rect + Rect + Texture + Eventual scale to apply + If not NULL, colorizes the texture with this color + + + + A text field that becomes editable only on double-click + + Area + EditorWindow reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + + A text field that becomes editable only on double-click + + Area + Editor reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + + A text field that becomes editable only on double-click and can also be dragged + + Area + EditorWindow reference + A unique ID to use in order to determine if the text is selected or not + Text + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Style for default (non-editing mode) appearance + Style for editing mode + + + + A text field that becomes editable only on double-click and can also be dragged + + Area + Editor reference + A unique ID to use in order to determine if the text is selected or not + Text + List containing the dragged item and all other relative draggable items + DraggableList index of the item being dragged + Style for default (non-editing mode) appearance + Style for editing mode + + + + A textArea that becomes editable only on double-click + + Area + EditorWindow reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + + A textArea that becomes editable only on double-click + + Area + Editor reference + A unique ID to use in order to determine if the text is selected or not + Text + Style for default (non-editing mode) appearance + Style for editing mode + + + Divider + + + Draws a Vector3Field that can have single axes disabled + + + Draws a Vector3Field that can have single axes disabled + + + Draws a Vector3Field that can have single axes disabled + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values. Supports using an int as an enum + + + Returns TRUE if there's mixed values. Supports using an int as an enum + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values. Supports also uint fields + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values. Auto-determines object type from the field's type + + + Returns TRUE if there's mixed values. Forces field to accept only objects of the given type + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values. Supports passing int values as bool (1 = true, 0 = false) + + + Returns TRUE if there's mixed values. Supports passing int values as bool (1 = true, 0 = false) + + + Returns TRUE if there's mixed values. Supports passing int values as bool (1 = true, 0 = false) + + + Returns TRUE if there's mixed values. Requires a SerializedProperty representation of each UnityEven field + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + Returns TRUE if there's mixed values + + + + Returns a new color equal to the given one with changed brightness + + Color to evaluate + Brightness factor (multiplied by current brightness) + If set applies this alpha value + + + + Returns a new color equal to the given one with changed saturation + + Color to evaluate + Saturation factor (multiplied by current brightness) + If set applies this alpha value + + + + Changes the alpha of this color and returns it + + + + + Returns a new color equal to the given one with changed alpha + + + + + Returns a HEX version of the given Unity Color, without the initial # + + If TRUE, also converts the alpha value and returns a hex of 8 characters, + otherwise doesn't and returns a hex of 6 characters + + + + Returns a HEX version of the given Unity Color, without the initial # + + If TRUE, also converts the alpha value and returns a hex of 8 characters, + otherwise doesn't and returns a hex of 6 characters + + + + Replicates parts of DeExtensions.ListExtensions for internal usage + + + + + Shifts an item from an index to another, without modifying the list except than by moving elements around + + + + + Shuffles the list + + + + + Replicates DeExtensions.RectExtensions for internal usage + + + + + Adds one rect into another, and returns the resulting a + + + + + Returns a copy or the Rect expanded around its center by the given amount + + Indicates how much to expand the rect on each size + + + + Returns a copy or the Rect expanded around its center by the given amount + + Indicates how much to expand the rect on each horizontal side + Indicates how much to expand the rect on each vertical side + + + + Returns a copy or the Rect contracted around its center by the given amount + + Indicates how much to contract the rect on each size + + + + Returns a copy or the Rect contracted around its center by the given amount + + Indicates how much to contract the rect on each horizontal side + Indicates how much to contract the rect on each vertical side + + + + Returns a copy of the Rect resized so it fits proportionally within the given size limits + + Width to fit + Height to fit + If TRUE (default) only shrinks the rect if needed, if FALSE also enlarges it to fit + + + + + Returns TRUE if the first rect includes the second one + + If TRUE, returns TRUE only if the second rect is fully included, + otherwise just if some part of it is included + + + + Returns a copy of the Rect with its X/Y coordinates set to 0 + + + + + Returns a copy of the Rect with its values shifted according the the given parameters + + + + + Returns a copy of the Rect with its X value shifted by the given value + + + + + Returns a copy of the Rect with its Y value shifted by the given value + + + + + Returns a copy of the Rect with its x shifted by the given value and its width shrinked/expanded accordingly + (so that the xMax value will stay the same as before) + + + + + Returns a copy of the Rect with its y shifted by the given value and its height shrinked/expanded accordingly + (so that the yMax value will stay the same as before) + + + + + Returns a copy of the Rect with its X property set to the given value + + + + + Returns a copy of the Rect with its Y property set to the given value + + + + + Returns a copy of the Rect with its height property set to the given value + + + + + Returns a copy of the Rect with its width property set to the given value + + + + + Returns a copy of the Rect with its X,Y properties set so the rect center corresponds to the given values + + + + + Returns a copy of the Rect with its X property set so the rect X center corresponds to the given value + + + + + Returns a copy of the Rect with its Y property set so the rect Y center corresponds to the given value + + + + + Returns the value of the given property (works like a cast to type). + + Improved from HiddenMonk's functions (http://answers.unity3d.com/questions/627090/convert-serializedproperty-to-custom-class.html) + + + + + + Returns TRUE if this property is inside an array + + + + + Returns -1 if the property is not inside an array, otherwise returns its index inside the array + + + + + Returns the height of a UnityEvent serializedProperty + + + + + Uses code from FlaShG's GitMerge: https://github.com/FlaShG/GitMerge-for-Unity/blob/master/Editor/SerializedPropertyExtensions.cs + + + + + Uses code from FlaShG's GitMerge: https://github.com/FlaShG/GitMerge-for-Unity/blob/master/Editor/SerializedPropertyExtensions.cs + + + + + String extensions + + + + + Returns TRUE if the string is null or empty + + If TRUE (default) and the string contains only spaces, considers it empty + + + + Compares a version string (in format #.#.###) with another of the same format, + and return TRUE if this one is minor. Boths trings must have the same number of dot separators. + + + + + Converts a HEX color to a Unity Color and returns it + + The HEX color, either with or without the initial # (accepts both regular and short format) + + + + Nicifies a string, replacing underscores with spaces, and adding a space before Uppercase letters (except the first character) + + + + + If the given string is a directory path, returns its parent + with or without final slash depending on the original directory format + + + + + If the string is a directory, returns the directory name, + if instead it's a file returns its name without extension. + Works better than Path.GetDirectoryName, which kind of sucks imho + + + + + Evaluates the string as a property or field and returns its value. + + If NULL considers the string as a static property, otherwise uses obj as the starting instance + + + + Texture extensions + + + + + Returns the full Rect of this texture, with options for position and scale + + + + + Checks that the texture uses the correct import settings, and applies them if they're incorrect. + + + + + Returns a clone of the event + + + + diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml.meta new file mode 100644 index 0000000..d199425 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/DemiEditor.xml.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: d4a42b2e4e6f64d4ba01d35c5a3dafed +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs.meta new file mode 100644 index 0000000..24b1340 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 1efb03f507a60b949a70ed828ac18eb8 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png new file mode 100644 index 0000000..6fbcc51 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png.meta new file mode 100644 index 0000000..ca9400a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 7ba4b2810f605d945af87e032ca2957b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png new file mode 100644 index 0000000..21afc7b Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png.meta new file mode 100644 index 0000000..488d14c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha10.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8c9cfa1dbe00a1d41ae9d14f5ac543ec +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png new file mode 100644 index 0000000..3097db8 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png.meta new file mode 100644 index 0000000..e907551 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha15.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 53d696c01f6ca524383f11fcc34dd13c +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png new file mode 100644 index 0000000..521e6dc Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png.meta new file mode 100644 index 0000000..2d94303 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha25.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: f7ff421f40d548444864a01cd7f47112 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png new file mode 100644 index 0000000..700b9de Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png.meta new file mode 100644 index 0000000..e3040e1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha50.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: aa1d42dc6ff3e894da2208c6929d2165 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png new file mode 100644 index 0000000..f4a47c3 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png.meta new file mode 100644 index 0000000..ce709e4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blackSquareAlpha80.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 595b166389c8db546a199430284ebc9b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png new file mode 100644 index 0000000..9d8a19a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png.meta new file mode 100644 index 0000000..490a921 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/blueSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 05cfe010378336646ad6c721f66543d1 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png new file mode 100644 index 0000000..3ed059a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png.meta new file mode 100644 index 0000000..bc2ac36 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/circle.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: af28470bd0e2e9543a6dfa9a1a4b348d +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png new file mode 100644 index 0000000..63ef49a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png.meta new file mode 100644 index 0000000..774d702 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/greenSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 789ef07ba2573f6448fa8b5dc5224c44 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png new file mode 100644 index 0000000..5c2feae Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png.meta new file mode 100644 index 0000000..ccb4643 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_bright.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 93b1287b4a087f84c95c72f49ec94e83 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png new file mode 100644 index 0000000..5dc9a72 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png.meta new file mode 100644 index 0000000..9baf726 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/grid_dark.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d542f997a51000946873268e3546b6ba +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png new file mode 100644 index 0000000..9242a22 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png.meta new file mode 100644 index 0000000..f84830d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alert.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 39cacc93c6c183f44992bf2421362f78 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png new file mode 100644 index 0000000..c06e167 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png.meta new file mode 100644 index 0000000..dff6533 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignB.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8b6b31f71cd528243b053cfc488e73f5 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png new file mode 100644 index 0000000..3118ab1 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png.meta new file mode 100644 index 0000000..b623d58 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBC.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 2cdc0bc527f7a434496c6be9236e636f +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png new file mode 100644 index 0000000..3ee1a48 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png.meta new file mode 100644 index 0000000..fd7ccf1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBL.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: abf8a615f379ef44b9ac872a13b7712f +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png new file mode 100644 index 0000000..ce4cf47 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png.meta new file mode 100644 index 0000000..c3dd648 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignBR.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: eeac3acbf7d1cd54fabfb1c4a12f9fc8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png new file mode 100644 index 0000000..c5f85cc Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png.meta new file mode 100644 index 0000000..75090ea --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCC.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8f0cb66458819764b94b93250bae94b6 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png new file mode 100644 index 0000000..39e1546 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png.meta new file mode 100644 index 0000000..b0e188a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCL.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 2a8208d8e80f90944b8ff2978292b03b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png new file mode 100644 index 0000000..9ec5557 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png.meta new file mode 100644 index 0000000..6223c1c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignCR.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 6f504a3fa8848264bb4fb9bb7d582dd5 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png new file mode 100644 index 0000000..dc638a7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png.meta new file mode 100644 index 0000000..7f4d729 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignHC.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: b9e0e5a8836018e4c810fbceba55a1b4 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png new file mode 100644 index 0000000..93c1812 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png.meta new file mode 100644 index 0000000..c7e801b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignL.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d18ceface0c20014b8db4bba05a41b83 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png new file mode 100644 index 0000000..c1aca04 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png.meta new file mode 100644 index 0000000..884fe5f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignR.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 727ba41e4cc95fe4a98b07301e3ebfc8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png new file mode 100644 index 0000000..b4397c6 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png.meta new file mode 100644 index 0000000..30bc025 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignT.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: b4785ec6d937dab4fa59da70b69afc9d +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png new file mode 100644 index 0000000..de6a933 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png.meta new file mode 100644 index 0000000..0d20edc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTC.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 0f79253104349f44cb73978f6c8e93de +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png new file mode 100644 index 0000000..627b907 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png.meta new file mode 100644 index 0000000..cf3e9ab --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTL.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 6efe1c8569d975640ba0c9f2ac4a9d61 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png new file mode 100644 index 0000000..6a0d89d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png.meta new file mode 100644 index 0000000..bb1b90d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignTR.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e01c0b07c87513844ab88bb432bcf85a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png new file mode 100644 index 0000000..ec87ccf Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png.meta new file mode 100644 index 0000000..52134bf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_alignVC.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d1d45eadab0e41c4a82cdffb6396b1d7 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png new file mode 100644 index 0000000..f146516 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png.meta new file mode 100644 index 0000000..e362a81 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 37639be6148186645bca3fce45d5aa22 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png new file mode 100644 index 0000000..bab977d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png.meta new file mode 100644 index 0000000..234280c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_camera_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 358cddede8023574191e0aae610a4645 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png new file mode 100644 index 0000000..b7f481e Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png.meta new file mode 100644 index 0000000..2a9bf06 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 7c83a08052c9e2f49b47897a637994de +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png new file mode 100644 index 0000000..30bdb8b Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png.meta new file mode 100644 index 0000000..d9323e2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_cog_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 6862027f2176eae40a3143c562466a1b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png new file mode 100644 index 0000000..8735b7c Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png.meta new file mode 100644 index 0000000..1e64e47 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 622fdb780ae13e840938631c5ed708f2 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png new file mode 100644 index 0000000..d61a35d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png.meta new file mode 100644 index 0000000..2f10151 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_comment_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d98b8847646169c4fb5af28dd84c4179 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png new file mode 100644 index 0000000..85bb248 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png.meta new file mode 100644 index 0000000..31ad788 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_delete.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 6b1f9e1e1c2cf004b8e3bdd3033a8e75 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png new file mode 100644 index 0000000..3445065 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png.meta new file mode 100644 index 0000000..6bac83d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_demigiant.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 229d0d11465a822449f78a50dbf7104d +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png new file mode 100644 index 0000000..90dc9de Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png.meta new file mode 100644 index 0000000..d5af1eb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeHAlignT.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 1ccb12a4b0bf8f447b2cc114851732f5 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png new file mode 100644 index 0000000..a762110 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png.meta new file mode 100644 index 0000000..50dfd23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_distributeVAlignL.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 32eaa0efb2b38774ea9705b40fdcc00a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png new file mode 100644 index 0000000..b71eefe Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png.meta new file mode 100644 index 0000000..3580f68 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_end.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: a248c8288afb9184f953d9aa07a696b0 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png new file mode 100644 index 0000000..f4525da Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png.meta new file mode 100644 index 0000000..0708f25 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_flipV.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: c44ae4a96937e2c4b8be481648364682 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png new file mode 100644 index 0000000..df26539 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png.meta new file mode 100644 index 0000000..fab01a6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_closed.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 301c130dbb4bbba4e87072804939c861 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png new file mode 100644 index 0000000..50a913a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png.meta new file mode 100644 index 0000000..cc34f91 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_foldout_open.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 18a5a7cde794cc04b9b446f0feedb3a0 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png new file mode 100644 index 0000000..7ea0c06 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png.meta new file mode 100644 index 0000000..072d281 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d173388c1d9c32a418b5b777dd89d71a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png new file mode 100644 index 0000000..a533084 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png.meta new file mode 100644 index 0000000..f7b7f22 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_heart_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 669c487f3c9c5fe4abb6459f9c2628f0 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png new file mode 100644 index 0000000..5a60bd0 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png.meta new file mode 100644 index 0000000..849e0ad --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4f69b96f9308d8f4ea239773ef5b55c4 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png new file mode 100644 index 0000000..a29a859 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png.meta new file mode 100644 index 0000000..bd76a57 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_light_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 252f207d01ecc87419cdba1d1c0ab1ea +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png new file mode 100644 index 0000000..7b718a2 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png.meta new file mode 100644 index 0000000..b7bc6d4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e3d0592dad579e141924133869455c53 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png new file mode 100644 index 0000000..be85443 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png.meta new file mode 100644 index 0000000..a870de6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_lock_open.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8d60feae84bdb2d4eb16a0037056c588 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png new file mode 100644 index 0000000..e236c92 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png.meta new file mode 100644 index 0000000..aabc040 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_nodeArrow.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4aa34055b1d36ef479af3d7b5701b28a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png new file mode 100644 index 0000000..b4d864a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png.meta new file mode 100644 index 0000000..029aabf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ok.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 34f39b5a760ddbb4d8b8749852868335 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png new file mode 100644 index 0000000..1d89e2a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png.meta new file mode 100644 index 0000000..560af25 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_optionsDropdown.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 62a48d93e78c63b4ea9b46537c7c0091 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png new file mode 100644 index 0000000..0608dcb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png.meta new file mode 100644 index 0000000..483c5b7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 2a563a43c33f0f3428d02b3a43886fc2 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png new file mode 100644 index 0000000..db4ac28 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png.meta new file mode 100644 index 0000000..e57aa67 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_play_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 45e128e1cf00555479ee7934ab11cadf +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png new file mode 100644 index 0000000..7e53975 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png.meta new file mode 100644 index 0000000..8d4e226 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 01976ad42d31f494e8040d3e32e283dc +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png new file mode 100644 index 0000000..6cc1c5f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png.meta new file mode 100644 index 0000000..ae28986 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_skull_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 6dfd924c0ba23844fb5d04ad1560de22 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png new file mode 100644 index 0000000..d280684 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png.meta new file mode 100644 index 0000000..59f2768 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 645aafe2260b2884a9df05b4bc01b1ec +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png new file mode 100644 index 0000000..4615829 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png.meta new file mode 100644 index 0000000..955bf42 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_star_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 18f3a26aa87fccc4cb5e211d4c6de662 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png new file mode 100644 index 0000000..afdcff3 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png.meta new file mode 100644 index 0000000..0d3bf2e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: cb46e1d925af22d43a6f8bf0e1d459e6 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png new file mode 100644 index 0000000..6613a3d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png.meta new file mode 100644 index 0000000..2ee6aab --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_ui_border.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: c0c40ceac3c6df146a0fcd4e6b226540 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png new file mode 100644 index 0000000..56a1324 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png.meta new file mode 100644 index 0000000..8dced06 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 55c2b426022dac44f9b25f0cba28aa45 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png new file mode 100644 index 0000000..e1a2c91 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png.meta new file mode 100644 index 0000000..a0db454 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/ico_visibility_off.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 0c0132429106c8a4d89d9d0a6b723ec3 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png new file mode 100644 index 0000000..c272180 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png.meta new file mode 100644 index 0000000..012525b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/orangeSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 3e730492361eb6e45be5c5fdafac23be +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project.meta new file mode 100644 index 0000000..8ddc4ff --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 52bdbb53205da074d9937b996806e2e2 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png new file mode 100644 index 0000000..80dc387 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png.meta new file mode 100644 index 0000000..eddd2e8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_atlas.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e2279677842a8064fbae0bc889fb85ab +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png new file mode 100644 index 0000000..90c5212 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png.meta new file mode 100644 index 0000000..30cc40c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_audio.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e1af8927fb6f5634896d59aed409a589 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png new file mode 100644 index 0000000..c418038 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png.meta new file mode 100644 index 0000000..66ef715 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_bundle.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 58676a985ae875646b7be748cf4499fd +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png new file mode 100644 index 0000000..fd589a0 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png.meta new file mode 100644 index 0000000..fa51749 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cog.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: fb605a2688b31194887f2e7a6769235b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png new file mode 100644 index 0000000..a34a3e8 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png.meta new file mode 100644 index 0000000..529d85c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_cross.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 3b67e53c8c2f8114b966c0e70d452419 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png new file mode 100644 index 0000000..99d0cf9 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png.meta new file mode 100644 index 0000000..8276473 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_demigiant.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: f36ab42cc6fcdfd4187033279d3d14a9 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png new file mode 100644 index 0000000..9bba7d0 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png.meta new file mode 100644 index 0000000..e0a5072 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_folder.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4f2c4b43188596b47866d41e1dc13c8a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png new file mode 100644 index 0000000..9ce1a4d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png.meta new file mode 100644 index 0000000..996c26e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_fonts.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: cf986943c88c2254780c17b2b5e3bc2f +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png new file mode 100644 index 0000000..f7ebe72 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png.meta new file mode 100644 index 0000000..ead0de6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_heart.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 20794834c0a413f408b80110d0fc73b8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png new file mode 100644 index 0000000..5a4b7eb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png.meta new file mode 100644 index 0000000..8e57f77 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_materials.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e02713e10d7aced44a7a651231f0adef +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png new file mode 100644 index 0000000..42f1f23 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png.meta new file mode 100644 index 0000000..0195fcf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_models.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 09a0cde07b4d75f49b4c817932791b81 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png new file mode 100644 index 0000000..3ffa475 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png.meta new file mode 100644 index 0000000..560f0dd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_particles.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8003873ab749935489bb11f23f830856 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png new file mode 100644 index 0000000..c441add Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png.meta new file mode 100644 index 0000000..2bef6e5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_play.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d8306b1e159c72c4ebc9a4fc31debe60 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png new file mode 100644 index 0000000..abc4353 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png.meta new file mode 100644 index 0000000..47f7775 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_prefab.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: ed3789262161efa4fa33c85ca534590e +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png new file mode 100644 index 0000000..c79b668 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png.meta new file mode 100644 index 0000000..2b2bbf9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_scripts.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 96cbdf605b8ddb34da384703f2d0b849 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png new file mode 100644 index 0000000..ed3b4bb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png.meta new file mode 100644 index 0000000..1d860ee --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_shaders.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: f252c69cd0163714eba038403f61b09e +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png new file mode 100644 index 0000000..22930f4 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png.meta new file mode 100644 index 0000000..68df579 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_skull.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d563d6ce25cd2ca48b185ec47a74a3fb +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png new file mode 100644 index 0000000..90483b3 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png.meta new file mode 100644 index 0000000..f872413 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_star.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 21820ec6fc9dd0b4fbf42a3b93fdad4e +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png new file mode 100644 index 0000000..750996d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png.meta new file mode 100644 index 0000000..946cabd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_terrains.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4a091a7609ef2d34bbdfaa1a886deb18 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png new file mode 100644 index 0000000..6aae964 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png.meta new file mode 100644 index 0000000..c18d4ea --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/project/ico_textures.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 3e6b96a975eba1c43b2bad66fb7f8b4a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png new file mode 100644 index 0000000..dd219ac Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png.meta new file mode 100644 index 0000000..96df50f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/purpleSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: dc0ca9b32ae9fd049911671cf1a480bf +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png new file mode 100644 index 0000000..798457f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png.meta new file mode 100644 index 0000000..299f17b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/redSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: fbdd7ecf39c13bf48a5bd02a1159c90b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png new file mode 100644 index 0000000..51afe67 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png.meta new file mode 100644 index 0000000..50cd914 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorder.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: afd7d0ddb1d6c744b9cb87ae49b2ce62 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png new file mode 100644 index 0000000..7000d8f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png.meta new file mode 100644 index 0000000..0488aae --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderAlpha15.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: dfd33662d9f6f3849bd92f6e159ca226 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png new file mode 100644 index 0000000..768cc82 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png.meta new file mode 100644 index 0000000..32d19bd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4896b5aa9d63dec498136c21ffce735b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png new file mode 100644 index 0000000..a1ed49d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png.meta new file mode 100644 index 0000000..180331a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: ff88be84254fb1f4b9a81a27ae0b2e81 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png new file mode 100644 index 0000000..2b313e4 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png.meta new file mode 100644 index 0000000..dd83662 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved02_darkBorders.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: e3ae01f12865ad54ba365963bda55759 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png new file mode 100644 index 0000000..e56d3b7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png.meta new file mode 100644 index 0000000..44abb4e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedAlpha.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: a1606d34a052ed3449da93edd229743e +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png new file mode 100644 index 0000000..bbd3158 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png.meta new file mode 100644 index 0000000..a156e1a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4578222ee7a511446b0c340551bf8740 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png new file mode 100644 index 0000000..57714a5 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png.meta new file mode 100644 index 0000000..72910c0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmpty02.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 7d504312fad10f040b95bd8836dc6fc6 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png new file mode 100644 index 0000000..47b177f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png.meta new file mode 100644 index 0000000..e9a6d7d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurvedEmptyThick.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: fc3b86627d5fe1c4d865b80627e2e37c +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png new file mode 100644 index 0000000..b9450f2 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png.meta new file mode 100644 index 0000000..db7c113 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBorders.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 25da15ac84743244ab4c860cf8798ec8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png new file mode 100644 index 0000000..4ddd37a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png.meta new file mode 100644 index 0000000..a248e7c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderCurved_darkBordersAlpha.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: f536c51d3da3f2e4ca93ac8773ec2ad8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png new file mode 100644 index 0000000..188ed94 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png.meta new file mode 100644 index 0000000..365f54f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 8db54efcce998554c86b796b37a7cdfa +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png new file mode 100644 index 0000000..188ed94 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png.meta new file mode 100644 index 0000000..c86a60d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty01.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: aa8dc9238ab21e54ca88fa22698e4679 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png new file mode 100644 index 0000000..ec9ead7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png.meta new file mode 100644 index 0000000..b2dcd93 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty02.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 29b0e8156f6fb774faf129c83bc9ee33 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png new file mode 100644 index 0000000..ca376a8 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png.meta new file mode 100644 index 0000000..e9f14fb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderEmpty03.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: c0a56b88a1b449045b3fe5f561aa12fa +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png new file mode 100644 index 0000000..ec9ead7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png.meta new file mode 100644 index 0000000..89331d1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickEmpty.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: c456d5ac01d2aa843a63985497b04931 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png new file mode 100644 index 0000000..ca376a8 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png.meta new file mode 100644 index 0000000..7365c26 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareBorderThickerEmpty.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 7acc6bd588627b046bc1c9b3cd78a6c7 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png new file mode 100644 index 0000000..38dc1bb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png.meta new file mode 100644 index 0000000..17c7922 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCorners03.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: dec3ea647707588408ec0d11ab130b73 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png new file mode 100644 index 0000000..facdba9 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png.meta new file mode 100644 index 0000000..7f51fb8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/squareCornersEmpty02.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: ca2f91cc405eb144dad970eb23db2f72 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png new file mode 100644 index 0000000..8e17561 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png.meta new file mode 100644 index 0000000..890be39 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_empty.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: d1278357b25e10442b6ca6c24edc9781 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png new file mode 100644 index 0000000..c8cfc7f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png.meta new file mode 100644 index 0000000..7edd20d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: c99a391f381fe534c80a193fe9f307a0 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png new file mode 100644 index 0000000..7763091 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png.meta new file mode 100644 index 0000000..b26261d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/tileBars_slanted_alpha.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 018a5623a46db1d49b1e6ff2482b07ab +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png new file mode 100644 index 0000000..c745068 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png.meta new file mode 100644 index 0000000..cdc61f9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/transparentSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 4d338c631fa36f345b72a36f1c91ff9a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png new file mode 100644 index 0000000..768a2da Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png.meta new file mode 100644 index 0000000..afcc984 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: ed7cb8f9a27664e48896c904189f0e2c +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png new file mode 100644 index 0000000..705c72b Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png.meta new file mode 100644 index 0000000..2758634 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_darkBorder.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 27df4ca974a8eaf40803907859421506 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png new file mode 100644 index 0000000..2a081f6 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png.meta new file mode 100644 index 0000000..8bfeba8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteDot_whiteBorderAlpha.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 039dc89c76661c344b7776f8a47cc5a4 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png new file mode 100644 index 0000000..afc2459 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png.meta new file mode 100644 index 0000000..2a4aa36 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: dfe6e0ac3e5f24740a17e14b65e08406 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png new file mode 100644 index 0000000..6480ee2 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png.meta new file mode 100644 index 0000000..1134262 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha10.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 93b68213089b05943a651574eb7e2fb5 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png new file mode 100644 index 0000000..e6f3c42 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png.meta new file mode 100644 index 0000000..8dfc149 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha15.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 5510cdd48a6aaaa439c95ef5b2fe9e28 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png new file mode 100644 index 0000000..5219f2a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png.meta new file mode 100644 index 0000000..cdfa23e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha25.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 511f6b24c50557a40a09633b12b8b8ef +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 32 + textureSettings: + filterMode: 0 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 100 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png new file mode 100644 index 0000000..ad90433 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png.meta new file mode 100644 index 0000000..103bbf1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha50.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: ef40b00a83f7bd34f84851386b3321f0 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png new file mode 100644 index 0000000..def9ea9 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png.meta new file mode 100644 index 0000000..4dd7287 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquareAlpha80.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 11848dd30e516d846a02cd302634d317 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png new file mode 100644 index 0000000..0f754e5 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png.meta new file mode 100644 index 0000000..27a1460 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/whiteSquare_fadeOut_bt.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: a40dc0d6372a9084fb45976308087290 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png new file mode 100644 index 0000000..c41f635 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png differ diff --git a/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png.meta b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png.meta new file mode 100644 index 0000000..54af05b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/DemiLib/Core/Editor/Imgs/yellowSquare.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 517a5bfe18f2ee04d9925db10be034e2 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt b/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt new file mode 100644 index 0000000..9837c95 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt @@ -0,0 +1,35 @@ +DOTween and DOTween Pro are copyright (c) 2014-2018 Daniele Giardini - Demigiant + +// IMPORTANT!!! ///////////////////////////////////////////// +// Upgrading DOTween from versions older than 1.2.000 /////// +// (or DOTween Pro older than 1.0.000) ////////////////////// +------------------------------------------------------------- +If you're upgrading your project from a version of DOTween older than 1.2.000 (or DOTween Pro older than 1.0.000) please follow these instructions carefully. +1) Import the new version in the same folder as the previous one, overwriting old files. A lot of errors will appear but don't worry +2) Close and reopen Unity (and your project). This is fundamental: skipping this step will cause a bloodbath +3) Open DOTween's Utility Panel (Tools > Demigiant > DOTween Utility Panel) if it doesn't open automatically, then press "Setup DOTween...": this will run the upgrade setup +4) From the Add/Remove Modules panel that opens, activate/deactivate Modules for Unity systems and for external assets (like TextMesh Pro) + +// GET STARTED ////////////////////////////////////////////// + +- After importing a new DOTween update, select DOTween's Utility Panel from the "Tools/Demigiant" menu (if it doesn't open automatically) and press the "Setup DOTween..." button to activate/deactivate Modules. You can also access a Preferences Tab from there to choose default settings for DOTween. + +// VISUAL SCRIPTING (PRO ONLY) +- To animate a gameObject, select it and choose "Add Component > DOTween > DOTween Animation" +- To animate a gameObject along a path, select it and choose "Add Component > DOTween > DOTween Path" + +// SCRIPTING +- In your code, add "using DG.Tweening" to each class where you want to use DOTween. +- You're ready to tween. Check out the links below for full documentation and license info. + + +// LINKS /////////////////////////////////////////////////////// + +DOTween website (documentation, examples, etc): http://dotween.demigiant.com +DOTween license: http://dotween.demigiant.com/license.php +DOTween repository (Google Code): https://code.google.com/p/dotween/ +Demigiant website (documentation, examples, etc): http://www.demigiant.com + +// NOTES ////////////////////////////////////////////////////// + +- DOTween's Utility Panel can be found under "Tools > Demigiant > DOTween Utility Panel" and also contains other useful options, plus a tab to set DOTween's preferences \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt.meta b/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt.meta new file mode 100644 index 0000000..ef7a8e9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/readme_DOTweenPro.txt.meta @@ -0,0 +1,19 @@ +fileFormatVersion: 2 +guid: 24123b2fcdc15c943bed44e0c6beeec7 +labels: +- Tween +- Tweening +- Animation +- HOTween +- Paths +- VisualScripting +- VisualEditor +- iTween +- LeanTween +- DFTween +- Ease +- Easing +- Shake +- Punch +TextScriptImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Demigiant/ver@1.0.244.txt b/Assets/CrazyZoo/Plugins/Demigiant/ver@1.0.244.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/Demigiant/ver@1.0.244.txt.meta b/Assets/CrazyZoo/Plugins/Demigiant/ver@1.0.244.txt.meta new file mode 100644 index 0000000..f80b5cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Demigiant/ver@1.0.244.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3351746bb63e2fa4186919ec938e65f5 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI.meta b/Assets/CrazyZoo/Plugins/FairyGUI.meta new file mode 100644 index 0000000..6524cf4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7865ce1321d59974aaf546aac994e850 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts.meta new file mode 100644 index 0000000..83e589f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 18909c5f8494a7f45937618ed5a4fbd0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core.meta new file mode 100644 index 0000000..3de1bef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eed3a919a48726c46a61e180a615ef7d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs new file mode 100644 index 0000000..388ef4b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs @@ -0,0 +1,110 @@ +using UnityEngine; +using NativeBlendMode = UnityEngine.Rendering.BlendMode; + +namespace FairyGUI +{ + /*关于BlendMode.Off, 这种模式相当于Blend Off指令的效果。当然,在着色器里使用Blend Off指令可以获得更高的效率, + 但因为Image着色器本身就有多个关键字,复制一个这样的着色器代价太大,所有为了节省Shader数量便增加了这样一种模式,也是可以接受的。 + */ + + /// + /// + /// + public enum BlendMode + { + Normal, + None, + Add, + Multiply, + Screen, + Erase, + Mask, + Below, + Off, + One_OneMinusSrcAlpha, + Custom1, + Custom2, + Custom3 + } + + /// + /// + /// + public class BlendModeUtils + { + public class BlendFactor + { + public NativeBlendMode srcFactor; + public NativeBlendMode dstFactor; + public bool pma; + + public BlendFactor(NativeBlendMode srcFactor, NativeBlendMode dstFactor, bool pma = false) + { + this.srcFactor = srcFactor; + this.dstFactor = dstFactor; + this.pma = pma; + } + } + + //Source指的是被计算的颜色,Destination是已经在屏幕上的颜色。 + //混合结果=Source * factor1 + Destination * factor2 + public static BlendFactor[] Factors = new BlendFactor[] { + //Normal + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //None + new BlendFactor(NativeBlendMode.One, NativeBlendMode.One), + //Add + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.One), + //Multiply + new BlendFactor(NativeBlendMode.DstColor, NativeBlendMode.OneMinusSrcAlpha, true), + //Screen + new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcColor, true), + //Erase + new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.OneMinusSrcAlpha), + //Mask + new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.SrcAlpha), + //Below + new BlendFactor(NativeBlendMode.OneMinusDstAlpha, NativeBlendMode.DstAlpha), + //Off + new BlendFactor(NativeBlendMode.One, NativeBlendMode.Zero), + //One_OneMinusSrcAlpha + new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcAlpha), + //Custom1 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //Custom2 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //Custom3 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha) + }; + + /// + /// + /// + /// + /// + public static void Apply(Material mat, BlendMode blendMode) + { + BlendFactor bf = Factors[(int)blendMode]; + mat.SetFloat(ShaderConfig.ID_BlendSrcFactor, (float)bf.srcFactor); + mat.SetFloat(ShaderConfig.ID_BlendDstFactor, (float)bf.dstFactor); + + if (bf.pma) + mat.SetFloat(ShaderConfig.ID_ColorOption, 1); + else + mat.SetFloat(ShaderConfig.ID_ColorOption, 0); + } + + /// + /// + /// + /// + /// + /// + public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor) + { + BlendFactor bf = Factors[(int)blendMode]; + bf.srcFactor = srcFactor; + bf.dstFactor = dstFactor; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs.meta new file mode 100644 index 0000000..8db746f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/BlendMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce4df113fe8d9994c83e22680544ccdb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs new file mode 100644 index 0000000..4727889 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs @@ -0,0 +1,202 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class CaptureCamera : MonoBehaviour + { + /// + /// + /// + [System.NonSerialized] + public Transform cachedTransform; + /// + /// + /// + [System.NonSerialized] + public Camera cachedCamera; + + [System.NonSerialized] + static CaptureCamera _main; + + [System.NonSerialized] + static int _layer = -1; + static int _hiddenLayer = -1; + + public const string Name = "Capture Camera"; + public const string LayerName = "VUI"; + public const string HiddenLayerName = "Hidden VUI"; + + void OnEnable() + { + cachedCamera = this.GetComponent(); + cachedTransform = this.gameObject.transform; + + if (this.gameObject.name == Name) + _main = this; + } + + /// + /// + /// + public static void CheckMain() + { + if (_main != null && _main.cachedCamera != null) + return; + + GameObject go = GameObject.Find(Name); + if (go != null) + { + _main = go.GetComponent(); + return; + } + + GameObject cameraObject = new GameObject(Name); + Camera camera = cameraObject.AddComponent(); + camera.depth = 0; + camera.cullingMask = 1 << layer; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.clear; + camera.orthographic = true; + camera.orthographicSize = 5; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + camera.enabled = false; +#if UNITY_5_4_OR_NEWER + camera.stereoTargetEye = StereoTargetEyeMask.None; +#endif + +#if UNITY_5_6_OR_NEWER + camera.allowHDR = false; + camera.allowMSAA = false; +#endif + cameraObject.AddComponent(); + } + + /// + /// + /// + public static int layer + { + get + { + if (_layer == -1) + { + _layer = LayerMask.NameToLayer(LayerName); + if (_layer == -1) + { + _layer = 30; + Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); + } + } + + return _layer; + } + } + + /// + /// + /// + public static int hiddenLayer + { + get + { + if (_hiddenLayer == -1) + { + _hiddenLayer = LayerMask.NameToLayer(HiddenLayerName); + if (_hiddenLayer == -1) + { + Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); + _hiddenLayer = 31; + } + } + + return _hiddenLayer; + } + } + + /// + /// + /// + /// + /// + /// + /// + public static RenderTexture CreateRenderTexture(int width, int height, bool stencilSupport) + { + RenderTexture texture = new RenderTexture(width, height, stencilSupport ? 24 : 0, RenderTextureFormat.ARGB32); + texture.antiAliasing = 1; + texture.filterMode = FilterMode.Bilinear; + texture.anisoLevel = 0; + texture.useMipMap = false; + texture.wrapMode = TextureWrapMode.Clamp; + texture.hideFlags = DisplayObject.hideFlags; + return texture; + } + + /// + /// + /// + /// + /// + /// + /// + public static void Capture(DisplayObject target, RenderTexture texture, float contentHeight, Vector2 offset) + { + CheckMain(); + + Matrix4x4 matrix = target.cachedTransform.localToWorldMatrix; + float scaleX = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude; + float scaleY = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude; + + Vector3 forward; + forward.x = matrix.m02; + forward.y = matrix.m12; + forward.z = matrix.m22; + + Vector3 upwards; + upwards.x = matrix.m01; + upwards.y = matrix.m11; + upwards.z = matrix.m21; + + float halfHeight = contentHeight * 0.5f; + + Camera camera = _main.cachedCamera; + camera.targetTexture = texture; + float aspect = (float)texture.width / texture.height; + camera.aspect = aspect * scaleX / scaleY; + camera.orthographicSize = halfHeight * scaleY; + _main.cachedTransform.localPosition = target.cachedTransform.TransformPoint(halfHeight * aspect - offset.x, -halfHeight + offset.y, 0); + if (forward != Vector3.zero) + _main.cachedTransform.localRotation = Quaternion.LookRotation(forward, upwards); + + int oldLayer = 0; + + if (target.graphics != null) + { + oldLayer = target.graphics.gameObject.layer; + target.graphics.gameObject.layer = CaptureCamera.layer; + } + + if (target is Container) + { + oldLayer = ((Container)target).numChildren > 0 ? ((Container)target).GetChildAt(0).layer : CaptureCamera.hiddenLayer; + ((Container)target).SetChildrenLayer(CaptureCamera.layer); + } + + RenderTexture old = RenderTexture.active; + RenderTexture.active = texture; + GL.Clear(true, true, Color.clear); + camera.Render(); + RenderTexture.active = old; + + if (target.graphics != null) + target.graphics.gameObject.layer = oldLayer; + + if (target is Container) + ((Container)target).SetChildrenLayer(oldLayer); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs.meta new file mode 100644 index 0000000..50a6b4c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/CaptureCamera.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d207151359c99fb448f4b3380bf41b0f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs new file mode 100644 index 0000000..6ef5a6d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs @@ -0,0 +1,1124 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Container : DisplayObject + { + /// + /// + /// + public RenderMode renderMode; + + /// + /// + /// + public Camera renderCamera; + + /// + /// + /// + public bool opaque; + + /// + /// + /// + public Vector4? clipSoftness; + + /// + /// + /// + public IHitTest hitArea; + + /// + /// + /// + public bool touchChildren; + + /// + /// + /// + public event Action onUpdate; + + /// + /// + /// + public bool reversedMask; + + List _children; + DisplayObject _mask; + Rect? _clipRect; + List _descendants; + + internal int _panelOrder; + internal DisplayObject _lastFocus; + + /// + /// + /// + public Container() + : base() + { + CreateGameObject("Container"); + Init(); + } + + /// + /// + /// + /// + public Container(string gameObjectName) + : base() + { + CreateGameObject(gameObjectName); + Init(); + } + + /// + /// + /// + /// + public Container(GameObject attachTarget) + : base() + { + SetGameObject(attachTarget); + Init(); + } + + void Init() + { + _children = new List(); + touchChildren = true; + } + + /// + /// + /// + public int numChildren + { + get { return _children.Count; } + } + + /// + /// + /// + /// + /// + public DisplayObject AddChild(DisplayObject child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// + /// + /// + /// + /// + public DisplayObject AddChildAt(DisplayObject child, int index) + { + int count = _children.Count; + if (index >= 0 && index <= count) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + child.RemoveFromParent(); + if (index == count) + _children.Add(child); + else + _children.Insert(index, child); + child.InternalSetParent(this); + + if (stage != null) + { + if (child is Container) + child.BroadcastEvent("onAddedToStage", null); + else + child.DispatchEvent("onAddedToStage", null); + } + + InvalidateBatchingState(true); + } + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public bool Contains(DisplayObject child) + { + return _children.Contains(child); + } + + /// + /// + /// + /// + /// + public DisplayObject GetChildAt(int index) + { + return _children[index]; + } + + /// + /// + /// + /// + /// + public DisplayObject GetChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].name == name) + return _children[i]; + } + + return null; + } + + /// + /// + /// + /// + public DisplayObject[] GetChildren() + { + return _children.ToArray(); + } + + /// + /// + /// + /// + /// + public int GetChildIndex(DisplayObject child) + { + return _children.IndexOf(child); + } + + /// + /// + /// + /// + /// + public DisplayObject RemoveChild(DisplayObject child) + { + return RemoveChild(child, false); + } + + /// + /// + /// + /// + /// + /// + public DisplayObject RemoveChild(DisplayObject child, bool dispose) + { + if (child.parent != this) + throw new Exception("obj is not a child"); + + int i = _children.IndexOf(child); + if (i >= 0) + return RemoveChildAt(i, dispose); + else + return null; + } + + /// + /// + /// + /// + /// + public DisplayObject RemoveChildAt(int index) + { + return RemoveChildAt(index, false); + } + + /// + /// + /// + /// + /// + /// + public DisplayObject RemoveChildAt(int index, bool dispose) + { + if (index >= 0 && index < _children.Count) + { + DisplayObject child = _children[index]; + + if (stage != null && (child._flags & Flags.Disposed) == 0) + { + if (child is Container) + { + child.BroadcastEvent("onRemovedFromStage", null); + if (child == Stage.inst.focus || ((Container)child).IsAncestorOf(Stage.inst.focus)) + Stage.inst._OnFocusRemoving(this); + } + else + { + child.DispatchEvent("onRemovedFromStage", null); + if (child == Stage.inst.focus) + Stage.inst._OnFocusRemoving(this); + } + } + _children.Remove(child); + InvalidateBatchingState(true); + if (!dispose) + child.InternalSetParent(null); + else + child.Dispose(); + + return child; + } + else + throw new Exception("Invalid child index"); + } + + /// + /// + /// + public void RemoveChildren() + { + RemoveChildren(0, int.MaxValue, false); + } + + /// + /// + /// + /// + /// + /// + public void RemoveChildren(int beginIndex, int endIndex, bool dispose) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex, dispose); + } + + /// + /// + /// + /// + /// + public void SetChildIndex(DisplayObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == index) return; + if (oldIndex == -1) throw new ArgumentException("Not a child of this container"); + _children.RemoveAt(oldIndex); + if (index >= _children.Count) + _children.Add(child); + else + _children.Insert(index, child); + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + /// + public void SwapChildren(DisplayObject child1, DisplayObject child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// + /// + /// + /// + public void SwapChildrenAt(int index1, int index2) + { + DisplayObject obj1 = _children[index1]; + DisplayObject obj2 = _children[index2]; + _children[index1] = obj2; + _children[index2] = obj1; + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + /// + public void ChangeChildrenOrder(IList indice, IList objs) + { + int cnt = objs.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject obj = objs[i]; + if (obj.parent != this) + throw new Exception("Not a child of this container"); + + _children[indice[i]] = obj; + } + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + public IEnumerator GetDescendants(bool backward) + { + return new DescendantsEnumerator(this, backward); + } + + /// + /// + /// + public Rect? clipRect + { + get { return _clipRect; } + set + { + if (_clipRect != value) + { + _clipRect = value; + UpdateBatchingFlags(); + } + } + } + + /// + /// + /// + public DisplayObject mask + { + get { return _mask; } + set + { + if (_mask != value) + { + _mask = value; + UpdateBatchingFlags(); + } + } + } + + /// + /// + /// + public void CreateGraphics() + { + if (graphics == null) + { + graphics = new NGraphics(this.gameObject); + graphics.texture = NTexture.Empty; + } + } + + public override Rect GetBounds(DisplayObject targetSpace) + { + if (_clipRect != null) + return TransformRect((Rect)_clipRect, targetSpace); + + int count = _children.Count; + + Rect rect; + if (count == 0) + { + Vector2 v = TransformPoint(Vector2.zero, targetSpace); + rect = Rect.MinMaxRect(v.x, v.y, 0, 0); + } + else if (count == 1) + { + rect = _children[0].GetBounds(targetSpace); + } + else + { + float minX = float.MaxValue, maxX = float.MinValue; + float minY = float.MaxValue, maxY = float.MinValue; + + for (int i = 0; i < count; ++i) + { + rect = _children[i].GetBounds(targetSpace); + minX = minX < rect.xMin ? minX : rect.xMin; + maxX = maxX > rect.xMax ? maxX : rect.xMax; + minY = minY < rect.yMin ? minY : rect.yMin; + maxY = maxY > rect.yMax ? maxY : rect.yMax; + } + + rect = Rect.MinMaxRect(minX, minY, maxX, maxY); + } + + return rect; + } + + /// + /// + /// + /// + public Camera GetRenderCamera() + { + if (renderMode == RenderMode.ScreenSpaceOverlay) + return StageCamera.main; + else + { + Camera cam = this.renderCamera; + if (cam == null) + { + if (HitTestContext.cachedMainCamera != null) + cam = HitTestContext.cachedMainCamera; + else + { + cam = Camera.main; + if (cam == null) + cam = StageCamera.main; + } + } + return cam; + } + } + + /// + /// + /// + /// + /// + /// + /// + public DisplayObject HitTest(Vector2 stagePoint, bool forTouch) + { + if (StageCamera.main == null) + { + if (this is Stage) + return this; + else + return null; + } + + HitTestContext.screenPoint = new Vector3(stagePoint.x, Screen.height - stagePoint.y, 0); + if (Display.displays.Length > 1) + { + Vector3 p = Display.RelativeMouseAt(HitTestContext.screenPoint); + if (p != Vector3.zero) + HitTestContext.screenPoint = p; + } + HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(HitTestContext.screenPoint); + HitTestContext.direction = Vector3.back; + HitTestContext.forTouch = forTouch; + HitTestContext.camera = StageCamera.main; + + DisplayObject ret = HitTest(); + if (ret != null) + return ret; + else if (this is Stage) + return this; + else + return null; + } + + override protected DisplayObject HitTest() + { + if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) + return null; + + if (this.cachedTransform.localScale.x == 0 || this.cachedTransform.localScale.y == 0) + return null; + + Camera savedCamera = HitTestContext.camera; + Vector3 savedWorldPoint = HitTestContext.worldPoint; + Vector3 savedDirection = HitTestContext.direction; + DisplayObject target; + + if (renderMode != RenderMode.ScreenSpaceOverlay || (_flags & Flags.UserGameObject) != 0) + { + Camera cam = GetRenderCamera(); + if (cam.targetDisplay != HitTestContext.screenPoint.z) + return null; + + HitTestContext.camera = cam; + if (renderMode == RenderMode.WorldSpace) + { + Vector3 screenPoint = HitTestContext.camera.WorldToScreenPoint(this.cachedTransform.position); //only for query z value + screenPoint.x = HitTestContext.screenPoint.x; + screenPoint.y = HitTestContext.screenPoint.y; + + //获得本地z轴在世界坐标的方向 + HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(screenPoint); + Ray ray = HitTestContext.camera.ScreenPointToRay(screenPoint); + HitTestContext.direction = Vector3.zero - ray.direction; + } + else if (renderMode == RenderMode.ScreenSpaceCamera) + { + HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(HitTestContext.screenPoint); + } + } + else + { + if (HitTestContext.camera.targetDisplay != HitTestContext.screenPoint.z && !(this is Stage)) + return null; + } + + target = HitTest_Container(); + + HitTestContext.camera = savedCamera; + HitTestContext.worldPoint = savedWorldPoint; + HitTestContext.direction = savedDirection; + + return target; + } + + DisplayObject HitTest_Container() + { + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + if (_vertexMatrix != null) + HitTestContext.worldPoint = this.cachedTransform.TransformPoint(new Vector2(localPoint.x, -localPoint.y)); + + if (hitArea != null) + { + if (!hitArea.HitTest(_contentRect, localPoint)) + return null; + + if (hitArea is MeshColliderHitTest) + localPoint = ((MeshColliderHitTest)hitArea).lastHit; + } + else + { + if (_clipRect != null && !((Rect)_clipRect).Contains(localPoint)) + return null; + } + + if (_mask != null) + { + DisplayObject tmp = _mask.InternalHitTestMask(); + if (!reversedMask && tmp == null || reversedMask && tmp != null) + return null; + } + + DisplayObject target = null; + if (touchChildren) + { + int count = _children.Count; + for (int i = count - 1; i >= 0; --i) // front to back! + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child == _mask || (child._flags & Flags.TouchDisabled) != 0) + continue; + + target = child.InternalHitTest(); + if (target != null) + break; + } + } + + if (target == null && opaque && (hitArea != null || _contentRect.Contains(localPoint))) + target = this; + + return target; + } + + /// + /// + /// + /// + /// + public bool IsAncestorOf(DisplayObject obj) + { + if (obj == null) + return false; + + Container p = obj.parent; + while (p != null) + { + if (p == this) + return true; + + p = p.parent; + } + return false; + } + + /// + /// + /// + public bool fairyBatching + { + get { return (_flags & Flags.FairyBatching) != 0; } + set + { + bool oldValue = (_flags & Flags.FairyBatching) != 0; + if (oldValue != value) + { + if (value) + _flags |= Flags.FairyBatching; + else + _flags &= ~Flags.FairyBatching; + UpdateBatchingFlags(); + } + } + } + + internal void UpdateBatchingFlags() + { + bool oldValue = (_flags & Flags.BatchingRoot) != 0; + bool newValue = (_flags & Flags.FairyBatching) != 0 || _clipRect != null || _mask != null || _paintingMode > 0; + if (newValue) + _flags |= Flags.BatchingRoot; + else + _flags &= ~Flags.BatchingRoot; + if (oldValue != newValue) + { + if (newValue) + _flags |= Flags.BatchingRequested; + else if (_descendants != null) + _descendants.Clear(); + + InvalidateBatchingState(); + } + } + + /// + /// + /// + /// + public void InvalidateBatchingState(bool childrenChanged) + { + if (childrenChanged && (_flags & Flags.BatchingRoot) != 0) + _flags |= Flags.BatchingRequested; + else + { + Container p = this.parent; + while (p != null) + { + if ((p._flags & Flags.BatchingRoot) != 0) + { + p._flags |= Flags.BatchingRequested; + break; + } + + p = p.parent; + } + } + } + + /// + /// + /// + /// + public void SetChildrenLayer(int value) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + child._SetLayerDirect(value); + if ((child is Container) && child._paintingMode == 0) + ((Container)child).SetChildrenLayer(value); + } + } + + override public void Update(UpdateContext context) + { + if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) + return; + + base.Update(context); + + if (_paintingMode != 0) + { + if ((_flags & Flags.CacheAsBitmap) != 0 && _paintingInfo.flag == 2) + { + if (onUpdate != null) + onUpdate(); + return; + } + + context.EnterPaintingMode(); + } + + if (_mask != null) + { + context.EnterClipping(this.id, reversedMask); + if (_mask.graphics != null) + _mask.graphics._PreUpdateMask(context, _mask.id); + } + else if (_clipRect != null) + context.EnterClipping(this.id, this.TransformRect((Rect)_clipRect, null), clipSoftness); + + float savedAlpha = context.alpha; + context.alpha *= this.alpha; + bool savedGrayed = context.grayed; + context.grayed = context.grayed || this.grayed; + + if ((_flags & Flags.FairyBatching) != 0) + context.batchingDepth++; + + if (context.batchingDepth > 0) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child.visible) + child.Update(context); + } + } + else + { + if (_mask != null) + _mask.renderingOrder = context.renderingOrder++; + + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child.visible) + { + if (!(child.graphics != null && child.graphics._maskFlag == 1)) //if not a mask + child.renderingOrder = context.renderingOrder++; + + child.Update(context); + } + } + + if (_mask != null) + { + if (_mask.graphics != null) + _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); + } + } + + if ((_flags & Flags.FairyBatching) != 0) + { + if (context.batchingDepth == 1) + SetRenderingOrder(context); + context.batchingDepth--; + } + + context.alpha = savedAlpha; + context.grayed = savedGrayed; + + if (_clipRect != null || _mask != null) + context.LeaveClipping(); + + if (_paintingMode != 0) + { + context.LeavePaintingMode(); + UpdateContext.OnEnd += _paintingInfo.captureDelegate; + } + + if (onUpdate != null) + onUpdate(); + } + + private void SetRenderingOrder(UpdateContext context) + { + if ((_flags & Flags.BatchingRequested) != 0) + DoFairyBatching(); + + if (_mask != null) + _mask.renderingOrder = context.renderingOrder++; + + int cnt = _descendants.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _descendants[i]; + if (!(child.graphics != null && child.graphics._maskFlag == 1)) + child.renderingOrder = context.renderingOrder++; + + if ((child._flags & Flags.BatchingRoot) != 0) + ((Container)child).SetRenderingOrder(context); + } + + if (_mask != null) + { + if (_mask.graphics != null) + _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); + } + } + + private void DoFairyBatching() + { + _flags &= ~Flags.BatchingRequested; + + if (_descendants == null) + _descendants = new List(); + else + _descendants.Clear(); + CollectChildren(this, false); + + int cnt = _descendants.Count; + + int i, j, k, m; + object curMat, testMat, lastMat; + DisplayObject current, test; + float[] bound; + for (i = 0; i < cnt; i++) + { + current = _descendants[i]; + bound = current._batchingBounds; + curMat = current.material; + if (curMat == null || (current._flags & Flags.SkipBatching) != 0) + continue; + + k = -1; + lastMat = null; + m = i; + for (j = i - 1; j >= 0; j--) + { + test = _descendants[j]; + if ((test._flags & Flags.SkipBatching) != 0) + break; + + testMat = test.material; + if (testMat != null) + { + if (lastMat != testMat) + { + lastMat = testMat; + m = j + 1; + } + + if (curMat == testMat) + k = m; + } + + if ((bound[0] > test._batchingBounds[0] ? bound[0] : test._batchingBounds[0]) + <= (bound[2] < test._batchingBounds[2] ? bound[2] : test._batchingBounds[2]) + && (bound[1] > test._batchingBounds[1] ? bound[1] : test._batchingBounds[1]) + <= (bound[3] < test._batchingBounds[3] ? bound[3] : test._batchingBounds[3])) + { + if (k == -1) + k = m; + break; + } + } + if (k != -1 && i != k) + { + _descendants.RemoveAt(i); + _descendants.Insert(k, current); + } + } + + //Debug.Log("DoFairyBatching " + cnt + "," + this.cachedTransform.GetInstanceID()); + } + + private void CollectChildren(Container initiator, bool outlineChanged) + { + int count = _children.Count; + for (int i = 0; i < count; i++) + { + DisplayObject child = _children[i]; + if (!child.visible) + continue; + + if (child._batchingBounds == null) + child._batchingBounds = new float[4]; + + if (child is Container) + { + Container container = (Container)child; + if ((container._flags & Flags.BatchingRoot) != 0) + { + initiator._descendants.Add(container); + if (outlineChanged || (container._flags & Flags.OutlineChanged) != 0) + { + Rect rect = container.GetBounds(initiator); + container._batchingBounds[0] = rect.xMin; + container._batchingBounds[1] = rect.yMin; + container._batchingBounds[2] = rect.xMax; + container._batchingBounds[3] = rect.yMax; + } + if ((container._flags & Flags.BatchingRequested) != 0) + container.DoFairyBatching(); + } + else + container.CollectChildren(initiator, outlineChanged || (container._flags & Flags.OutlineChanged) != 0); + } + else if (child != initiator._mask) + { + if (outlineChanged || (child._flags & Flags.OutlineChanged) != 0) + { + Rect rect = child.GetBounds(initiator); + child._batchingBounds[0] = rect.xMin; + child._batchingBounds[1] = rect.yMin; + child._batchingBounds[2] = rect.xMax; + child._batchingBounds[3] = rect.yMax; + } + initiator._descendants.Add(child); + } + + child._flags &= ~Flags.OutlineChanged; + } + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + base.Dispose(); //Destroy GameObject tree first, avoid destroying each seperately; + + int numChildren = _children.Count; + for (int i = numChildren - 1; i >= 0; --i) + { + DisplayObject obj = _children[i]; + obj.InternalSetParent(null); //Avoid RemoveParent call + obj.Dispose(); + } + } + + /// + /// If true, when the container is focused, tab navigation is lock inside it. + /// + public bool tabStopChildren + { + get { return (_flags & Flags.TabStopChildren) != 0; } + set + { + if (value) + _flags |= Flags.TabStopChildren; + else + _flags &= ~Flags.TabStopChildren; + } + } + + struct DescendantsEnumerator : IEnumerator + { + Container _root; + Container _com; + DisplayObject _current; + int _index; + bool _forward; + + public DescendantsEnumerator(Container root, bool backward) + { + _root = root; + _com = _root; + _current = null; + _forward = !backward; + if (_forward) + _index = 0; + else + _index = _com._children.Count - 1; + } + + public DisplayObject Current + { + get { return _current; } + } + + object IEnumerator.Current + { + get { return _current; } + } + + public bool MoveNext() + { + if (_forward) + { + if (_index >= _com._children.Count) + { + if (_com == _root) + { + _current = null; + return false; + } + + _current = _com; + _com = _com.parent; + _index = _com.GetChildIndex(_current) + 1; + return true; + } + else + { + DisplayObject obj = _com._children[_index]; + if (obj is Container) + { + _com = (Container)obj; + _index = 0; + return MoveNext(); + } + _index++; + _current = obj; + return true; + } + } + else + { + if (_index < 0) + { + if (_com == _root) + { + _current = null; + return false; + } + + _current = _com; + _com = _com.parent; + _index = _com.GetChildIndex(_current) - 1; + return true; + } + else + { + DisplayObject obj = _com._children[_index]; + if (obj is Container) + { + _com = (Container)obj; + _index = _com._children.Count - 1; + return MoveNext(); + } + _index--; + _current = obj; + return true; + } + } + } + + public void Reset() + { + _com = _root; + _current = null; + _index = 0; + } + + public void Dispose() + { + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs.meta new file mode 100644 index 0000000..c71ade0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Container.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 531f2c788ec31e7459700f6811410a6f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs new file mode 100644 index 0000000..9bc4538 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs @@ -0,0 +1,1891 @@ +using System; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class DisplayObject : EventDispatcher + { + /// + /// + /// + public string name; + + /// + /// + /// + public Container parent { get; private set; } + + /// + /// + /// + public GameObject gameObject { get; protected set; } + + /// + /// + /// + public Transform cachedTransform { get; protected set; } + + /// + /// + /// + public NGraphics graphics { get; protected set; } + + /// + /// + /// + public NGraphics paintingGraphics { get; protected set; } + + /// + /// + /// + public event Action onPaint; + + /// + /// + /// + public GObject gOwner; + + /// + /// + /// + public uint id; + + bool _visible; + bool _touchable; + Vector2 _pivot; + Vector3 _pivotOffset; + Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存 + Vector2 _skew; + int _renderingOrder; + float _alpha; + bool _grayed; + BlendMode _blendMode; + IFilter _filter; + Transform _home; + string _cursor; + bool _perspective; + int _focalLength; + Vector3 _pixelPerfectAdjustment; + int _checkPixelPerfect; + + EventListener _onClick; + EventListener _onRightClick; + EventListener _onTouchBegin; + EventListener _onTouchMove; + EventListener _onTouchEnd; + EventListener _onRollOver; + EventListener _onRollOut; + EventListener _onMouseWheel; + EventListener _onAddedToStage; + EventListener _onRemovedFromStage; + EventListener _onKeyDown; + EventListener _onClickLink; + EventListener _onFocusIn; + EventListener _onFocusOut; + + protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap + protected internal PaintingInfo _paintingInfo; + protected Rect _contentRect; + protected NGraphics.VertexMatrix _vertexMatrix; + protected internal Flags _flags; + protected internal float[] _batchingBounds; + + internal static uint _gInstanceCounter; + + internal static HideFlags hideFlags = HideFlags.None; + + public DisplayObject() + { + id = _gInstanceCounter++; + + _alpha = 1; + _visible = true; + _touchable = true; + _blendMode = BlendMode.Normal; + _focalLength = 2000; + _flags |= Flags.OutlineChanged; + if (UIConfig.makePixelPerfect) + _flags |= Flags.PixelPerfect; + } + + /// + /// + /// + public EventListener onClick + { + get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } + } + + /// + /// + /// + public EventListener onRightClick + { + get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } + } + + /// + /// + /// + public EventListener onTouchBegin + { + get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } + } + + /// + /// + /// + public EventListener onTouchMove + { + get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } + } + + /// + /// + /// + public EventListener onTouchEnd + { + get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } + } + + /// + /// + /// + public EventListener onRollOver + { + get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } + } + + /// + /// + /// + public EventListener onRollOut + { + get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } + } + + /// + /// + /// + public EventListener onMouseWheel + { + get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); } + } + + /// + /// + /// + public EventListener onAddedToStage + { + get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } + } + + /// + /// + /// + public EventListener onRemovedFromStage + { + get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } + } + + /// + /// + /// + public EventListener onKeyDown + { + get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } + } + + /// + /// + /// + public EventListener onClickLink + { + get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } + } + + /// + /// + /// + public EventListener onFocusIn + { + get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } + } + + /// + /// + /// + public EventListener onFocusOut + { + get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } + } + + // [Y 修改] + private static Transform uiCacheRoot; + + // [Y 修改] + public static void CreateUICacheRoot(Transform _uiCacheRoot) + { + uiCacheRoot = _uiCacheRoot; + } + + protected void CreateGameObject(string gameObjectName) + { + gameObject = new GameObject(gameObjectName); + cachedTransform = gameObject.transform; + if (Application.isPlaying) + { + UnityEngine.Object.DontDestroyOnLoad(gameObject); + + DisplayObjectInfo info = gameObject.AddComponent(); + info.displayObject = this; + } + + gameObject.hideFlags = DisplayObject.hideFlags; + gameObject.SetActive(false); + + // [Y 修改] +#if UNITY_EDITOR + gameObject.transform.SetParent(uiCacheRoot, false); +#endif + } + + protected void SetGameObject(GameObject gameObject) + { + this.gameObject = gameObject; + this.cachedTransform = gameObject.transform; + _rotation = cachedTransform.localEulerAngles; + + _flags |= Flags.UserGameObject; + } + + protected void DestroyGameObject() + { + if ((_flags & Flags.UserGameObject) == 0 && gameObject != null) + { + if (Application.isPlaying) + GameObject.Destroy(gameObject); + else + GameObject.DestroyImmediate(gameObject); + gameObject = null; + cachedTransform = null; + } + } + + /// + /// + /// + public float alpha + { + get { return _alpha; } + set { _alpha = value; } + } + + /// + /// + /// + public bool grayed + { + get { return _grayed; } + set { _grayed = value; } + } + + /// + /// + /// + public bool visible + { + get { return _visible; } + set + { + if (_visible != value) + { + _visible = value; + _flags |= Flags.OutlineChanged; + if (parent != null && _visible) + { + gameObject.SetActive(true); + InvalidateBatchingState(); + if (this is Container) + ((Container)this).InvalidateBatchingState(true); + } + else + gameObject.SetActive(false); + } + } + } + + /// + /// + /// + public float x + { + get { return cachedTransform.localPosition.x; } + set { SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z); } + } + + /// + /// + /// + public float y + { + get { return -cachedTransform.localPosition.y; } + set { SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z); } + } + + /// + /// + /// + public float z + { + get { return cachedTransform.localPosition.z; } + set { SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value); } + } + + /// + /// + /// + public Vector2 xy + { + get { return new Vector2(this.x, this.y); } + set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); } + } + + /// + /// + /// + public Vector3 position + { + get { return new Vector3(this.x, this.y, this.z); } + set { SetPosition(value.x, value.y, value.z); } + } + + /// + /// + /// + /// + /// + public void SetXY(float xv, float yv) + { + if (cachedTransform != null) + { + SetPosition(xv, yv, cachedTransform.localPosition.z); + } + } + + /// + /// + /// + /// + /// + /// + public void SetPosition(float xv, float yv, float zv) + { + Vector3 v = new Vector3(); + v.x = xv; + v.y = -yv; + v.z = zv; + if (v != cachedTransform.localPosition) + { + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + if ((_flags & Flags.PixelPerfect) != 0) + { + //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。 + _checkPixelPerfect = Time.frameCount; + _pixelPerfectAdjustment = Vector3.zero; + } + } + } + + /// + /// If the object position is align by pixel + /// + public bool pixelPerfect + { + get { return (_flags & Flags.PixelPerfect) != 0; } + set + { + if (value) + _flags |= Flags.PixelPerfect; + else + _flags &= ~Flags.PixelPerfect; + } + } + + /// + /// + /// + public float width + { + get + { + EnsureSizeCorrect(); + return _contentRect.width; + } + set + { + if (!Mathf.Approximately(value, _contentRect.width)) + { + _contentRect.width = value; + _flags |= Flags.WidthChanged; + _flags &= ~Flags.HeightChanged; + OnSizeChanged(); + } + } + } + + /// + /// + /// + public float height + { + get + { + EnsureSizeCorrect(); + return _contentRect.height; + } + set + { + if (!Mathf.Approximately(value, _contentRect.height)) + { + _contentRect.height = value; + _flags &= ~Flags.WidthChanged; + _flags |= Flags.HeightChanged; + OnSizeChanged(); + } + } + } + + /// + /// + /// + public Vector2 size + { + get + { + EnsureSizeCorrect(); + return _contentRect.size; + } + set { SetSize(value.x, value.y); } + } + + /// + /// + /// + /// + /// + public void SetSize(float wv, float hv) + { + if (!Mathf.Approximately(wv, _contentRect.width)) + _flags |= Flags.WidthChanged; + else + _flags &= ~Flags.WidthChanged; + if (!Mathf.Approximately(hv, _contentRect.height)) + _flags |= Flags.HeightChanged; + else + _flags &= ~Flags.HeightChanged; + + if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0) + { + _contentRect.width = wv; + _contentRect.height = hv; + OnSizeChanged(); + } + } + + virtual public void EnsureSizeCorrect() + { + } + + virtual protected void OnSizeChanged() + { + ApplyPivot(); + + if (_paintingInfo != null) + _paintingInfo.flag = 1; + if (graphics != null) + graphics.contentRect = _contentRect; + _flags |= Flags.OutlineChanged; + } + + /// + /// + /// + public float scaleX + { + get { return cachedTransform.localScale.x; } + set + { + Vector3 v = cachedTransform.localScale; + v.x = v.z = ValidateScale(value); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + } + + /// + /// + /// + public float scaleY + { + get { return cachedTransform.localScale.y; } + set + { + Vector3 v = cachedTransform.localScale; + v.y = ValidateScale(value); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + } + + /// + /// + /// + /// + /// + public void SetScale(float xv, float yv) + { + // [Y 修改] + if (cachedTransform == null) return; + + Vector3 v = new Vector3(); + v.x = v.z = ValidateScale(xv); + v.y = ValidateScale(yv); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + + /// + /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。 + /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。 + /// 这里限制一下scale的最小值作为当前解决方案。 + /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。 + /// + /// + /// + private float ValidateScale(float value) + { + if (value >= 0 && value < 0.001f) + value = 0.001f; + else if (value < 0 && value > -0.001f) + value = -0.001f; + return value; + } + + /// + /// + /// + public Vector2 scale + { + get { return cachedTransform.localScale; } + set { SetScale(value.x, value.y); } + } + + /// + /// + /// + public float rotation + { + get + { + //和Unity默认的旋转方向相反 + return -_rotation.z; + } + set + { + _rotation.z = -value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public float rotationX + { + get { return _rotation.x; } + set + { + _rotation.x = value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public float rotationY + { + get { return _rotation.y; } + set + { + _rotation.y = value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public Vector2 skew + { + get { return _skew; } + set + { + _skew = value; + _flags |= Flags.OutlineChanged; + + if (!Application.isPlaying) //编辑期间不支持!! + return; + + UpdateTransformMatrix(); + } + } + + /// + /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。 + /// + public bool perspective + { + get { return _perspective; } + set + { + if (_perspective != value) + { + _perspective = value; + if (_perspective) //屏蔽Unity自身的旋转变换 + cachedTransform.localEulerAngles = Vector3.zero; + else + cachedTransform.localEulerAngles = _rotation; + + ApplyPivot(); + UpdateTransformMatrix(); + } + } + } + + /// + /// + /// + public int focalLength + { + get { return _focalLength; } + set + { + if (value <= 0) + value = 1; + + _focalLength = value; + if (_vertexMatrix != null) + UpdateTransformMatrix(); + } + } + + void UpdateTransformMatrix() + { + Matrix4x4 matrix = Matrix4x4.identity; + if (_skew.x != 0 || _skew.y != 0) + ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y); + if (_perspective) + matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one); + if (matrix.isIdentity) + _vertexMatrix = null; + else if (_vertexMatrix == null) + _vertexMatrix = new NGraphics.VertexMatrix(); + + //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。 + if (_vertexMatrix != null) + { + _vertexMatrix.matrix = matrix; + _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, + _focalLength); + + if (graphics == null) + EnterPaintingMode(4, null); + } + else + { + if (graphics == null) + LeavePaintingMode(4); + } + + if (_paintingMode > 0) + { + paintingGraphics.vertexMatrix = _vertexMatrix; + _paintingInfo.flag = 1; + } + else if (graphics != null) + graphics.vertexMatrix = _vertexMatrix; + + _flags |= Flags.OutlineChanged; + } + + /// + /// + /// + public Vector2 pivot + { + get { return _pivot; } + set + { + Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, + (_pivot.y - value.y) * _contentRect.height); + Vector3 oldOffset = _pivotOffset; + + _pivot = value; + UpdatePivotOffset(); + Vector3 v = cachedTransform.localPosition; + v += oldOffset - _pivotOffset + deltaPivot; + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + } + } + + void UpdatePivotOffset() + { + float px = _pivot.x * _contentRect.width; + float py = _pivot.y * _contentRect.height; + + //注意这里不用处理skew,因为在顶点变换里有对pivot的处理 + Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale); + _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0)); + + if (_vertexMatrix != null) + _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, + _focalLength); + } + + void ApplyPivot() + { + if (_pivot.x != 0 || _pivot.y != 0) + { + Vector3 oldOffset = _pivotOffset; + + UpdatePivotOffset(); + Vector3 v = cachedTransform.localPosition; + + if ((_flags & Flags.PixelPerfect) != 0) + { + v -= _pixelPerfectAdjustment; + _checkPixelPerfect = Time.frameCount; + _pixelPerfectAdjustment = Vector3.zero; + } + + v += oldOffset - _pivotOffset; + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + } + } + + /// + /// This is the pivot position + /// + public Vector3 location + { + get + { + Vector3 pos = this.position; + pos.x += _pivotOffset.x; + pos.y -= _pivotOffset.y; + pos.z += _pivotOffset.z; + return pos; + } + + set { this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z); } + } + + /// + /// + /// + virtual public Material material + { + get + { + if (graphics != null) + return graphics.material; + else + return null; + } + set + { + if (graphics != null) + graphics.material = value; + } + } + + /// + /// + /// + virtual public string shader + { + get + { + if (graphics != null) + return graphics.shader; + else + return null; + } + set + { + if (graphics != null) + graphics.shader = value; + } + } + + /// + /// + /// + virtual public int renderingOrder + { + get { return _renderingOrder; } + set + { + if ((_flags & Flags.GameObjectDisposed) != 0) + { + DisplayDisposedWarning(); + return; + } + + _renderingOrder = value; + if (graphics != null) + graphics.sortingOrder = value; + if (_paintingMode > 0) + paintingGraphics.sortingOrder = value; + } + } + + /// + /// + /// + public int layer + { + get + { + if (_paintingMode > 0) + return paintingGraphics.gameObject.layer; + else + return gameObject.layer; + } + set { SetLayer(value, false); } + } + + /// + /// If the object can be focused? + /// + public bool focusable + { + get { return (_flags & Flags.NotFocusable) == 0; } + set + { + if (value) + _flags &= ~Flags.NotFocusable; + else + _flags |= Flags.NotFocusable; + } + } + + /// + /// If the object can be navigated by TAB? + /// + public bool tabStop + { + get { return (_flags & Flags.TabStop) != 0; } + set + { + if (value) + _flags |= Flags.TabStop; + else + _flags &= ~Flags.TabStop; + } + } + + /// + /// If the object focused? + /// + public bool focused + { + get + { + return Stage.inst.focus == this || + (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus); + } + } + + internal bool _AcceptTab() + { + if (_touchable && _visible + && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0) + && (_flags & Flags.NotFocusable) == 0) + { + Stage.inst.SetFocus(this, true); + return true; + } + else + return false; + } + + /// + /// + /// + /// + public string cursor + { + get { return _cursor; } + set + { + _cursor = value; + if (Application.isPlaying + && (this == Stage.inst.touchTarget || + (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget))) + { + Stage.inst._ChangeCursor(_cursor); + } + } + } + + /// + /// + /// + public bool isDisposed + { + get { return (_flags & Flags.Disposed) != 0 || gameObject == null; } + } + + internal void InternalSetParent(Container value) + { + if (parent != value) + { + if (value == null && (parent._flags & Flags.Disposed) != 0) + parent = value; + else + { + parent = value; + UpdateHierarchy(); + } + + _flags |= Flags.OutlineChanged; + } + } + + /// + /// + /// + public Container topmost + { + get + { + DisplayObject currentObject = this; + while (currentObject.parent != null) + currentObject = currentObject.parent; + return currentObject as Container; + } + } + + /// + /// + /// + public Stage stage + { + get { return topmost as Stage; } + } + + /// + /// + /// + public Container worldSpaceContainer + { + get + { + Container wsc = null; + DisplayObject currentObject = this; + while (currentObject.parent != null) + { + if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace) + { + wsc = (Container)currentObject; + break; + } + + currentObject = currentObject.parent; + } + + return wsc; + } + } + + /// + /// + /// + public bool touchable + { + get { return _touchable; } + set + { + if (_touchable != value) + { + _touchable = value; + if (this is Container) + { + ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest; + if (hitArea != null) + hitArea.collider.enabled = value; + } + } + } + } + + /// + /// + /// + /// + public bool touchDisabled + { + get { return (_flags & Flags.TouchDisabled) != 0; } + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// + public void EnterPaintingMode() + { + EnterPaintingMode(16384, null, 1); + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 + /// + /// 请求者id + /// 纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 + public void EnterPaintingMode(int requestorId, Margin? extend) + { + EnterPaintingMode(requestorId, extend, 1); + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 + /// + /// 请求者id + /// 扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 + /// 附加一个缩放系数 + public void EnterPaintingMode(int requestorId, Margin? extend, float scale) + { + bool first = _paintingMode == 0; + _paintingMode |= requestorId; + if (first) + { + if (_paintingInfo == null) + { + _paintingInfo = new PaintingInfo() + { + captureDelegate = Capture, + scale = 1 + }; + } + + if (paintingGraphics == null) + { + if (graphics == null) + paintingGraphics = new NGraphics(this.gameObject); + else + { + GameObject go = new GameObject(this.gameObject.name + " (Painter)"); + go.layer = this.gameObject.layer; + go.transform.SetParent(cachedTransform, false); + go.hideFlags = DisplayObject.hideFlags; + paintingGraphics = new NGraphics(go); + } + } + else + paintingGraphics.enabled = true; + + paintingGraphics.vertexMatrix = null; + + if (this is Container) + { + ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer); + ((Container)this).UpdateBatchingFlags(); + } + else + this.InvalidateBatchingState(); + + if (graphics != null) + this.gameObject.layer = CaptureCamera.hiddenLayer; + } + + if (extend != null) + _paintingInfo.extend = (Margin)extend; + _paintingInfo.scale = scale; + _paintingInfo.flag = 1; + } + + /// + /// 离开绘画模式 + /// + /// + public void LeavePaintingMode(int requestorId) + { + if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0) + return; + + _paintingMode ^= requestorId; + if (_paintingMode == 0) + { + paintingGraphics.enabled = false; + + if (this is Container) + { + ((Container)this).SetChildrenLayer(this.layer); + ((Container)this).UpdateBatchingFlags(); + } + else + this.InvalidateBatchingState(); + + if (graphics != null) + this.gameObject.layer = paintingGraphics.gameObject.layer; + } + } + + /// + /// + /// + public bool paintingMode + { + get { return _paintingMode > 0; } + } + + /// + /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。 + /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。 + /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。 + /// + public bool cacheAsBitmap + { + get { return (_flags & Flags.CacheAsBitmap) != 0; } + set + { + if (value) + { + _flags |= Flags.CacheAsBitmap; + EnterPaintingMode(8, null, UIContentScaler.scaleFactor); + } + else + { + _flags &= ~Flags.CacheAsBitmap; + LeavePaintingMode(8); + } + } + } + + /// + /// + /// + /// + /// + /// + public Texture2D GetScreenShot(Margin? extend, float scale) + { + EnterPaintingMode(8, null, scale); + UpdatePainting(); + Capture(); + + Texture2D output; + if (paintingGraphics.texture == null) + output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true); + else + { + RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture; + output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true); + RenderTexture old = RenderTexture.active; + RenderTexture.active = rt; + output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); + output.Apply(); + RenderTexture.active = old; + } + + LeavePaintingMode(8); + + return output; + } + + /// + /// + /// + public IFilter filter + { + get { return _filter; } + + set + { + if (!Application.isPlaying) //编辑期间不支持!! + return; + + if (value == _filter) + return; + + if (_filter != null) + _filter.Dispose(); + + if (value != null && value.target != null) + value.target.filter = null; + + _filter = value; + if (_filter != null) + _filter.target = this; + } + } + + /// + /// + /// + public BlendMode blendMode + { + get { return _blendMode; } + set + { + _blendMode = value; + InvalidateBatchingState(); + + if (graphics == null) + { + if (_blendMode != BlendMode.Normal) + { + if (!Application.isPlaying) //Not supported in edit mode! + return; + + EnterPaintingMode(2, null); + paintingGraphics.blendMode = _blendMode; + } + else + LeavePaintingMode(2); + } + else + graphics.blendMode = _blendMode; + } + } + + /// + /// + /// + /// + /// + virtual public Rect GetBounds(DisplayObject targetSpace) + { + EnsureSizeCorrect(); + + if (targetSpace == this) // optimization + { + return _contentRect; + } + else if (targetSpace == parent && _rotation.z == 0) + { + return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, + _contentRect.width * cachedTransform.localScale.x, + _contentRect.height * cachedTransform.localScale.y); + } + else + return TransformRect(_contentRect, targetSpace); + } + + internal DisplayObject InternalHitTest() + { + if (_visible && (!HitTestContext.forTouch || _touchable)) + return HitTest(); + else + return null; + } + + internal DisplayObject InternalHitTestMask() + { + if (_visible) + return HitTest(); + else + return null; + } + + virtual protected DisplayObject HitTest() + { + Rect rect = GetBounds(this); + if (rect.width == 0 || rect.height == 0) + return null; + + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + if (rect.Contains(localPoint)) + return this; + else + return null; + } + + /// + /// 将舞台坐标转换为本地坐标 + /// + /// + /// + public Vector2 GlobalToLocal(Vector2 point) + { + Container wsc = this.worldSpaceContainer; + + if (wsc != null) //I am in a world space + { + Camera cam = wsc.GetRenderCamera(); + Vector3 worldPoint; + Vector3 direction; + Vector3 screenPoint = new Vector3(); + screenPoint.x = point.x; + screenPoint.y = Screen.height - point.y; + + if (wsc.hitArea is MeshColliderHitTest) + { + Ray ray = cam.ScreenPointToRay(screenPoint); + RaycastHit hit; + if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100)) + { + point = new Vector2(hit.textureCoord.x * _contentRect.width, + (1 - hit.textureCoord.y) * _contentRect.height); + worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); + direction = Vector3.back; + } + else //当射线没有击中模型时,无法确定本地坐标 + return new Vector2(float.NaN, float.NaN); + } + else + { + screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z; + worldPoint = cam.ScreenToWorldPoint(screenPoint); + Ray ray = cam.ScreenPointToRay(screenPoint); + direction = Vector3.zero - ray.direction; + } + + return this.WorldToLocal(worldPoint, direction); + } + else //I am in stage space + { + Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); + return this.WorldToLocal(worldPoint, Vector3.back); + } + } + + /// + /// 将本地坐标转换为舞台坐标 + /// + /// + /// + public Vector2 LocalToGlobal(Vector2 point) + { + Container wsc = this.worldSpaceContainer; + + Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0); + if (wsc != null) + { + if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead. + return new Vector2(float.NaN, float.NaN); + + Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint); + return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y); + } + else + { + point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint); + point.y = -point.y; + return point; + } + } + + /// + /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。 + /// 返回的点是在对象的本地坐标空间,且z=0 + /// + /// + /// + /// + public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction) + { + Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint); + if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0, + { + //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点 + direction = this.cachedTransform.InverseTransformDirection(direction); + float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / + Vector3.Dot(direction, Vector3.forward); + if (float.IsInfinity(distOnLine)) + return Vector2.zero; + + localPoint = localPoint + direction * distOnLine; + } + else if (_vertexMatrix != null) + { + Vector3 center = _vertexMatrix.cameraPos; + center.z = 0; + center -= _vertexMatrix.matrix.MultiplyPoint(center); + + Matrix4x4 mm = _vertexMatrix.matrix.inverse; + + localPoint -= center; + localPoint = mm.MultiplyPoint(localPoint); + + Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos); + Vector3 vec = localPoint - camPos; + float lambda = -camPos.z / vec.z; + localPoint = camPos + lambda * vec; + localPoint.z = 0; + } + + localPoint.y = -localPoint.y; + + return localPoint; + } + + /// + /// + /// + /// + /// + public Vector3 LocalToWorld(Vector3 localPoint) + { + localPoint.y = -localPoint.y; + if (_vertexMatrix != null) + { + Vector3 center = _vertexMatrix.cameraPos; + center.z = 0; + center -= _vertexMatrix.matrix.MultiplyPoint(center); + + localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint); + localPoint += center; + + Vector3 camPos = _vertexMatrix.cameraPos; + Vector3 vec = localPoint - camPos; + float lambda = -camPos.z / vec.z; + localPoint = camPos + lambda * vec; + localPoint.z = 0; + } + + return this.cachedTransform.TransformPoint(localPoint); + } + + /// + /// + /// + /// + /// null if to world space + /// + public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace) + { + if (targetSpace == this) + return point; + + point = LocalToWorld(point); + if (targetSpace != null) + point = targetSpace.WorldToLocal(point, Vector3.back); + + return point; + } + + /// + /// + /// + /// + /// null if to world space + /// + public Rect TransformRect(Rect rect, DisplayObject targetSpace) + { + if (targetSpace == this) + return rect; + + if (targetSpace == parent && _rotation.z == 0) // optimization + { + Vector3 vec = cachedTransform.localScale; + return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y, + rect.width * vec.x, rect.height * vec.y); + } + else + { + Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue); + + TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4); + TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4); + TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4); + TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4); + + return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w); + } + } + + protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4) + { + Vector2 v = TransformPoint(new Vector2(px, py), targetSpace); + + if (vec4.x > v.x) vec4.x = v.x; + if (vec4.z < v.x) vec4.z = v.x; + if (vec4.y > v.y) vec4.y = v.y; + if (vec4.w < v.y) vec4.w = v.y; + } + + /// + /// + /// + public void RemoveFromParent() + { + if (parent != null) + parent.RemoveChild(this); + } + + /// + /// + /// + public void InvalidateBatchingState() + { + if (parent != null) + parent.InvalidateBatchingState(true); + } + + virtual public void Update(UpdateContext context) + { + if (_checkPixelPerfect != 0) + { + if (_rotation == Vector3.zero) + { + Vector3 v = cachedTransform.localPosition; + v.x = Mathf.Round(v.x); + v.y = Mathf.Round(v.y); + _pixelPerfectAdjustment = v - cachedTransform.localPosition; + if (_pixelPerfectAdjustment != Vector3.zero) + cachedTransform.localPosition = v; + } + + _checkPixelPerfect = 0; + } + + if (graphics != null) + graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed); + + if (_paintingMode != 0) + { + UpdatePainting(); + + //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。 + if (!(this is Container)) + { + if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2) + UpdateContext.OnEnd += _paintingInfo.captureDelegate; + } + + paintingGraphics.Update(context, 1, false); + } + + if (_filter != null) + _filter.Update(); + + Stats.ObjectCount++; + } + + void UpdatePainting() + { + NTexture paintingTexture = paintingGraphics.texture; + if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁 + { + paintingTexture = null; + _paintingInfo.flag = 1; + } + + if (_paintingInfo.flag == 1) + { + _paintingInfo.flag = 0; + + //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的 + Margin extend = _paintingInfo.extend; + paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, + _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom); + int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale); + int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale); + if (paintingTexture == null || paintingTexture.width != textureWidth || + paintingTexture.height != textureHeight) + { + if (paintingTexture != null) + paintingTexture.Dispose(); + if (textureWidth > 0 && textureHeight > 0) + { + paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, + UIConfig.depthSupportForPaintingMode)); + Stage.inst.MonitorTexture(paintingTexture); + } + else + paintingTexture = null; + + paintingGraphics.texture = paintingTexture; + } + } + + if (paintingTexture != null) + paintingTexture.lastActive = Time.time; + } + + void Capture() + { + if (paintingGraphics.texture == null) + return; + + Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top); + CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, + paintingGraphics.contentRect.height, offset); + + _paintingInfo.flag = 2; //2表示已完成一次Capture + if (onPaint != null) + onPaint(); + } + + /// + /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。 + /// + public Transform home + { + get { return _home; } + set + { + _home = value; + if (value != null && cachedTransform.parent == null) + cachedTransform.SetParent(value, false); + } + } + + void UpdateHierarchy() + { + if ((_flags & Flags.GameObjectDisposed) != 0) + return; + + if ((_flags & Flags.UserGameObject) != 0) + { + //we dont change transform parent of this object + if (gameObject != null) + { + if (parent != null && visible) + gameObject.SetActive(true); + else + gameObject.SetActive(false); + } + } + else if (parent != null) + { + cachedTransform.SetParent(parent.cachedTransform, false); + + if (_visible) + gameObject.SetActive(true); + + int layerValue = parent.gameObject.layer; + if (parent._paintingMode != 0) + layerValue = CaptureCamera.hiddenLayer; + SetLayer(layerValue, true); + } + else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit) + { + if (Application.isPlaying) + { + if (gOwner == null || gOwner.parent == null) //如果gOwner还有parent的话,说明只是暂时的隐藏 + { + // ToolSet.SetParent(cachedTransform, _home); + // if (_home == null) + // Object.DontDestroyOnLoad(this.gameObject); + + // [Y 修改] + if (_home != null) + { + ToolSet.SetParent(cachedTransform, _home); + } + else + { + cachedTransform.SetParent(uiCacheRoot, false); + } + } + } + + gameObject.SetActive(false); + } + } + + virtual protected bool SetLayer(int value, bool fromParent) + { + if ((_flags & Flags.LayerSet) != 0) //setted + { + if (fromParent) + return false; + } + else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent + { + if (!fromParent) + _flags |= Flags.LayerSet; + } + else + { + if (fromParent) + _flags |= Flags.LayerFromParent; + else + _flags |= Flags.LayerSet; + } + + if (_paintingMode > 0) + paintingGraphics.gameObject.layer = value; + else if (gameObject.layer != value) + { + gameObject.layer = value; + if ((this is Container)) + { + int cnt = ((Container)this).numChildren; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = ((Container)this).GetChildAt(i); + child.SetLayer(value, true); + } + } + } + + return true; + } + + internal void _SetLayerDirect(int value) + { + if (_paintingMode > 0) + paintingGraphics.gameObject.layer = value; + else + gameObject.layer = value; + } + + virtual public void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + _flags |= Flags.Disposed; + RemoveFromParent(); + RemoveEventListeners(); + if (graphics != null) + graphics.Dispose(); + if (_filter != null) + _filter.Dispose(); + if (paintingGraphics != null) + { + if (paintingGraphics.texture != null) + paintingGraphics.texture.Dispose(); + + paintingGraphics.Dispose(); + if (paintingGraphics.gameObject != this.gameObject) + { + if (Application.isPlaying) + UnityEngine.Object.Destroy(paintingGraphics.gameObject); + else + UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject); + } + } + + DestroyGameObject(); + } + + internal void DisplayDisposedWarning() + { + if ((_flags & Flags.DisposedWarning) == 0) + { + _flags |= Flags.DisposedWarning; + + StringBuilder sb = new StringBuilder(); + sb.Append("DisplayObject is still in use but GameObject was disposed. ("); + if (gOwner != null) + { + sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=") + .Append(gOwner.y).Append(", name=").Append(gOwner.name); + if (gOwner.packageItem != null) + sb.Append(", res=" + gOwner.packageItem.name); + } + else + { + sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=") + .Append(name); + } + + sb.Append(")"); + Debug.LogError(sb.ToString()); + } + } + + protected internal class PaintingInfo + { + public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC + public Margin extend; + public float scale; + public int flag; + } + + [Flags] + protected internal enum Flags + { + Disposed = 1, + UserGameObject = 2, + TouchDisabled = 4, + OutlineChanged = 8, + UpdatingSize = 0x10, + WidthChanged = 0x20, + HeightChanged = 0x40, + PixelPerfect = 0x80, + LayerSet = 0x100, + LayerFromParent = 0x200, + NotFocusable = 0x400, + TabStop = 0x800, + TabStopChildren = 0x1000, + FairyBatching = 0x2000, + BatchingRequested = 0x4000, + BatchingRoot = 0x8000, + SkipBatching = 0x10000, + CacheAsBitmap = 0x20000, + GameObjectDisposed = 0x40000, + DisposedWarning = 0x80000 + } + } + + /// + /// + /// + public class DisplayObjectInfo : MonoBehaviour + { + /// + /// + /// /// + [System.NonSerialized] public DisplayObject displayObject; + + private void OnDestroy() + { + if (displayObject != null) + displayObject._flags |= DisplayObject.Flags.GameObjectDisposed; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs.meta new file mode 100644 index 0000000..49368cc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/DisplayObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24d09ba8cf3faa74f8dcd1c86ad38588 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs new file mode 100644 index 0000000..6218b79 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs @@ -0,0 +1,388 @@ +using UnityEngine; +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// GoWrapper is class for wrapping common gameobject into UI display list. + /// + public class GoWrapper : DisplayObject + { + [Obsolete("No need to manually set this flag anymore, coz it will be handled automatically.")] + public bool supportStencil; + + public event Action onUpdate; + public Action> customCloneMaterials; + public Action customRecoverMaterials; + + protected GameObject _wrapTarget; + protected List _renderers; + protected Dictionary _materialsBackup; + protected Canvas _canvas; + protected bool _cloneMaterial; + protected bool _shouldCloneMaterial; + + protected struct RendererInfo + { + public Renderer renderer; + public Material[] materials; + public int sortingOrder; + } + + protected static List helperTransformList = new List(); + + /// + /// + /// + public GoWrapper() + { + // _flags |= Flags.SkipBatching; + + _renderers = new List(); + _materialsBackup = new Dictionary(); + + CreateGameObject("GoWrapper"); + } + + /// + /// + /// + /// 包装对象。 + public GoWrapper(GameObject go) : this() + { + SetWrapTarget(go, false); + } + + /// + /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 + /// 对象包含的所有材质不会被复制,如果材质已经是公用的,这可能影响到其他对象。如果希望自动复制,改为使用SetWrapTarget(target, true)设置。 + /// + public GameObject wrapTarget + { + get { return _wrapTarget; } + set { SetWrapTarget(value, false); } + } + + [Obsolete("setWrapTarget is deprecated. Use SetWrapTarget instead.")] + public void setWrapTarget(GameObject target, bool cloneMaterial) + { + SetWrapTarget(target, cloneMaterial); + } + + /// + /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 + /// + /// + /// 如果true,则复制材质,否则直接使用sharedMaterial。 + public void SetWrapTarget(GameObject target, bool cloneMaterial) + { + // set Flags.SkipBatching only target not null + if (target == null) _flags &= ~Flags.SkipBatching; + else _flags |= Flags.SkipBatching; + InvalidateBatchingState(); + + RecoverMaterials(); + + _cloneMaterial = cloneMaterial; + if (_wrapTarget != null) + _wrapTarget.transform.SetParent(null, false); + + _canvas = null; + _wrapTarget = target; + _shouldCloneMaterial = false; + _renderers.Clear(); + + if (_wrapTarget != null) + { + _wrapTarget.transform.SetParent(this.cachedTransform, false); + _canvas = _wrapTarget.GetComponent(); + if (_canvas != null) + { + _canvas.renderMode = RenderMode.WorldSpace; + _canvas.worldCamera = StageCamera.main; + _canvas.overrideSorting = true; + + RectTransform rt = _canvas.GetComponent(); + rt.pivot = new Vector2(0, 1); + rt.position = new Vector3(0, 0, 0); + this.SetSize(rt.rect.width, rt.rect.height); + } + else + { + CacheRenderers(); + this.SetSize(0, 0); + } + + SetGoLayers(this.layer); + } + } + + /// + /// GoWrapper will cache all renderers of your gameobject on constructor. + /// If your gameobject change laterly, call this function to update the cache. + /// GoWrapper会在构造函数里查询你的gameobject所有的Renderer并保存。如果你的gameobject + /// 后续发生了改变,调用这个函数通知GoWrapper重新查询和保存。 + /// + public void CacheRenderers() + { + if (_canvas != null) + return; + + RecoverMaterials(); + _renderers.Clear(); + + Renderer[] items = _wrapTarget.GetComponentsInChildren(true); + + int cnt = items.Length; + _renderers.Capacity = cnt; + for (int i = 0; i < cnt; i++) + { + Renderer r = items[i]; + Material[] mats = r.sharedMaterials; + RendererInfo ri = new RendererInfo() + { + renderer = r, + materials = mats, + sortingOrder = r.sortingOrder + }; + _renderers.Add(ri); + + if (!_cloneMaterial && mats != null + && ((r is SkinnedMeshRenderer) || (r is MeshRenderer))) + { + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + if (mat != null && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects + mat.renderQueue = 3000; + } + } + } + _renderers.Sort((RendererInfo c1, RendererInfo c2) => + { + return c1.sortingOrder - c2.sortingOrder; + }); + + _shouldCloneMaterial = _cloneMaterial; + } + + void CloneMaterials() + { + _shouldCloneMaterial = false; + + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + Material[] mats = ri.materials; + if (mats == null) + continue; + + bool shouldSetRQ = (ri.renderer is SkinnedMeshRenderer) || (ri.renderer is MeshRenderer); + + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + if (mat == null) + continue; + + //确保相同的材质不会复制两次 + Material newMat; + if (!_materialsBackup.TryGetValue(mat, out newMat)) + { + newMat = new Material(mat); + _materialsBackup[mat] = newMat; + } + mats[j] = newMat; + + if (shouldSetRQ && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects + newMat.renderQueue = 3000; + } + + if (customCloneMaterials != null) + customCloneMaterials.Invoke(_materialsBackup); + else if (ri.renderer != null) + ri.renderer.sharedMaterials = mats; + } + } + + void RecoverMaterials() + { + if (_materialsBackup.Count == 0) + return; + + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + if (ri.renderer == null) + continue; + + Material[] mats = ri.materials; + if (mats == null) + continue; + + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + + foreach (KeyValuePair kv in _materialsBackup) + { + if (kv.Value == mat) + mats[j] = kv.Key; + } + } + + if (customRecoverMaterials != null) + customRecoverMaterials.Invoke(); + else + ri.renderer.sharedMaterials = mats; + } + + foreach (KeyValuePair kv in _materialsBackup) + Material.DestroyImmediate(kv.Value); + + _materialsBackup.Clear(); + } + + public override int renderingOrder + { + get + { + return base.renderingOrder; + } + set + { + base.renderingOrder = value; + + if (_canvas != null) + _canvas.sortingOrder = value; + else + { + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + if (ri.renderer != null) + { + if (i != 0 && _renderers[i].sortingOrder != _renderers[i - 1].sortingOrder) + value = UpdateContext.current.renderingOrder++; + ri.renderer.sortingOrder = value; + } + } + } + } + } + + override protected bool SetLayer(int value, bool fromParent) + { + if (base.SetLayer(value, fromParent)) + { + SetGoLayers(value); + return true; + } + else + return false; + } + + protected void SetGoLayers(int layer) + { + if (_wrapTarget == null) + return; + + _wrapTarget.GetComponentsInChildren(true, helperTransformList); + int cnt = helperTransformList.Count; + for (int i = 0; i < cnt; i++) + helperTransformList[i].gameObject.layer = layer; + helperTransformList.Clear(); + } + + override public void Update(UpdateContext context) + { + if (onUpdate != null) + onUpdate(context); + + if (_shouldCloneMaterial) + CloneMaterials(); + + ApplyClipping(context); + + base.Update(context); + } + + private List helperMaterials = new List(); + virtual protected void ApplyClipping(UpdateContext context) + { +#if UNITY_2018_2_OR_NEWER + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + Renderer renderer = _renderers[i].renderer; + if (renderer == null) + continue; + + if (customCloneMaterials != null) + helperMaterials.AddRange(_materialsBackup.Values); + else + renderer.GetSharedMaterials(helperMaterials); + + int cnt2 = helperMaterials.Count; + for (int j = 0; j < cnt2; j++) + { + Material mat = helperMaterials[j]; + if (mat != null) + context.ApplyClippingProperties(mat, false); + } + + helperMaterials.Clear(); + } +#else + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + Material[] mats = _renderers[i].materials; + if (mats == null) + continue; + + int cnt2 = mats.Length; + for (int j = 0; j < cnt2; j++) + { + Material mat = mats[j]; + if (mat != null) + context.ApplyClippingProperties(mat, false); + } + } +#endif + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + if (_wrapTarget != null) + { + UnityEngine.Object.Destroy(_wrapTarget); + _wrapTarget = null; + + if (_materialsBackup.Count > 0) + { //如果有备份,说明材质是复制出来的,应该删除 + foreach (KeyValuePair kv in _materialsBackup) + Material.DestroyImmediate(kv.Value); + } + } + + _renderers = null; + _materialsBackup = null; + _canvas = null; + customCloneMaterials = null; + customRecoverMaterials = null; + + base.Dispose(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs.meta new file mode 100644 index 0000000..b245045 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/GoWrapper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 796d0bdebe7368c47adfdf04a1abdfc6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest.meta new file mode 100644 index 0000000..acbcc89 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 736ceb6630254bd42b41568b387cbcbe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs new file mode 100644 index 0000000..3deb4c3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs @@ -0,0 +1,33 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class ColliderHitTest : IHitTest + { + /// + /// + /// + public Collider collider; + + /// + /// + /// + /// + /// + /// + virtual public bool HitTest(Rect contentRect, Vector2 localPoint) + { + RaycastHit hit; + if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) + return false; + + if (hit.collider != collider) + return false; + + return true; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs.meta new file mode 100644 index 0000000..690f155 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ColliderHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ffed53edbd969f3439a942ca847cd43d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs new file mode 100644 index 0000000..2d5886f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class HitTestContext + { + //set before hit test + public static Vector3 screenPoint; + public static Vector3 worldPoint; + public static Vector3 direction; + public static bool forTouch; + public static Camera camera; + + public static int layerMask = -1; + public static float maxDistance = Mathf.Infinity; + + public static Camera cachedMainCamera; + + static Dictionary raycastHits = new Dictionary(); + + /// + /// + /// + /// + /// + /// + public static bool GetRaycastHitFromCache(Camera camera, out RaycastHit hit) + { + RaycastHit? hitRef; + if (!raycastHits.TryGetValue(camera, out hitRef)) + { + Ray ray = camera.ScreenPointToRay(screenPoint); + if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) + { + raycastHits[camera] = hit; + return true; + } + else + { + raycastHits[camera] = null; + return false; + } + } + else if (hitRef == null) + { + hit = new RaycastHit(); + return false; + } + else + { + hit = (RaycastHit)hitRef; + return true; + } + } + + /// + /// + /// + /// + /// + public static void CacheRaycastHit(Camera camera, ref RaycastHit hit) + { + raycastHits[camera] = hit; + } + + /// + /// + /// + public static void ClearRaycastHitCache() + { + raycastHits.Clear(); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs.meta new file mode 100644 index 0000000..29cbd24 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19869d6307205b84a81aef6031ba1f33 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs new file mode 100644 index 0000000..5725953 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs @@ -0,0 +1,27 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public enum HitTestMode + { + Default, + Raycast + } + + /// + /// + /// + public interface IHitTest + { + /// + /// + /// + /// + /// + /// + bool HitTest(Rect contentRect, Vector2 localPoint); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs.meta new file mode 100644 index 0000000..31388e7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/IHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8bbadf82645501c41957c257ab020708 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs new file mode 100644 index 0000000..d0b1090 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs @@ -0,0 +1,43 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class MeshColliderHitTest : ColliderHitTest + { + public Vector2 lastHit; + + /// + /// + /// + /// + public MeshColliderHitTest(MeshCollider collider) + { + this.collider = collider; + } + + /// + /// + /// + /// + /// + /// + override public bool HitTest(Rect contentRect, Vector2 localPoint) + { + RaycastHit hit; + if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) + return false; + + if (hit.collider != collider) + return false; + + lastHit = new Vector2(hit.textureCoord.x * contentRect.width, (1 - hit.textureCoord.y) * contentRect.height); + HitTestContext.direction = Vector3.back; + HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(new Vector2(lastHit.x, Screen.height - lastHit.y)); + + return true; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta new file mode 100644 index 0000000..f82af96 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d0a2fa0c7008814795dc7f5f3bd4b19 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs new file mode 100644 index 0000000..92aa744 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs @@ -0,0 +1,82 @@ +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PixelHitTestData + { + public int pixelWidth; + public float scale; + public byte[] pixels; + public int pixelsLength; + public int pixelsOffset; + + public void Load(ByteBuffer ba) + { + ba.ReadInt(); + pixelWidth = ba.ReadInt(); + scale = 1.0f / ba.ReadByte(); + pixels = ba.buffer; + pixelsLength = ba.ReadInt(); + pixelsOffset = ba.position; + ba.Skip(pixelsLength); + } + } + + /// + /// + /// + public class PixelHitTest : IHitTest + { + public int offsetX; + public int offsetY; + public float sourceWidth; + public float sourceHeight; + + PixelHitTestData _data; + + /// + /// + /// + /// + /// + /// + public PixelHitTest(PixelHitTestData data, int offsetX, int offsetY, float sourceWidth, float sourceHeight) + { + _data = data; + this.offsetX = offsetX; + this.offsetY = offsetY; + this.sourceWidth = sourceWidth; + this.sourceHeight = sourceHeight; + } + + /// + /// + /// + /// + /// + /// + public bool HitTest(Rect contentRect, Vector2 localPoint) + { + if (!contentRect.Contains(localPoint)) + return false; + + int x = Mathf.FloorToInt((localPoint.x * sourceWidth / contentRect.width - offsetX) * _data.scale); + int y = Mathf.FloorToInt((localPoint.y * sourceHeight / contentRect.height - offsetY) * _data.scale); + if (x < 0 || y < 0 || x >= _data.pixelWidth) + return false; + + int pos = y * _data.pixelWidth + x; + int pos2 = pos / 8; + int pos3 = pos % 8; + + if (pos2 >= 0 && pos2 < _data.pixelsLength) + return ((_data.pixels[_data.pixelsOffset + pos2] >> pos3) & 0x1) > 0; + else + return false; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs.meta new file mode 100644 index 0000000..b05a9f0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 98cb65df7f5853c4b8e3719a28d4d81f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs new file mode 100644 index 0000000..4c178df --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RectHitTest : IHitTest + { + /// + /// + /// + public Rect rect; + + /// + /// + /// + /// + /// + /// + public bool HitTest(Rect contentRect, Vector2 localPoint) + { + return rect.Contains(localPoint); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs.meta new file mode 100644 index 0000000..f9f209f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/RectHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 92768f03d9b8dea47b1649613c4d0de7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs new file mode 100644 index 0000000..08d6cf4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs @@ -0,0 +1,44 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class ShapeHitTest : IHitTest + { + /// + /// + /// + public DisplayObject shape; + + public ShapeHitTest(DisplayObject obj) + { + shape = obj; + } + + /// + /// + /// + /// + /// + /// + public bool HitTest(Rect contentRect, Vector2 localPoint) + { + if (shape.graphics == null) + return false; + + if (shape.parent != null) + { + localPoint = shape.parent.TransformPoint(localPoint, shape); + contentRect.size = shape.size; + } + + IHitTest ht = shape.graphics.meshFactory as IHitTest; + if (ht == null) + return false; + + return ht.HitTest(contentRect, localPoint); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs.meta new file mode 100644 index 0000000..614d509 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/HitTest/ShapeHitTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0cd85528f2766431cafc5282f956c060 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs new file mode 100644 index 0000000..e8282a9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs @@ -0,0 +1,436 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Image : DisplayObject, IMeshFactory + { + protected Rect? _scale9Grid; + protected bool _scaleByTile; + protected Vector2 _textureScale; + protected int _tileGridIndice; + protected FillMesh _fillMesh; + + public Image() : this(null) + { + } + + /// + /// + /// + /// + public Image(NTexture texture) + : base() + { + _flags |= Flags.TouchDisabled; + + CreateGameObject("Image"); + graphics = new NGraphics(gameObject); + graphics.shader = ShaderConfig.imageShader; + graphics.meshFactory = this; + + _textureScale = Vector2.one; + + if (texture != null) + UpdateTexture(texture); + } + + /// + /// + /// + public NTexture texture + { + get { return graphics.texture; } + set + { + UpdateTexture(value); + } + } + + public Vector2 textureScale + { + get { return _textureScale; } + set + { + _textureScale = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.Tint(); + } + } + + /// + /// + /// + public FillMethod fillMethod + { + get { return _fillMesh != null ? _fillMesh.method : FillMethod.None; } + set + { + if (_fillMesh == null) + { + if (value == FillMethod.None) + return; + + _fillMesh = new FillMesh(); + } + if (_fillMesh.method != value) + { + _fillMesh.method = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public int fillOrigin + { + get { return _fillMesh != null ? _fillMesh.origin : 0; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.origin != value) + { + _fillMesh.origin = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public bool fillClockwise + { + get { return _fillMesh != null ? _fillMesh.clockwise : true; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.clockwise != value) + { + _fillMesh.clockwise = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public float fillAmount + { + get { return _fillMesh != null ? _fillMesh.amount : 0; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.amount != value) + { + _fillMesh.amount = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Rect? scale9Grid + { + get { return _scale9Grid; } + set + { + if (_scale9Grid != value) + { + _scale9Grid = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public bool scaleByTile + { + get { return _scaleByTile; } + set + { + if (_scaleByTile != value) + { + _scaleByTile = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public int tileGridIndice + { + get { return _tileGridIndice; } + set + { + if (_tileGridIndice != value) + { + _tileGridIndice = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public void SetNativeSize() + { + if (graphics.texture != null) + SetSize(graphics.texture.width, graphics.texture.height); + else + SetSize(0, 0); + } + + virtual protected void UpdateTexture(NTexture value) + { + if (value == graphics.texture) + return; + + graphics.texture = value; + _textureScale = Vector2.one; + if (_contentRect.width == 0) + SetNativeSize(); + InvalidateBatchingState(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (_fillMesh != null && _fillMesh.method != FillMethod.None) + { + _fillMesh.OnPopulateMesh(vb); + } + else if (_scaleByTile) + { + NTexture texture = graphics.texture; + if (texture.root == texture + && texture.nativeTexture != null + && texture.nativeTexture.wrapMode == TextureWrapMode.Repeat) + { + Rect uvRect = vb.uvRect; + uvRect.width *= vb.contentRect.width / texture.width * _textureScale.x; + uvRect.height *= vb.contentRect.height / texture.height * _textureScale.y; + + vb.AddQuad(vb.contentRect, vb.vertexColor, uvRect); + vb.AddTriangles(); + } + else + { + Rect contentRect = vb.contentRect; + contentRect.width *= _textureScale.x; + contentRect.height *= _textureScale.y; + + TileFill(vb, contentRect, vb.uvRect, texture.width, texture.height); + vb.AddTriangles(); + } + } + else if (_scale9Grid != null) + { + SliceFill(vb); + } + else + graphics.OnPopulateMesh(vb); + } + + static int[] TRIANGLES_9_GRID = new int[] { + 4,0,1,1,5,4, + 5,1,2,2,6,5, + 6,2,3,3,7,6, + 8,4,5,5,9,8, + 9,5,6,6,10,9, + 10,6,7,7,11,10, + 12,8,9,9,13,12, + 13,9,10,10,14,13, + 14,10,11, + 11,15,14 + }; + + static int[] gridTileIndice = new int[] { -1, 0, -1, 2, 4, 3, -1, 1, -1 }; + static float[] gridX = new float[4]; + static float[] gridY = new float[4]; + static float[] gridTexX = new float[4]; + static float[] gridTexY = new float[4]; + + public void SliceFill(VertexBuffer vb) + { + NTexture texture = graphics.texture; + Rect gridRect = (Rect)_scale9Grid; + Rect contentRect = vb.contentRect; + contentRect.width *= _textureScale.x; + contentRect.height *= _textureScale.y; + Rect uvRect = vb.uvRect; + + float sourceW = texture.width; + float sourceH = texture.height; + + if (graphics.flip != FlipType.None) + { + if (graphics.flip == FlipType.Horizontal || graphics.flip == FlipType.Both) + { + gridRect.x = sourceW - gridRect.xMax; + gridRect.xMax = gridRect.x + gridRect.width; + } + + if (graphics.flip == FlipType.Vertical || graphics.flip == FlipType.Both) + { + gridRect.y = sourceH - gridRect.yMax; + gridRect.yMax = gridRect.y + gridRect.height; + } + } + + float sx = uvRect.width / sourceW; + float sy = uvRect.height / sourceH; + float xMax = uvRect.xMax; + float yMax = uvRect.yMax; + float xMax2 = gridRect.xMax; + float yMax2 = gridRect.yMax; + + gridTexX[0] = uvRect.x; + gridTexX[1] = uvRect.x + gridRect.x * sx; + gridTexX[2] = uvRect.x + xMax2 * sx; + gridTexX[3] = xMax; + gridTexY[0] = yMax; + gridTexY[1] = yMax - gridRect.y * sy; + gridTexY[2] = yMax - yMax2 * sy; + gridTexY[3] = uvRect.y; + + if (contentRect.width >= (sourceW - gridRect.width)) + { + gridX[1] = gridRect.x; + gridX[2] = contentRect.width - (sourceW - xMax2); + gridX[3] = contentRect.width; + } + else + { + float tmp = gridRect.x / (sourceW - xMax2); + tmp = contentRect.width * tmp / (1 + tmp); + gridX[1] = tmp; + gridX[2] = tmp; + gridX[3] = contentRect.width; + } + + if (contentRect.height >= (sourceH - gridRect.height)) + { + gridY[1] = gridRect.y; + gridY[2] = contentRect.height - (sourceH - yMax2); + gridY[3] = contentRect.height; + } + else + { + float tmp = gridRect.y / (sourceH - yMax2); + tmp = contentRect.height * tmp / (1 + tmp); + gridY[1] = tmp; + gridY[2] = tmp; + gridY[3] = contentRect.height; + } + + if (_tileGridIndice == 0) + { + for (int cy = 0; cy < 4; cy++) + { + for (int cx = 0; cx < 4; cx++) + vb.AddVert(new Vector2(gridX[cx] / _textureScale.x, gridY[cy] / _textureScale.y), vb.vertexColor, new Vector2(gridTexX[cx], gridTexY[cy])); + } + vb.AddTriangles(TRIANGLES_9_GRID); + } + else + { + Rect drawRect; + Rect texRect; + int row, col; + int part; + + for (int pi = 0; pi < 9; pi++) + { + col = pi % 3; + row = pi / 3; + part = gridTileIndice[pi]; + drawRect = Rect.MinMaxRect(gridX[col], gridY[row], gridX[col + 1], gridY[row + 1]); + texRect = Rect.MinMaxRect(gridTexX[col], gridTexY[row + 1], gridTexX[col + 1], gridTexY[row]); + + if (part != -1 && (_tileGridIndice & (1 << part)) != 0) + { + TileFill(vb, drawRect, texRect, + (part == 0 || part == 1 || part == 4) ? gridRect.width : drawRect.width, + (part == 2 || part == 3 || part == 4) ? gridRect.height : drawRect.height); + } + else + { + drawRect.x /= _textureScale.x; + drawRect.y /= _textureScale.y; + drawRect.width /= _textureScale.x; + drawRect.height /= _textureScale.y; + + vb.AddQuad(drawRect, vb.vertexColor, texRect); + } + } + + vb.AddTriangles(); + } + } + + void TileFill(VertexBuffer vb, Rect contentRect, Rect uvRect, float sourceW, float sourceH) + { + int hc = Mathf.CeilToInt(contentRect.width / sourceW); + int vc = Mathf.CeilToInt(contentRect.height / sourceH); + float tailWidth = contentRect.width - (hc - 1) * sourceW; + float tailHeight = contentRect.height - (vc - 1) * sourceH; + float xMax = uvRect.xMax; + float yMax = uvRect.yMax; + + for (int i = 0; i < hc; i++) + { + for (int j = 0; j < vc; j++) + { + Rect uvTmp = uvRect; + if (i == hc - 1) + uvTmp.xMax = Mathf.Lerp(uvRect.x, xMax, tailWidth / sourceW); + if (j == vc - 1) + uvTmp.yMin = Mathf.Lerp(uvRect.y, yMax, 1 - tailHeight / sourceH); + + Rect drawRect = new Rect(contentRect.x + i * sourceW, contentRect.y + j * sourceH, + i == (hc - 1) ? tailWidth : sourceW, j == (vc - 1) ? tailHeight : sourceH); + + drawRect.x /= _textureScale.x; + drawRect.y /= _textureScale.y; + drawRect.width /= _textureScale.x; + drawRect.height /= _textureScale.y; + + vb.AddQuad(drawRect, vb.vertexColor, uvTmp); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs.meta new file mode 100644 index 0000000..a97057c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Image.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 948ec8822e3c52942bc6e7f6265b264c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs new file mode 100644 index 0000000..f5b7ffd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs @@ -0,0 +1,243 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + [Flags] + public enum MaterialFlags + { + Clipped = 1, + SoftClipped = 2, + StencilTest = 4, + AlphaMask = 8, + Grayed = 16, + ColorFilter = 32 + } + + /// + /// Every texture-shader combination has a MaterialManager. + /// + public class MaterialManager + { + public event Action onCreateNewMaterial; + + public bool firstMaterialInFrame; + + NTexture _texture; + Shader _shader; + List _addKeywords; + Dictionary> _materials; + bool _combineTexture; + + class MaterialRef + { + public Material material; + public int frame; + public BlendMode blendMode; + public uint group; + } + + const int internalKeywordsCount = 6; + static string[] internalKeywords = new[] { "CLIPPED", "SOFT_CLIPPED", null, "ALPHA_MASK", "GRAYED", "COLOR_FILTER" }; + + /// + /// + /// + /// + /// + internal MaterialManager(NTexture texture, Shader shader) + { + _texture = texture; + _shader = shader; + _materials = new Dictionary>(); + _combineTexture = texture.alphaTexture != null; + } + + /// + /// + /// + /// + /// + public int GetFlagsByKeywords(IList keywords) + { + if (_addKeywords == null) + _addKeywords = new List(); + + int flags = 0; + for (int i = 0; i < keywords.Count; i++) + { + string s = keywords[i]; + if (string.IsNullOrEmpty(s)) + continue; + int j = _addKeywords.IndexOf(s); + if (j == -1) + { + j = _addKeywords.Count; + _addKeywords.Add(s); + } + flags += (1 << (j + internalKeywordsCount)); + } + + return flags; + } + + /// + /// + /// + /// + /// + /// + /// + public Material GetMaterial(int flags, BlendMode blendMode, uint group) + { + if (blendMode != BlendMode.Normal && BlendModeUtils.Factors[(int)blendMode].pma) + flags |= (int)MaterialFlags.ColorFilter; + + List items; + if (!_materials.TryGetValue(flags, out items)) + { + items = new List(); + _materials[flags] = items; + } + + int frameId = Time.frameCount; + int cnt = items.Count; + MaterialRef result = null; + for (int i = 0; i < cnt; i++) + { + MaterialRef item = items[i]; + + if (item.group == group && item.blendMode == blendMode) + { + if (item.frame != frameId) + { + firstMaterialInFrame = true; + item.frame = frameId; + } + else + firstMaterialInFrame = false; + + if (_combineTexture) + item.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + + return item.material; + } + else if (result == null && (item.frame > frameId || item.frame < frameId - 1)) //collect materials if it is unused in last frame + result = item; + } + + if (result == null) + { + result = new MaterialRef() { material = CreateMaterial(flags) }; + items.Add(result); + } + else if (_combineTexture) + result.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + + if (result.blendMode != blendMode) + { + BlendModeUtils.Apply(result.material, blendMode); + result.blendMode = blendMode; + } + + result.group = group; + result.frame = frameId; + firstMaterialInFrame = true; + return result.material; + } + + /// + /// + /// + /// + Material CreateMaterial(int flags) + { + Material mat = new Material(_shader); + + mat.mainTexture = _texture.nativeTexture; + if (_texture.alphaTexture != null) + { + mat.EnableKeyword("COMBINED"); + mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + } + + for (int i = 0; i < internalKeywordsCount; i++) + { + if ((flags & (1 << i)) != 0) + { + string s = internalKeywords[i]; + if (s != null) + mat.EnableKeyword(s); + } + } + if (_addKeywords != null) + { + int keywordCnt = _addKeywords.Count; + for (int i = 0; i < keywordCnt; i++) + { + if ((flags & (1 << (i + internalKeywordsCount))) != 0) + mat.EnableKeyword(_addKeywords[i]); + } + } + + mat.hideFlags = DisplayObject.hideFlags; + if (onCreateNewMaterial != null) + onCreateNewMaterial(mat); + + return mat; + } + + /// + /// + /// + public void DestroyMaterials() + { + var iter = _materials.GetEnumerator(); + while (iter.MoveNext()) + { + List items = iter.Current.Value; + if (Application.isPlaying) + { + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + Object.Destroy(items[j].material); + } + else + { + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + Object.DestroyImmediate(items[j].material); + } + items.Clear(); + } + iter.Dispose(); + } + + /// + /// + /// + public void RefreshMaterials() + { + _combineTexture = _texture.alphaTexture != null; + var iter = _materials.GetEnumerator(); + while (iter.MoveNext()) + { + List items = iter.Current.Value; + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + { + Material mat = items[j].material; + mat.mainTexture = _texture.nativeTexture; + if (_combineTexture) + { + mat.EnableKeyword("COMBINED"); + mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + } + } + } + iter.Dispose(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs.meta new file mode 100644 index 0000000..231c168 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MaterialManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7223c4628e56c1e448c70e10168f5fa1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh.meta new file mode 100644 index 0000000..1835cb1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fca659474d209d94fbded309f407995c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs new file mode 100644 index 0000000..9848001 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class CompositeMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public readonly List elements; + + /// + /// If it is -1, means all elements are active, otherwise, only the specific element is active + /// + public int activeIndex; + + public CompositeMesh() + { + elements = new List(); + activeIndex = -1; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int cnt = elements.Count; + if (cnt == 1) + elements[0].OnPopulateMesh(vb); + else + { + VertexBuffer vb2 = VertexBuffer.Begin(vb); + + for (int i = 0; i < cnt; i++) + { + if (activeIndex == -1 || i == activeIndex) + { + vb2.Clear(); + elements[i].OnPopulateMesh(vb2); + vb.Append(vb2); + } + } + + vb2.End(); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + bool flag = false; + int cnt = elements.Count; + for (int i = 0; i < cnt; i++) + { + if (activeIndex == -1 || i == activeIndex) + { + IHitTest ht = elements[i] as IHitTest; + if (ht != null) + { + if (ht.HitTest(contentRect, point)) + return true; + } + else + flag = true; + } + } + + return flag; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs.meta new file mode 100644 index 0000000..beafd23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/CompositeMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba3d921c1f6e95f4e9105f45fd67bda5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs new file mode 100644 index 0000000..13b4399 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs @@ -0,0 +1,200 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class EllipseMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? centerColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float startDegree; + + /// + /// + /// + public float endDegreee; + + static int[] SECTOR_CENTER_TRIANGLES = new int[] { + 0, 4, 1, + 0, 3, 4, + 0, 2, 3, + 0, 8, 5, + 0, 7, 8, + 0, 6, 7, + 6, 5, 2, + 2, 1, 6 + }; + + public EllipseMesh() + { + lineColor = Color.black; + startDegree = 0; + endDegreee = 360; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float sectionStart = Mathf.Clamp(startDegree, 0, 360); + float sectionEnd = Mathf.Clamp(endDegreee, 0, 360); + bool clipped = sectionStart > 0 || sectionEnd < 360; + sectionStart = sectionStart * Mathf.Deg2Rad; + sectionEnd = sectionEnd * Mathf.Deg2Rad; + Color32 centerColor2 = centerColor == null ? color : (Color32)centerColor; + + float radiusX = rect.width / 2; + float radiusY = rect.height / 2; + int sides = Mathf.CeilToInt(Mathf.PI * (radiusX + radiusY) / 4); + sides = Mathf.Clamp(sides, 40, 800); + float angleDelta = 2 * Mathf.PI / sides; + float angle = 0; + float lineAngle = 0; + + if (lineWidth > 0 && clipped) + { + lineAngle = lineWidth / Mathf.Max(radiusX, radiusY); + sectionStart += lineAngle; + sectionEnd -= lineAngle; + } + + int vpos = vb.currentVertCount; + float centerX = rect.x + radiusX; + float centerY = rect.y + radiusY; + vb.AddVert(new Vector3(centerX, centerY, 0), centerColor2); + for (int i = 0; i < sides; i++) + { + if (angle < sectionStart) + angle = sectionStart; + else if (angle > sectionEnd) + angle = sectionEnd; + Vector3 vec = new Vector3(Mathf.Cos(angle) * (radiusX - lineWidth) + centerX, Mathf.Sin(angle) * (radiusY - lineWidth) + centerY, 0); + vb.AddVert(vec, color); + if (lineWidth > 0) + { + vb.AddVert(vec, lineColor); + vb.AddVert(new Vector3(Mathf.Cos(angle) * radiusX + centerX, Mathf.Sin(angle) * radiusY + centerY, 0), lineColor); + } + angle += angleDelta; + } + + if (lineWidth > 0) + { + int cnt = sides * 3; + for (int i = 0; i < cnt; i += 3) + { + if (i != cnt - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else if (!clipped) + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + else + { + vb.AddTriangle(0, i + 1, i + 1); + vb.AddTriangle(i + 2, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 3, i + 2); + } + } + } + else + { + for (int i = 0; i < sides; i++) + { + if (i != sides - 1) + vb.AddTriangle(0, i + 1, i + 2); + else if (!clipped) + vb.AddTriangle(0, i + 1, 1); + else + vb.AddTriangle(0, i + 1, i + 1); + } + } + + if (lineWidth > 0 && clipped) + { + //扇形内边缘的线条 + + vb.AddVert(new Vector3(radiusX, radiusY, 0), lineColor); + float centerRadius = lineWidth * 0.5f; + + sectionStart -= lineAngle; + angle = sectionStart + lineAngle * 0.5f + Mathf.PI * 0.5f; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + angle -= Mathf.PI; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + vb.AddVert(new Vector3(Mathf.Cos(sectionStart) * radiusX + radiusX, Mathf.Sin(sectionStart) * radiusY + radiusY, 0), lineColor); + vb.AddVert(vb.GetPosition(vpos + 3), lineColor); + + sectionEnd += lineAngle; + angle = sectionEnd - lineAngle * 0.5f + Mathf.PI * 0.5f; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + angle -= Mathf.PI; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + vb.AddVert(vb.GetPosition(vpos + sides * 3), lineColor); + vb.AddVert(new Vector3(Mathf.Cos(sectionEnd) * radiusX + radiusX, Mathf.Sin(sectionEnd) * radiusY + radiusY, 0), lineColor); + + vb.AddTriangles(SECTOR_CENTER_TRIANGLES, sides * 3 + 1); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + float radiusX = contentRect.width * 0.5f; + float raduisY = contentRect.height * 0.5f; + float xx = point.x - radiusX - contentRect.x; + float yy = point.y - raduisY - contentRect.y; + if (Mathf.Pow(xx / radiusX, 2) + Mathf.Pow(yy / raduisY, 2) < 1) + { + if (startDegree != 0 || endDegreee != 360) + { + float deg = Mathf.Atan2(yy, xx) * Mathf.Rad2Deg; + if (deg < 0) + deg += 360; + return deg >= startDegree && deg <= endDegreee; + } + else + return true; + } + + return false; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs.meta new file mode 100644 index 0000000..7db7205 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/EllipseMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ea96854995120948847301fb48d1675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs new file mode 100644 index 0000000..c07074e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs @@ -0,0 +1,400 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class FillMesh : IMeshFactory + { + /// + /// + /// + public FillMethod method; + + /// + /// + /// + public int origin; + + /// + /// + /// + public float amount; + + /// + /// + /// + public bool clockwise; + + public FillMesh() + { + clockwise = true; + amount = 1; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + float amount = Mathf.Clamp01(this.amount); + switch (method) + { + case FillMethod.Horizontal: + FillHorizontal(vb, vb.contentRect, origin, amount); + break; + + case FillMethod.Vertical: + FillVertical(vb, vb.contentRect, origin, amount); + break; + + case FillMethod.Radial90: + FillRadial90(vb, vb.contentRect, (Origin90)origin, amount, clockwise); + break; + + case FillMethod.Radial180: + FillRadial180(vb, vb.contentRect, (Origin180)origin, amount, clockwise); + break; + + case FillMethod.Radial360: + FillRadial360(vb, vb.contentRect, (Origin360)origin, amount, clockwise); + break; + } + } + + static void FillHorizontal(VertexBuffer vb, Rect vertRect, int origin, float amount) + { + float a = vertRect.width * amount; + if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) + vertRect.x += (vertRect.width - a); + vertRect.width = a; + + vb.AddQuad(vertRect); + vb.AddTriangles(); + } + + static void FillVertical(VertexBuffer vb, Rect vertRect, int origin, float amount) + { + float a = vertRect.height * amount; + if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) + vertRect.y += (vertRect.height - a); + vertRect.height = a; + + vb.AddQuad(vertRect); + vb.AddTriangles(); + } + + //4 vertex + static void FillRadial90(VertexBuffer vb, Rect vertRect, Origin90 origin, float amount, bool clockwise) + { + bool flipX = origin == Origin90.TopRight || origin == Origin90.BottomRight; + bool flipY = origin == Origin90.BottomLeft || origin == Origin90.BottomRight; + if (flipX != flipY) + clockwise = !clockwise; + + float ratio = clockwise ? amount : (1 - amount); + float tan = Mathf.Tan(Mathf.PI * 0.5f * ratio); + bool thresold = false; + if (ratio != 1) + thresold = (vertRect.height / vertRect.width - tan) > 0; + if (!clockwise) + thresold = !thresold; + float x = vertRect.x + (ratio == 0 ? float.MaxValue : (vertRect.height / tan)); + float y = vertRect.y + (ratio == 1 ? float.MaxValue : (vertRect.width * tan)); + float x2 = x; + float y2 = y; + if (flipX) + x2 = vertRect.width - x; + if (flipY) + y2 = vertRect.height - y; + float xMin = flipX ? (vertRect.width - vertRect.x) : vertRect.xMin; + float yMin = flipY ? (vertRect.height - vertRect.y) : vertRect.yMin; + float xMax = flipX ? -vertRect.xMin : vertRect.xMax; + float yMax = flipY ? -vertRect.yMin : vertRect.yMax; + + vb.AddVert(new Vector3(xMin, yMin, 0)); + + if (clockwise) + vb.AddVert(new Vector3(xMax, yMin, 0)); + + if (y > vertRect.yMax) + { + if (thresold) + vb.AddVert(new Vector3(x2, yMax, 0)); + else + vb.AddVert(new Vector3(xMax, yMax, 0)); + } + else + vb.AddVert(new Vector3(xMax, y2, 0)); + + if (x > vertRect.xMax) + { + if (thresold) + vb.AddVert(new Vector3(xMax, y2, 0)); + else + vb.AddVert(new Vector3(xMax, yMax, 0)); + } + else + vb.AddVert(new Vector3(x2, yMax, 0)); + + if (!clockwise) + vb.AddVert(new Vector3(xMin, yMax, 0)); + + if (flipX == flipY) + { + vb.AddTriangle(0, 1, 2); + vb.AddTriangle(0, 2, 3); + } + else + { + vb.AddTriangle(2, 1, 0); + vb.AddTriangle(3, 2, 0); + } + } + + //8 vertex + static void FillRadial180(VertexBuffer vb, Rect vertRect, Origin180 origin, float amount, bool clockwise) + { + switch (origin) + { + case Origin180.Top: + if (amount <= 0.5f) + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.TopRight, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.TopLeft, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x += vertRect.width; + else + vertRect.x -= vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Bottom: + if (amount <= 0.5f) + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.BottomLeft, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.BottomRight, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x -= vertRect.width; + else + vertRect.x += vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Left: + if (amount <= 0.5f) + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.TopLeft, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.BottomLeft, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y -= vertRect.height; + else + vertRect.y += vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Right: + if (amount <= 0.5f) + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.BottomRight, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.TopRight, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y += vertRect.height; + else + vertRect.y -= vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + } + } + + //12 vertex + static void FillRadial360(VertexBuffer vb, Rect vertRect, Origin360 origin, float amount, bool clockwise) + { + switch (origin) + { + case Origin360.Top: + if (amount < 0.5f) + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x += vertRect.width; + else + vertRect.x -= vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + + break; + + case Origin360.Bottom: + if (amount < 0.5f) + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x -= vertRect.width; + else + vertRect.x += vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin360.Left: + if (amount < 0.5f) + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y -= vertRect.height; + else + vertRect.y += vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin360.Right: + if (amount < 0.5f) + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y += vertRect.height; + else + vertRect.y -= vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs.meta new file mode 100644 index 0000000..fabd898 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/FillMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b37d56dc1840734a8fdb4971f5bc733 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs new file mode 100644 index 0000000..347546b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs @@ -0,0 +1,179 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// Inspired by kim ki won (http://mypi.ruliweb.daum.net/mypi.htm?id=newtypekorea) + /// + public class LineMesh : IMeshFactory + { + /// + /// + /// + public GPath path; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public AnimationCurve lineWidthCurve; + + /// + /// + /// + public Gradient gradient; + + /// + /// + /// + public bool roundEdge; + + /// + /// + /// + public float fillStart; + + /// + /// + /// + public float fillEnd; + + /// + /// + /// + public float pointDensity; + + /// + /// + /// + public bool repeatFill; + + static List points = new List(); + static List ts = new List(); + + public LineMesh() + { + path = new GPath(); + lineWidth = 2; + fillStart = 0; + fillEnd = 1; + pointDensity = 0.1f; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Vector2 uvMin = vb.uvRect.position; + Vector2 uvMax = new Vector2(vb.uvRect.xMax, vb.uvRect.yMax); + float uvRatio = path.length / vb.textureSize.x; + + int segCount = path.segmentCount; + float t = 0; + float lw = lineWidth; + float u; + for (int si = 0; si < segCount; si++) + { + float ratio = path.GetSegmentLength(si) / path.length; + float t0 = Mathf.Clamp(fillStart - t, 0, ratio) / ratio; + float t1 = Mathf.Clamp(fillEnd - t, 0, ratio) / ratio; + if (t0 >= t1) + { + t += ratio; + continue; + } + + points.Clear(); + ts.Clear(); + path.GetPointsInSegment(si, t0, t1, points, ts, pointDensity); + int cnt = points.Count; + + Color c0 = vb.vertexColor; + Color c1 = vb.vertexColor; + if (gradient != null) + c0 = gradient.Evaluate(t); + if (lineWidthCurve != null) + lw = lineWidthCurve.Evaluate(t); + + if (roundEdge && si == 0 && t0 == 0) + DrawRoundEdge(vb, points[0], points[1], lw, c0, uvMin); + + int vertCount = vb.currentVertCount; + for (int i = 1; i < cnt; i++) + { + Vector3 p0 = points[i - 1]; + Vector3 p1 = points[i]; + int k = vertCount + (i - 1) * 2; + float tc = t + ratio * ts[i]; + + Vector3 lineVector = p1 - p0; + Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); + widthVector.Normalize(); + + if (i == 1) + { + if (repeatFill) + u = tc * uvRatio * uvMax.x; + else + u = Mathf.Lerp(uvMin.x, uvMax.x, t + ratio * ts[i - 1]); + vb.AddVert(p0 - widthVector * lw * 0.5f, c0, new Vector2(u, uvMax.y)); + vb.AddVert(p0 + widthVector * lw * 0.5f, c0, new Vector2(u, uvMin.y)); + + if (si != 0) //joint + { + vb.AddTriangle(k - 2, k - 1, k + 1); + vb.AddTriangle(k - 2, k + 1, k); + } + } + if (gradient != null) + c1 = gradient.Evaluate(tc); + + if (lineWidthCurve != null) + lw = lineWidthCurve.Evaluate(tc); + + if (repeatFill) + u = tc * uvRatio * uvMax.x; + else + u = Mathf.Lerp(uvMin.x, uvMax.x, tc); + vb.AddVert(p1 - widthVector * lw * 0.5f, c1, new Vector2(u, uvMax.y)); + vb.AddVert(p1 + widthVector * lw * 0.5f, c1, new Vector2(u, uvMin.y)); + + vb.AddTriangle(k, k + 1, k + 3); + vb.AddTriangle(k, k + 3, k + 2); + } + + if (roundEdge && si == segCount - 1 && t1 == 1) + DrawRoundEdge(vb, points[cnt - 1], points[cnt - 2], lw, c1, uvMax); + + t += ratio; + } + } + + void DrawRoundEdge(VertexBuffer vb, Vector2 p0, Vector2 p1, float lw, Color32 color, Vector2 uv) + { + Vector2 widthVector = Vector3.Cross(p0 - p1, new Vector3(0, 0, 1)); + widthVector.Normalize(); + widthVector = widthVector * lw / 2f; + Vector2 lineVector = (p0 - p1).normalized * lw / 2f; + + int sides = Mathf.CeilToInt(Mathf.PI * lw / 2); + if (sides < 6) + sides = 6; + int current = vb.currentVertCount; + float angleUnit = Mathf.PI / (sides - 1); + + vb.AddVert(p0, color, uv); + vb.AddVert(p0 + widthVector, color, uv); + + for (int n = 0; n < sides; n++) + { + vb.AddVert(p0 + Mathf.Cos(angleUnit * n) * widthVector + Mathf.Sin(angleUnit * n) * lineVector, color, uv); + vb.AddTriangle(current, current + 1 + n, current + 2 + n); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs.meta new file mode 100644 index 0000000..e347440 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/LineMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d1935a924fabf74a92c72b22a042279 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs new file mode 100644 index 0000000..99cf3bd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs @@ -0,0 +1,15 @@ + +namespace FairyGUI +{ + /// + /// + /// + public interface IMeshFactory + { + /// + /// + /// + /// + void OnPopulateMesh(VertexBuffer vb); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs.meta new file mode 100644 index 0000000..45a6cf3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/MeshFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 274275eaa3fbbc94697cbe90a0fb52f1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs new file mode 100644 index 0000000..c7cc167 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs @@ -0,0 +1,51 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PlaneMesh : IMeshFactory + { + public int gridSize = 30; + + public void OnPopulateMesh(VertexBuffer vb) + { + float w = vb.contentRect.width; + float h = vb.contentRect.height; + float xMax = vb.contentRect.xMax; + float yMax = vb.contentRect.yMax; + int hc = (int)Mathf.Min(Mathf.CeilToInt(w / gridSize), 9); + int vc = (int)Mathf.Min(Mathf.CeilToInt(h / gridSize), 9); + int eachPartX = Mathf.FloorToInt(w / hc); + int eachPartY = Mathf.FloorToInt(h / vc); + float x, y; + for (int i = 0; i <= vc; i++) + { + if (i == vc) + y = yMax; + else + y = vb.contentRect.y + i * eachPartY; + for (int j = 0; j <= hc; j++) + { + if (j == hc) + x = xMax; + else + x = vb.contentRect.x + j * eachPartX; + vb.AddVert(new Vector3(x, y, 0)); + } + } + + for (int i = 0; i < vc; i++) + { + int k = i * (hc + 1); + for (int j = 1; j <= hc; j++) + { + int m = k + j; + vb.AddTriangle(m - 1, m, m + hc); + vb.AddTriangle(m, m + hc + 1, m + hc); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs.meta new file mode 100644 index 0000000..7ff3827 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PlaneMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 121b756a7a8240c49b63fa9de560691a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs new file mode 100644 index 0000000..9ebf147 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PolygonMesh : IMeshFactory, IHitTest + { + /// + /// points must be in clockwise order, and must start from bottom-left if stretchUV is set. + /// + public readonly List points; + + /// + /// if you dont want to provide uv, leave it empty. + /// + public readonly List texcoords; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public Color32[] colors; + + /// + /// + /// + public bool usePercentPositions; + + static List sRestIndices = new List(); + + public PolygonMesh() + { + points = new List(); + texcoords = new List(); + } + + /// + /// + /// + /// + public void Add(Vector2 point) + { + points.Add(point); + } + + /// + /// + /// + /// + /// + public void Add(Vector2 point, Vector2 texcoord) + { + points.Add(point); + texcoords.Add(texcoord); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int numVertices = points.Count; + if (numVertices < 3) + return; + + int restIndexPos, numRestIndices; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float w = vb.contentRect.width; + float h = vb.contentRect.height; + bool useTexcoords = texcoords.Count >= numVertices; + bool fullUV = true; + for (int i = 0; i < numVertices; i++) + { + Vector3 vec = new Vector3(points[i].x, points[i].y, 0); + if (usePercentPositions) + { + vec.x *= w; + vec.y *= h; + } + if (useTexcoords) + { + Vector2 uv = texcoords[i]; + if (uv.x != 0 && uv.x != 1 || uv.y != 0 && uv.y != 1) + fullUV = false; + uv.x = Mathf.Lerp(vb.uvRect.x, vb.uvRect.xMax, uv.x); + uv.y = Mathf.Lerp(vb.uvRect.y, vb.uvRect.yMax, uv.y); + vb.AddVert(vec, color, uv); + } + else + vb.AddVert(vec, color); + } + + if (useTexcoords && fullUV && numVertices == 4) + vb._isArbitraryQuad = true; + + // Algorithm "Ear clipping method" described here: + // -> https://en.wikipedia.org/wiki/Polygon_triangulation + // + // Implementation inspired by: + // -> http://polyk.ivank.net + // -> Starling + + sRestIndices.Clear(); + for (int i = 0; i < numVertices; ++i) + sRestIndices.Add(i); + + restIndexPos = 0; + numRestIndices = numVertices; + + Vector2 a, b, c, p; + int otherIndex; + bool earFound; + int i0, i1, i2; + + while (numRestIndices > 3) + { + earFound = false; + i0 = sRestIndices[restIndexPos % numRestIndices]; + i1 = sRestIndices[(restIndexPos + 1) % numRestIndices]; + i2 = sRestIndices[(restIndexPos + 2) % numRestIndices]; + + a = points[i0]; + b = points[i1]; + c = points[i2]; + + if ((a.y - b.y) * (c.x - b.x) + (b.x - a.x) * (c.y - b.y) >= 0) + { + earFound = true; + for (int i = 3; i < numRestIndices; ++i) + { + otherIndex = sRestIndices[(restIndexPos + i) % numRestIndices]; + p = points[otherIndex]; + + if (IsPointInTriangle(ref p, ref a, ref b, ref c)) + { + earFound = false; + break; + } + } + } + + if (earFound) + { + vb.AddTriangle(i0, i1, i2); + sRestIndices.RemoveAt((restIndexPos + 1) % numRestIndices); + + numRestIndices--; + restIndexPos = 0; + } + else + { + restIndexPos++; + if (restIndexPos == numRestIndices) break; // no more ears + } + } + vb.AddTriangle(sRestIndices[0], sRestIndices[1], sRestIndices[2]); + + if (colors != null) + vb.RepeatColors(colors, 0, vb.currentVertCount); + + if (lineWidth > 0) + DrawOutline(vb); + } + + void DrawOutline(VertexBuffer vb) + { + int numVertices = points.Count; + int start = vb.currentVertCount - numVertices; + int k = vb.currentVertCount; + for (int i = 0; i < numVertices; i++) + { + Vector3 p0 = vb.vertices[start + i]; + p0.y = -p0.y; + Vector3 p1; + if (i < numVertices - 1) + p1 = vb.vertices[start + i + 1]; + else + p1 = vb.vertices[start]; + p1.y = -p1.y; + + Vector3 lineVector = p1 - p0; + Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); + widthVector.Normalize(); + + vb.AddVert(p0 - widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p0 + widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p1 - widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p1 + widthVector * lineWidth * 0.5f, lineColor); + + k += 4; + vb.AddTriangle(k - 4, k - 3, k - 1); + vb.AddTriangle(k - 4, k - 1, k - 2); + + //joint + if (i != 0) + { + vb.AddTriangle(k - 6, k - 5, k - 3); + vb.AddTriangle(k - 6, k - 3, k - 4); + } + if (i == numVertices - 1) + { + start += numVertices; + vb.AddTriangle(k - 2, k - 1, start + 1); + vb.AddTriangle(k - 2, start + 1, start); + } + } + } + + bool IsPointInTriangle(ref Vector2 p, ref Vector2 a, ref Vector2 b, ref Vector2 c) + { + // From Starling + // This algorithm is described well in this article: + // http://www.blackpawn.com/texts/pointinpoly/default.html + + float v0x = c.x - a.x; + float v0y = c.y - a.y; + float v1x = b.x - a.x; + float v1y = b.y - a.y; + float v2x = p.x - a.x; + float v2y = p.y - a.y; + + float dot00 = v0x * v0x + v0y * v0y; + float dot01 = v0x * v1x + v0y * v1y; + float dot02 = v0x * v2x + v0y * v2y; + float dot11 = v1x * v1x + v1y * v1y; + float dot12 = v1x * v2x + v1y * v2y; + + float invDen = 1.0f / (dot00 * dot11 - dot01 * dot01); + float u = (dot11 * dot02 - dot01 * dot12) * invDen; + float v = (dot00 * dot12 - dot01 * dot02) * invDen; + + return (u >= 0) && (v >= 0) && (u + v < 1); + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + // Algorithm & implementation thankfully taken from: + // -> http://alienryderflex.com/polygon/ + // inspired by Starling + int len = points.Count; + int i; + int j = len - 1; + bool oddNodes = false; + float w = contentRect.width; + float h = contentRect.height; + + for (i = 0; i < len; ++i) + { + float ix = points[i].x; + float iy = points[i].y; + float jx = points[j].x; + float jy = points[j].y; + if (usePercentPositions) + { + ix *= w; + iy *= h; + ix *= w; + iy *= h; + } + + if ((iy < point.y && jy >= point.y || jy < point.y && iy >= point.y) && (ix <= point.x || jx <= point.x)) + { + if (ix + (point.y - iy) / (jy - iy) * (jx - ix) < point.x) + oddNodes = !oddNodes; + } + + j = i; + } + + return oddNodes; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs.meta new file mode 100644 index 0000000..8382497 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/PolygonMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db020628cd79e714fbafdbaaa2cc355f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs new file mode 100644 index 0000000..3f1f9a9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs @@ -0,0 +1,85 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RectMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public Color32[] colors; + + public RectMesh() + { + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + if (lineWidth == 0) + { + if (color.a != 0)//optimized + vb.AddQuad(rect, color); + } + else + { + Rect part; + + //left,right + part = new Rect(rect.x, rect.y, lineWidth, rect.height); + vb.AddQuad(part, lineColor); + part = new Rect(rect.xMax - lineWidth, rect.y, lineWidth, rect.height); + vb.AddQuad(part, lineColor); + + //top, bottom + part = new Rect(rect.x + lineWidth, rect.y, rect.width - lineWidth * 2, lineWidth); + vb.AddQuad(part, lineColor); + part = new Rect(rect.x + lineWidth, rect.yMax - lineWidth, rect.width - lineWidth * 2, lineWidth); + vb.AddQuad(part, lineColor); + + //middle + if (color.a != 0)//optimized + { + part = Rect.MinMaxRect(rect.x + lineWidth, rect.y + lineWidth, rect.xMax - lineWidth, rect.yMax - lineWidth); + if (part.width > 0 && part.height > 0) + vb.AddQuad(part, color); + } + } + + if (colors != null) + vb.RepeatColors(colors, 0, vb.currentVertCount); + + vb.AddTriangles(); + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + return contentRect.Contains(point); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs.meta new file mode 100644 index 0000000..37fbe33 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RectMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 13a3a9d0d365d834696112114d7bf951 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs new file mode 100644 index 0000000..2a4d084 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs @@ -0,0 +1,128 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RegularPolygonMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public int sides; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? centerColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float[] distances; + + /// + /// + /// + public float rotation; + + public RegularPolygonMesh() + { + sides = 3; + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (distances != null && distances.Length < sides) + { + Debug.LogError("distances.Length 0) + { + vb.AddVert(vec, lineColor); + + xv = Mathf.Cos(angle) * r + centerX; + yv = Mathf.Sin(angle) * r + centerY; + vb.AddVert(new Vector3(xv, yv, 0), lineColor); + } + angle += angleDelta; + } + + if (lineWidth > 0) + { + int tmp = sides * 3; + for (int i = 0; i < tmp; i += 3) + { + if (i != tmp - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + } + } + else + { + for (int i = 0; i < sides; i++) + vb.AddTriangle(0, i + 1, (i == sides - 1) ? 1 : i + 2); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (drawRect != null) + return ((Rect)drawRect).Contains(point); + else + return contentRect.Contains(point); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta new file mode 100644 index 0000000..962d6b0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4084bdb2f1738340a28ab5699977f3b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs new file mode 100644 index 0000000..76fd965 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs @@ -0,0 +1,177 @@ +using UnityEngine; + +namespace FairyGUI +{ + public class RoundedRectMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float topLeftRadius; + + /// + /// + /// + public float topRightRadius; + + /// + /// + /// + public float bottomLeftRadius; + + /// + /// + /// + public float bottomRightRadius; + + public RoundedRectMesh() + { + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float radiusX = rect.width / 2; + float radiusY = rect.height / 2; + float cornerMaxRadius = Mathf.Min(radiusX, radiusY); + float centerX = radiusX + rect.x; + float centerY = radiusY + rect.y; + + vb.AddVert(new Vector3(centerX, centerY, 0), color); + + int cnt = vb.currentVertCount; + for (int i = 0; i < 4; i++) + { + float radius = 0; + switch (i) + { + case 0: + radius = bottomRightRadius; + break; + + case 1: + radius = bottomLeftRadius; + break; + + case 2: + radius = topLeftRadius; + break; + + case 3: + radius = topRightRadius; + break; + } + radius = Mathf.Min(cornerMaxRadius, radius); + + float offsetX = rect.x; + float offsetY = rect.y; + + if (i == 0 || i == 3) + offsetX = rect.xMax - radius * 2; + if (i == 0 || i == 1) + offsetY = rect.yMax - radius * 2; + + if (radius != 0) + { + int partNumSides = Mathf.Max(1, Mathf.CeilToInt(Mathf.PI * radius / 8)) + 1; + float angleDelta = Mathf.PI / 2 / partNumSides; + float angle = Mathf.PI / 2 * i; + float startAngle = angle; + + for (int j = 1; j <= partNumSides; j++) + { + if (j == partNumSides) //消除精度误差带来的不对齐 + angle = startAngle + Mathf.PI / 2; + Vector3 v1 = new Vector3(offsetX + Mathf.Cos(angle) * (radius - lineWidth) + radius, + offsetY + Mathf.Sin(angle) * (radius - lineWidth) + radius, 0); + vb.AddVert(v1, color); + if (lineWidth != 0) + { + vb.AddVert(v1, lineColor); + vb.AddVert(new Vector3(offsetX + Mathf.Cos(angle) * radius + radius, + offsetY + Mathf.Sin(angle) * radius + radius, 0), lineColor); + } + angle += angleDelta; + } + } + else + { + Vector3 v1 = new Vector3(offsetX, offsetY, 0); + if (lineWidth != 0) + { + if (i == 0 || i == 3) + offsetX -= lineWidth; + else + offsetX += lineWidth; + if (i == 0 || i == 1) + offsetY -= lineWidth; + else + offsetY += lineWidth; + Vector3 v2 = new Vector3(offsetX, offsetY, 0); + vb.AddVert(v2, color); + vb.AddVert(v2, lineColor); + vb.AddVert(v1, lineColor); + } + else + vb.AddVert(v1, color); + } + } + cnt = vb.currentVertCount - cnt; + + if (lineWidth > 0) + { + for (int i = 0; i < cnt; i += 3) + { + if (i != cnt - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + } + } + else + { + for (int i = 0; i < cnt; i++) + vb.AddTriangle(0, i + 1, (i == cnt - 1) ? 1 : i + 2); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (drawRect != null) + return ((Rect)drawRect).Contains(point); + else + return contentRect.Contains(point); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs.meta new file mode 100644 index 0000000..40e1c7c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/RoundedRectMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f910c4392a714c41b421c296621562b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs new file mode 100644 index 0000000..5cd375f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs @@ -0,0 +1,90 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class StraightLineMesh : IMeshFactory + { + /// + /// + /// + public Color color; + + /// + /// + /// + public Vector3 origin; + + /// + /// + /// + public Vector3 end; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public bool repeatFill; + + public StraightLineMesh() + { + color = Color.black; + lineWidth = 1; + } + + /// + /// + /// + /// + /// + /// + public StraightLineMesh(float lineWidth, Color color, bool repeatFill) + { + this.lineWidth = lineWidth; + this.color = color; + this.repeatFill = repeatFill; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (origin == end) + return; + + float length = Vector2.Distance(origin, end); + Vector3 lineVector = end - origin; + Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); + widthVector.Normalize(); + + Vector3 v0, v1, v2, v3; + + if (repeatFill) + { + float ratio = length / vb.textureSize.x; + v0 = VertexBuffer.NormalizedUV[0]; + v1 = VertexBuffer.NormalizedUV[1]; + v2 = new Vector2(ratio, 1); + v3 = new Vector2(ratio, 0); + } + else + { + v0 = new Vector2(vb.uvRect.xMin, vb.uvRect.yMin); + v1 = new Vector2(vb.uvRect.xMin, vb.uvRect.yMax); + v2 = new Vector2(vb.uvRect.xMax, vb.uvRect.yMax); + v3 = new Vector2(vb.uvRect.xMax, vb.uvRect.yMin); + } + + vb.AddVert(origin - widthVector * lineWidth * 0.5f, color, v0); + vb.AddVert(origin + widthVector * lineWidth * 0.5f, color, v1); + vb.AddVert(end + widthVector * lineWidth * 0.5f, color, v2); + vb.AddVert(end - widthVector * lineWidth * 0.5f, color, v3); + + vb.AddTriangles(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs.meta new file mode 100644 index 0000000..19278bf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/StraightLineMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 27b002bc89d804a7b8058b9d16d5c506 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs new file mode 100644 index 0000000..78ffb30 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs @@ -0,0 +1,441 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public sealed class VertexBuffer + { + /// + /// + /// + public Rect contentRect; + + /// + /// + /// + public Rect uvRect; + + /// + /// + /// + public Color32 vertexColor; + + /// + /// + /// + public Vector2 textureSize; + + /// + /// + /// + public readonly List vertices; + + /// + /// + /// + public readonly List colors; + + /// + /// + /// + public readonly List uvs; + + /// + /// + /// + public readonly List uvs2; + + /// + /// + /// + public readonly List triangles; + + static public Vector2[] NormalizedUV = new Vector2[] { + new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; + + static public Vector2[] NormalizedPosition = new Vector2[] { + new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1) }; + + internal bool _alphaInVertexColor; + internal bool _isArbitraryQuad; + + static Stack _pool = new Stack(); + + /// + /// + /// + /// + public static VertexBuffer Begin() + { + if (_pool.Count > 0) + { + VertexBuffer inst = _pool.Pop(); + inst.Clear(); + return inst; + } + else + return new VertexBuffer(); + } + + /// + /// + /// + /// + public static VertexBuffer Begin(VertexBuffer source) + { + VertexBuffer vb = Begin(); + vb.contentRect = source.contentRect; + vb.uvRect = source.uvRect; + vb.vertexColor = source.vertexColor; + vb.textureSize = source.textureSize; + + return vb; + } + + private VertexBuffer() + { + vertices = new List(); + colors = new List(); + uvs = new List(); + uvs2 = new List(); + triangles = new List(); + } + + /// + /// + /// + public void End() + { + _pool.Push(this); + } + + /// + /// + /// + public void Clear() + { + vertices.Clear(); + colors.Clear(); + uvs.Clear(); + uvs2.Clear(); + triangles.Clear(); + + _isArbitraryQuad = false; + _alphaInVertexColor = false; + } + + /// + /// + /// + public int currentVertCount + { + get + { + return vertices.Count; + } + } + + /// + /// + /// + /// + public void AddVert(Vector3 position) + { + position.y = -position.y; + vertices.Add(position); + colors.Add(vertexColor); + if (vertexColor.a != 255) + _alphaInVertexColor = true; + uvs.Add(new Vector2( + Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); + } + + /// + /// + /// + /// + /// + public void AddVert(Vector3 position, Color32 color) + { + position.y = -position.y; + vertices.Add(position); + colors.Add(color); + if (color.a != 255) + _alphaInVertexColor = true; + uvs.Add(new Vector2( + Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); + } + + /// + /// + /// + /// + /// + /// + public void AddVert(Vector3 position, Color32 color, Vector2 uv) + { + position.y = -position.y; + vertices.Add(position); + uvs.Add(new Vector2(uv.x, uv.y)); + colors.Add(color); + if (color.a != 255) + _alphaInVertexColor = true; + } + + /// + /// + /// 1---2 + /// | / | + /// 0---3 + /// + /// + public void AddQuad(Rect vertRect) + { + AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f)); + AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f)); + AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f)); + AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f)); + } + + /// + /// + /// + /// + /// + public void AddQuad(Rect vertRect, Color32 color) + { + AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f), color); + AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f), color); + AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f), color); + AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f), color); + } + + /// + /// + /// + /// + /// + /// + public void AddQuad(Rect vertRect, Color32 color, Rect uvRect) + { + vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMax, 0f)); + vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMin, 0f)); + vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMin, 0f)); + vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMax, 0f)); + + uvs.Add(new Vector2(uvRect.xMin, uvRect.yMin)); + uvs.Add(new Vector2(uvRect.xMin, uvRect.yMax)); + uvs.Add(new Vector2(uvRect.xMax, uvRect.yMax)); + uvs.Add(new Vector2(uvRect.xMax, uvRect.yMin)); + + colors.Add(color); + colors.Add(color); + colors.Add(color); + colors.Add(color); + + if (color.a != 255) + _alphaInVertexColor = true; + } + + static List helperV4List = new List(4) { Vector4.zero, Vector4.zero, Vector4.zero, Vector4.zero }; + internal List FixUVForArbitraryQuad() + { + //ref1 http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/ + //ref2 https://bitlush.com/blog/arbitrary-quadrilaterals-in-opengl-es-2-0 + + Vector4 qq = Vector4.one; + Vector2 a = vertices[2] - vertices[0]; + Vector2 b = vertices[1] - vertices[3]; + Vector2 c = vertices[0] - vertices[3]; + + float cross = a.x * b.y - a.y * b.x; + if (cross != 0) + { + float s = (a.x * c.y - a.y * c.x) / cross; + if (s > 0 && s < 1) + { + float t = (b.x * c.y - b.y * c.x) / cross; + if (t > 0 && t < 1) + { + qq.x = 1 / (1 - t); + qq.y = 1 / s; + qq.z = 1 / t; + qq.w = 1 / (1 - s); + } + } + } + + for (int i = 0; i < 4; i++) + { + Vector4 v = uvs[i]; + float q = qq[i]; + v.x *= q; + v.y *= q; + v.w = q; + helperV4List[i] = v; + } + + return helperV4List; + } + + /// + /// + /// + /// + /// + /// + public void RepeatColors(Color32[] value, int startIndex, int count) + { + int len = Mathf.Min(startIndex + count, vertices.Count); + int colorCount = value.Length; + int k = 0; + for (int i = startIndex; i < len; i++) + { + Color32 c = value[(k++) % colorCount]; + colors[i] = c; + if (c.a != 255) + _alphaInVertexColor = true; + } + } + + /// + /// + /// + /// + /// + /// + public void AddTriangle(int idx0, int idx1, int idx2) + { + triangles.Add(idx0); + triangles.Add(idx1); + triangles.Add(idx2); + } + + /// + /// + /// + /// + /// + public void AddTriangles(int[] idxList, int startVertexIndex = 0) + { + if (startVertexIndex != 0) + { + if (startVertexIndex < 0) + startVertexIndex = vertices.Count + startVertexIndex; + + int cnt = idxList.Length; + for (int i = 0; i < cnt; i++) + triangles.Add(idxList[i] + startVertexIndex); + } + else + triangles.AddRange(idxList); + } + + /// + /// + /// + /// + public void AddTriangles(int startVertexIndex = 0) + { + int cnt = vertices.Count; + if (startVertexIndex < 0) + startVertexIndex = cnt + startVertexIndex; + + for (int i = startVertexIndex; i < cnt; i += 4) + { + triangles.Add(i); + triangles.Add(i + 1); + triangles.Add(i + 2); + + triangles.Add(i + 2); + triangles.Add(i + 3); + triangles.Add(i); + } + } + + /// + /// + /// + /// + /// + public Vector3 GetPosition(int index) + { + if (index < 0) + index = vertices.Count + index; + + Vector3 vec = vertices[index]; + vec.y = -vec.y; + return vec; + } + + /// + /// + /// + /// + /// + /// + public Vector2 GetUVAtPosition(Vector2 position, bool usePercent) + { + if (usePercent) + { + return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, position.x), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, position.y)); + } + else + return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (position.y - contentRect.yMin) / contentRect.height)); + } + + /// + /// + /// + /// + public void Append(VertexBuffer vb) + { + int len = vertices.Count; + vertices.AddRange(vb.vertices); + uvs.AddRange(vb.uvs); + uvs2.AddRange(vb.uvs2); + colors.AddRange(vb.colors); + if (len != 0) + { + int len1 = vb.triangles.Count; + for (int i = 0; i < len1; i++) + triangles.Add(vb.triangles[i] + len); + } + else + triangles.AddRange(vb.triangles); + + if (vb._alphaInVertexColor) + _alphaInVertexColor = true; + } + + /// + /// + /// + /// + public void Insert(VertexBuffer vb) + { + vertices.InsertRange(0, vb.vertices); + uvs.InsertRange(0, vb.uvs); + uvs2.InsertRange(0, vb.uvs2); + colors.InsertRange(0, vb.colors); + int len = triangles.Count; + if (len != 0) + { + int len1 = vb.vertices.Count; + for (int i = 0; i < len; i++) + triangles[i] += len1; + } + triangles.InsertRange(0, vb.triangles); + + if (vb._alphaInVertexColor) + _alphaInVertexColor = true; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs.meta new file mode 100644 index 0000000..4dbc7cd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Mesh/VertexBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d5501e8f84e40e47835611ab3896029 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs new file mode 100644 index 0000000..aaa2a3c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs @@ -0,0 +1,414 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class MovieClip : Image + { + /// + /// + /// + public class Frame + { + public NTexture texture; + public float addDelay; + } + + /// + /// + /// + public float interval; + + /// + /// + /// + public bool swing; + + /// + /// + /// + public float repeatDelay; + + /// + /// + /// + public float timeScale; + + /// + /// Whether to ignore Unity time scale. + /// + public bool ignoreEngineTimeScale; + + Frame[] _frames; + int _frameCount; + int _frame; + bool _playing; + int _start; + int _end; + int _times; + int _endAt; + int _status; //0-none, 1-next loop, 2-ending, 3-ended + + float _frameElapsed; //当前帧延迟 + bool _reversed; + int _repeatedCount; + TimerCallback _timerDelegate; + + EventListener _onPlayEnd; + + /// + /// + /// + public MovieClip() + { + interval = 0.1f; + _playing = true; + _timerDelegate = OnTimer; + timeScale = 1; + ignoreEngineTimeScale = false; + + if (Application.isPlaying) + { + onAddedToStage.Add(OnAddedToStage); + onRemovedFromStage.Add(OnRemoveFromStage); + } + + SetPlaySettings(); + } + + /// + /// + /// + public EventListener onPlayEnd + { + get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } + } + + /// + /// + /// + public Frame[] frames + { + get + { + return _frames; + } + set + { + _frames = value; + _scale9Grid = null; + _scaleByTile = false; + + if (_frames == null) + { + _frameCount = 0; + graphics.texture = null; + CheckTimer(); + return; + } + _frameCount = frames.Length; + + if (_end == -1 || _end > _frameCount - 1) + _end = _frameCount - 1; + if (_endAt == -1 || _endAt > _frameCount - 1) + _endAt = _frameCount - 1; + + if (_frame < 0 || _frame > _frameCount - 1) + _frame = _frameCount - 1; + + InvalidateBatchingState(); + + _frameElapsed = 0; + _repeatedCount = 0; + _reversed = false; + + DrawFrame(); + CheckTimer(); + } + } + + /// + /// + /// + public bool playing + { + get { return _playing; } + set + { + if (_playing != value) + { + _playing = value; + CheckTimer(); + } + } + } + + /// + /// + /// + public int frame + { + get { return _frame; } + set + { + if (_frame != value) + { + if (_frames != null && value >= _frameCount) + value = _frameCount - 1; + + _frame = value; + _frameElapsed = 0; + DrawFrame(); + } + } + } + + /// + /// + /// + public void Rewind() + { + _frame = 0; + _frameElapsed = 0; + _reversed = false; + _repeatedCount = 0; + DrawFrame(); + } + + /// + /// + /// + /// + public void SyncStatus(MovieClip anotherMc) + { + _frame = anotherMc._frame; + _frameElapsed = anotherMc._frameElapsed; + _reversed = anotherMc._reversed; + _repeatedCount = anotherMc._repeatedCount; + DrawFrame(); + } + + /// + /// + /// + /// + public void Advance(float time) + { + int beginFrame = _frame; + bool beginReversed = _reversed; + float backupTime = time; + while (true) + { + float tt = interval + _frames[_frame].addDelay; + if (_frame == 0 && _repeatedCount > 0) + tt += repeatDelay; + if (time < tt) + { + _frameElapsed = 0; + break; + } + + time -= tt; + + if (swing) + { + if (_reversed) + { + _frame--; + if (_frame <= 0) + { + _frame = 0; + _repeatedCount++; + _reversed = !_reversed; + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = Mathf.Max(0, _frameCount - 2); + _repeatedCount++; + _reversed = !_reversed; + } + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = 0; + _repeatedCount++; + } + } + + if (_frame == beginFrame && _reversed == beginReversed) //走了一轮了 + { + float roundTime = backupTime - time; //这就是一轮需要的时间 + time -= Mathf.FloorToInt(time / roundTime) * roundTime; //跳过 + } + } + + DrawFrame(); + } + + /// + /// + /// + public void SetPlaySettings() + { + SetPlaySettings(0, -1, 0, -1); + } + + /// + /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) + /// + /// + /// + /// + /// + public void SetPlaySettings(int start, int end, int times, int endAt) + { + _start = start; + _end = end; + if (_end == -1 || _end > _frameCount - 1) + _end = _frameCount - 1; + _times = times; + _endAt = endAt; + if (_endAt == -1) + _endAt = _end; + _status = 0; + this.frame = start; + } + + void OnAddedToStage() + { + if (_playing && _frameCount > 0) + Timers.inst.AddUpdate(_timerDelegate); + } + + void OnRemoveFromStage() + { + Timers.inst.Remove(_timerDelegate); + } + + void CheckTimer() + { + if (!Application.isPlaying) + return; + + if (_playing && _frameCount > 0 && this.stage != null) + Timers.inst.AddUpdate(_timerDelegate); + else + Timers.inst.Remove(_timerDelegate); + } + + void OnTimer(object param) + { + if (!_playing || _frameCount == 0 || _status == 3) + return; + + float dt; + if (ignoreEngineTimeScale) + { + dt = Time.unscaledDeltaTime; + if (dt > 0.1f) + dt = 0.1f; + } + else + dt = Time.deltaTime; + if (timeScale != 1) + dt *= timeScale; + + _frameElapsed += dt; + float tt = interval + _frames[_frame].addDelay; + if (_frame == 0 && _repeatedCount > 0) + tt += repeatDelay; + if (_frameElapsed < tt) + return; + + _frameElapsed -= tt; + if (_frameElapsed > interval) + _frameElapsed = interval; + + if (swing) + { + if (_reversed) + { + _frame--; + if (_frame <= 0) + { + _frame = 0; + _repeatedCount++; + _reversed = !_reversed; + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = Mathf.Max(0, _frameCount - 2); + _repeatedCount++; + _reversed = !_reversed; + } + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = 0; + _repeatedCount++; + } + } + + if (_status == 1) //new loop + { + _frame = _start; + _frameElapsed = 0; + _status = 0; + DrawFrame(); + } + else if (_status == 2) //ending + { + _frame = _endAt; + _frameElapsed = 0; + _status = 3; //ended + DrawFrame(); + + DispatchEvent("onPlayEnd", null); + } + else + { + DrawFrame(); + if (_frame == _end) + { + if (_times > 0) + { + _times--; + if (_times == 0) + _status = 2; //ending + else + _status = 1; //new loop + } + else if (_start != 0) + _status = 1; //new loop + } + } + } + + void DrawFrame() + { + if (_frameCount > 0) + { + Frame frame = _frames[_frame]; + graphics.texture = frame.texture; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs.meta new file mode 100644 index 0000000..14f8687 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/MovieClip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5ddeeb52259b7ed4e8a604fa8cd47897 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs new file mode 100644 index 0000000..e46a4b1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs @@ -0,0 +1,67 @@ +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class NAudioClip + { + public static Action CustomDestroyMethod; + + /// + /// + /// + public DestroyMethod destroyMethod; + + /// + /// + /// + public AudioClip nativeClip; + + /// + /// + /// + /// + public NAudioClip(AudioClip audioClip) + { + nativeClip = audioClip; + } + + /// + /// + /// + public void Unload() + { + if (nativeClip == null) + return; + + if (destroyMethod == DestroyMethod.Unload) + Resources.UnloadAsset(nativeClip); + else if (destroyMethod == DestroyMethod.Destroy) + UnityEngine.Object.DestroyImmediate(nativeClip, true); + else if (destroyMethod == DestroyMethod.Custom) + { + if (CustomDestroyMethod == null) + Debug.LogWarning("NAudioClip.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); + else + CustomDestroyMethod(nativeClip); + } + + nativeClip = null; + } + + /// + /// + /// + /// + public void Reload(AudioClip audioClip) + { + if (nativeClip != null && nativeClip != audioClip) + Unload(); + + nativeClip = audioClip; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs.meta new file mode 100644 index 0000000..bde56cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NAudioClip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e081bc28928c3474194543c862fadec5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs new file mode 100644 index 0000000..9e8c03c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs @@ -0,0 +1,841 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + /// + /// + /// + public class NGraphics : IMeshFactory + { + /// + /// + /// + public GameObject gameObject { get; private set; } + + /// + /// + /// + public MeshFilter meshFilter { get; private set; } + + /// + /// + /// + public MeshRenderer meshRenderer { get; private set; } + + /// + /// + /// + public Mesh mesh { get; private set; } + + /// + /// + /// + public BlendMode blendMode; + + /// + /// 不参与剪裁 + /// + public bool dontClip; + + /// + /// 当Mesh更新时触发 + /// + public event Action meshModifier; + + NTexture _texture; + string _shader; + Material _material; + int _customMatarial; //0-none, 1-common, 2-support internal mask, 128-owns material + MaterialManager _manager; + string[] _shaderKeywords; + int _materialFlags; + IMeshFactory _meshFactory; + + float _alpha; + Color _color; + bool _meshDirty; + Rect _contentRect; + FlipType _flip; + + public class VertexMatrix + { + public Vector3 cameraPos; + public Matrix4x4 matrix; + } + VertexMatrix _vertexMatrix; + + bool hasAlphaBackup; + List _alphaBackup; //透明度改变需要通过修改顶点颜色实现,但顶点颜色本身可能就带有透明度,所以这里要有一个备份 + + internal int _maskFlag; + StencilEraser _stencilEraser; + +#if !UNITY_5_6_OR_NEWER + Color32[] _colors; +#endif + + MaterialPropertyBlock _propertyBlock; + bool _blockUpdated; + + /// + /// + /// + /// + public NGraphics(GameObject gameObject) + { + this.gameObject = gameObject; + + _alpha = 1f; + _shader = ShaderConfig.imageShader; + _color = Color.white; + _meshFactory = this; + + meshFilter = gameObject.AddComponent(); + meshRenderer = gameObject.AddComponent(); + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + meshRenderer.receiveShadows = false; + + mesh = new Mesh(); + mesh.name = gameObject.name; + mesh.MarkDynamic(); + + meshFilter.mesh = mesh; + + meshFilter.hideFlags = DisplayObject.hideFlags; + meshRenderer.hideFlags = DisplayObject.hideFlags; + mesh.hideFlags = DisplayObject.hideFlags; + + Stats.LatestGraphicsCreation++; + } + + /// + /// + /// + public IMeshFactory meshFactory + { + get { return _meshFactory; } + set + { + if (_meshFactory != value) + { + _meshFactory = value; + _meshDirty = true; + } + } + } + + /// + /// + /// + /// + /// + public T GetMeshFactory() where T : IMeshFactory, new() + { + if (!(_meshFactory is T)) + { + _meshFactory = new T(); + _meshDirty = true; + } + return (T)_meshFactory; + } + + /// + /// + /// + public Rect contentRect + { + get { return _contentRect; } + set + { + _contentRect = value; + _meshDirty = true; + } + } + + /// + /// + /// + public FlipType flip + { + get { return _flip; } + set + { + if (_flip != value) + { + _flip = value; + _meshDirty = true; + } + } + } + + /// + /// + /// + public NTexture texture + { + get { return _texture; } + set + { + if (_texture != value) + { + if (value != null) + value.AddRef(); + if (_texture != null) + _texture.ReleaseRef(); + + _texture = value; + if (_customMatarial != 0 && _material != null) + _material.mainTexture = _texture != null ? _texture.nativeTexture : null; + _meshDirty = true; + UpdateManager(); + } + } + } + + /// + /// + /// + public string shader + { + get { return _shader; } + set + { + _shader = value; + UpdateManager(); + } + } + + /// + /// + /// + /// + /// + public void SetShaderAndTexture(string shader, NTexture texture) + { + _shader = shader; + if (_texture != texture) + this.texture = texture; + else + UpdateManager(); + } + + /// + /// + /// + public Material material + { + get + { + if (_customMatarial == 0 && _material == null && _manager != null) + _material = _manager.GetMaterial(_materialFlags, blendMode, 0); + return _material; + } + set + { + if ((_customMatarial & 128) != 0 && _material != null) + Object.DestroyImmediate(_material); + + _material = value; + if (_material != null) + { + _customMatarial = 1; + if (_material.HasProperty(ShaderConfig.ID_Stencil) || _material.HasProperty(ShaderConfig.ID_ClipBox)) + _customMatarial |= 2; + + meshRenderer.sharedMaterial = _material; + if (_texture != null) + _material.mainTexture = _texture.nativeTexture; + } + else + { + _customMatarial = 0; + meshRenderer.sharedMaterial = null; + } + } + } + + /// + /// Same as material property except that ownership is transferred to this object. + /// + /// + public void SetMaterial(Material material) + { + this.material = material; + _customMatarial |= 128; + } + + /// + /// + /// + public string[] materialKeywords + { + get { return _shaderKeywords; } + set + { + _shaderKeywords = value; + UpdateMaterialFlags(); + } + } + + /// + /// + /// + /// + /// + public void ToggleKeyword(string keyword, bool enabled) + { + if (enabled) + { + if (_shaderKeywords == null) + { + _shaderKeywords = new string[] { keyword }; + UpdateMaterialFlags(); + } + else if (Array.IndexOf(_shaderKeywords, keyword) == -1) + { + Array.Resize(ref _shaderKeywords, _shaderKeywords.Length + 1); + _shaderKeywords[_shaderKeywords.Length - 1] = keyword; + UpdateMaterialFlags(); + } + } + else + { + if (_shaderKeywords != null) + { + int i = Array.IndexOf(_shaderKeywords, keyword); + if (i != -1) + { + _shaderKeywords[i] = null; + UpdateMaterialFlags(); + } + } + } + } + + void UpdateManager() + { + if (_texture != null) + _manager = _texture.GetMaterialManager(_shader); + else + _manager = null; + UpdateMaterialFlags(); + } + + void UpdateMaterialFlags() + { + if (_customMatarial != 0) + { + if (material != null) + material.shaderKeywords = _shaderKeywords; + } + else if (_shaderKeywords != null && _manager != null) + _materialFlags = _manager.GetFlagsByKeywords(_shaderKeywords); + else + _materialFlags = 0; + } + + /// + /// + /// + public bool enabled + { + get { return meshRenderer.enabled; } + set { meshRenderer.enabled = value; } + } + + /// + /// + /// + public int sortingOrder + { + get { return meshRenderer.sortingOrder; } + set { meshRenderer.sortingOrder = value; } + } + + /// + /// + /// + /// + internal void _SetStencilEraserOrder(int value) + { + _stencilEraser.meshRenderer.sortingOrder = value; + } + + /// + /// + /// + /// + public Color color + { + get { return _color; } + set { _color = value; } + } + + /// + /// + /// + public void Tint() + { + if (_meshDirty) + return; + + int vertCount = mesh.vertexCount; + if (vertCount == 0) + return; + +#if !UNITY_5_6_OR_NEWER + Color32[] colors = _colors; + if (colors == null) + colors = mesh.colors32; +#else + VertexBuffer vb = VertexBuffer.Begin(); + mesh.GetColors(vb.colors); + List colors = vb.colors; +#endif + for (int i = 0; i < vertCount; i++) + { + Color32 col = _color; + col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); + colors[i] = col; + } + +#if !UNITY_5_6_OR_NEWER + mesh.colors32 = colors; +#else + mesh.SetColors(vb.colors); + vb.End(); +#endif + } + + void ChangeAlpha(float value) + { + _alpha = value; + + int vertCount = mesh.vertexCount; + if (vertCount == 0) + return; + +#if !UNITY_5_6_OR_NEWER + Color32[] colors = _colors; + if (colors == null) + colors = mesh.colors32; +#else + VertexBuffer vb = VertexBuffer.Begin(); + mesh.GetColors(vb.colors); + List colors = vb.colors; +#endif + for (int i = 0; i < vertCount; i++) + { + Color32 col = colors[i]; + col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); + colors[i] = col; + } + +#if !UNITY_5_6_OR_NEWER + mesh.colors32 = colors; +#else + mesh.SetColors(vb.colors); + vb.End(); +#endif + } + + /// + /// + /// + public VertexMatrix vertexMatrix + { + get { return _vertexMatrix; } + set + { + _vertexMatrix = value; + _meshDirty = true; + } + } + + /// + /// + /// + /// + public MaterialPropertyBlock materialPropertyBlock + { + get + { + if (_propertyBlock == null) + _propertyBlock = new MaterialPropertyBlock(); + + _blockUpdated = true; + return _propertyBlock; + } + } + + /// + /// + /// + public void SetMeshDirty() + { + _meshDirty = true; + } + + /// + /// + /// + /// + public bool UpdateMesh() + { + if (_meshDirty) + { + UpdateMeshNow(); + return true; + } + else + return false; + } + + /// + /// + /// + public void Dispose() + { + if (mesh != null) + { + if (Application.isPlaying) + Object.Destroy(mesh); + else + Object.DestroyImmediate(mesh); + mesh = null; + } + if ((_customMatarial & 128) != 0 && _material != null) + Object.DestroyImmediate(_material); + + if (_texture != null) + { + _texture.ReleaseRef(); + _texture = null; + } + + _manager = null; + _material = null; + meshRenderer = null; + meshFilter = null; + _stencilEraser = null; + meshModifier = null; + } + + /// + /// + /// + /// + /// + /// + public void Update(UpdateContext context, float alpha, bool grayed) + { + Stats.GraphicsCount++; + + if (_meshDirty) + { + _alpha = alpha; + UpdateMeshNow(); + } + else if (_alpha != alpha) + ChangeAlpha(alpha); + + if (_propertyBlock != null && _blockUpdated) + { + meshRenderer.SetPropertyBlock(_propertyBlock); + _blockUpdated = false; + } + + if (_customMatarial != 0) + { + if ((_customMatarial & 2) != 0 && _material != null) + context.ApplyClippingProperties(_material, false); + } + else + { + if (_manager != null) + { + if (_maskFlag == 1) + { + _material = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, context.clipInfo.clipId); + context.ApplyAlphaMaskProperties(_material, false); + } + else + { + int matFlags = _materialFlags; + if (grayed) + matFlags |= (int)MaterialFlags.Grayed; + + if (context.clipped) + { + if (context.stencilReferenceValue > 0) + matFlags |= (int)MaterialFlags.StencilTest; + if (context.rectMaskDepth > 0) + { + if (context.clipInfo.soft) + matFlags |= (int)MaterialFlags.SoftClipped; + else + matFlags |= (int)MaterialFlags.Clipped; + } + + _material = _manager.GetMaterial(matFlags, blendMode, context.clipInfo.clipId); + if (_manager.firstMaterialInFrame) + context.ApplyClippingProperties(_material, true); + } + else + _material = _manager.GetMaterial(matFlags, blendMode, 0); + } + } + else + _material = null; + + if (!Material.ReferenceEquals(_material, meshRenderer.sharedMaterial)) + meshRenderer.sharedMaterial = _material; + } + + if (_maskFlag != 0) + { + if (_maskFlag == 1) + _maskFlag = 2; + else + { + if (_stencilEraser != null) + _stencilEraser.enabled = false; + + _maskFlag = 0; + } + } + } + + internal void _PreUpdateMask(UpdateContext context, uint maskId) + { + //_maskFlag: 0-new mask, 1-active mask, 2-mask complete + if (_maskFlag == 0) + { + if (_stencilEraser == null) + { + _stencilEraser = new StencilEraser(gameObject.transform); + _stencilEraser.meshFilter.mesh = mesh; + } + else + _stencilEraser.enabled = true; + } + + _maskFlag = 1; + + if (_manager != null) + { + //这里使用maskId而不是clipInfo.clipId,是因为遮罩有两个用途,一个是写入遮罩,一个是擦除,两个不能用同一个材质 + Material mat = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, maskId); + if (!Material.ReferenceEquals(mat, _stencilEraser.meshRenderer.sharedMaterial)) + _stencilEraser.meshRenderer.sharedMaterial = mat; + + context.ApplyAlphaMaskProperties(mat, true); + } + } + + void UpdateMeshNow() + { + _meshDirty = false; + + if (_texture == null || _meshFactory == null) + { + if (mesh.vertexCount > 0) + { + mesh.Clear(); + + if (meshModifier != null) + meshModifier(); + } + return; + } + + VertexBuffer vb = VertexBuffer.Begin(); + vb.contentRect = _contentRect; + vb.uvRect = _texture.uvRect; + if (_texture != null) + vb.textureSize = new Vector2(_texture.width, _texture.height); + else + vb.textureSize = new Vector2(0, 0); + if (_flip != FlipType.None) + { + if (_flip == FlipType.Horizontal || _flip == FlipType.Both) + { + float tmp = vb.uvRect.xMin; + vb.uvRect.xMin = vb.uvRect.xMax; + vb.uvRect.xMax = tmp; + } + if (_flip == FlipType.Vertical || _flip == FlipType.Both) + { + float tmp = vb.uvRect.yMin; + vb.uvRect.yMin = vb.uvRect.yMax; + vb.uvRect.yMax = tmp; + } + } + vb.vertexColor = _color; + _meshFactory.OnPopulateMesh(vb); + + int vertCount = vb.currentVertCount; + if (vertCount == 0) + { + if (mesh.vertexCount > 0) + { + mesh.Clear(); + + if (meshModifier != null) + meshModifier(); + } + vb.End(); + return; + } + + if (_texture.rotated) + { + float xMin = _texture.uvRect.xMin; + float yMin = _texture.uvRect.yMin; + float yMax = _texture.uvRect.yMax; + float tmp; + for (int i = 0; i < vertCount; i++) + { + Vector2 vec = vb.uvs[i]; + tmp = vec.y; + vec.y = yMin + vec.x - xMin; + vec.x = xMin + yMax - tmp; + vb.uvs[i] = vec; + } + } + + hasAlphaBackup = vb._alphaInVertexColor; + if (hasAlphaBackup) + { + if (_alphaBackup == null) + _alphaBackup = new List(); + else + _alphaBackup.Clear(); + for (int i = 0; i < vertCount; i++) + { + Color32 col = vb.colors[i]; + _alphaBackup.Add(col.a); + + col.a = (byte)(col.a * _alpha); + vb.colors[i] = col; + } + } + else if (_alpha != 1) + { + for (int i = 0; i < vertCount; i++) + { + Color32 col = vb.colors[i]; + col.a = (byte)(col.a * _alpha); + vb.colors[i] = col; + } + } + + if (_vertexMatrix != null) + { + Vector3 camPos = _vertexMatrix.cameraPos; + Vector3 center = new Vector3(camPos.x, camPos.y, 0); + center -= _vertexMatrix.matrix.MultiplyPoint(center); + for (int i = 0; i < vertCount; i++) + { + Vector3 pt = vb.vertices[i]; + pt = _vertexMatrix.matrix.MultiplyPoint(pt); + pt += center; + Vector3 vec = pt - camPos; + float lambda = -camPos.z / vec.z; + pt.x = camPos.x + lambda * vec.x; + pt.y = camPos.y + lambda * vec.y; + pt.z = 0; + + vb.vertices[i] = pt; + } + } + + mesh.Clear(); + +#if UNITY_5_2 || UNITY_5_3_OR_NEWER + mesh.SetVertices(vb.vertices); + if (vb._isArbitraryQuad) + mesh.SetUVs(0, vb.FixUVForArbitraryQuad()); + else + mesh.SetUVs(0, vb.uvs); + mesh.SetColors(vb.colors); + mesh.SetTriangles(vb.triangles, 0); + if (vb.uvs2.Count == vb.uvs.Count) + mesh.SetUVs(1, vb.uvs2); + +#if !UNITY_5_6_OR_NEWER + _colors = null; +#endif +#else + Vector3[] vertices = new Vector3[vertCount]; + Vector2[] uv = new Vector2[vertCount]; + _colors = new Color32[vertCount]; + int[] triangles = new int[vb.triangles.Count]; + + vb.vertices.CopyTo(vertices); + vb.uvs.CopyTo(uv); + vb.colors.CopyTo(_colors); + vb.triangles.CopyTo(triangles); + + mesh.vertices = vertices; + mesh.uv = uv; + mesh.triangles = triangles; + mesh.colors32 = _colors; + + if(vb.uvs2.Count==uv.Length) + { + uv = new Vector2[vertCount]; + vb.uvs2.CopyTo(uv); + mesh.uv2 = uv; + } +#endif + vb.End(); + + if (meshModifier != null) + meshModifier(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = texture.GetDrawRect(vb.contentRect); + + vb.AddQuad(rect, vb.vertexColor, vb.uvRect); + vb.AddTriangles(); + vb._isArbitraryQuad = _vertexMatrix != null; + } + + class StencilEraser + { + public GameObject gameObject; + public MeshFilter meshFilter; + public MeshRenderer meshRenderer; + + public StencilEraser(Transform parent) + { + gameObject = new GameObject("StencilEraser"); + gameObject.transform.SetParent(parent, false); + + meshFilter = gameObject.AddComponent(); + meshRenderer = gameObject.AddComponent(); + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + meshRenderer.receiveShadows = false; + + gameObject.layer = parent.gameObject.layer; + gameObject.hideFlags = parent.gameObject.hideFlags; + meshFilter.hideFlags = parent.gameObject.hideFlags; + meshRenderer.hideFlags = parent.gameObject.hideFlags; + } + + public bool enabled + { + get { return meshRenderer.enabled; } + set { meshRenderer.enabled = value; } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs.meta new file mode 100644 index 0000000..df86d03 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NGraphics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b84f79fb60acc974cb58c5368b257716 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs new file mode 100644 index 0000000..59ef486 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs @@ -0,0 +1,538 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + /// + /// + /// + public enum DestroyMethod + { + Destroy, + Unload, + None, + ReleaseTemp, + Custom + } + + /// + /// + /// + public class NTexture + { + /// + /// This event will trigger when a texture is destroying if its destroyMethod is Custom + /// + public static event Action CustomDestroyMethod; + + /// + /// + /// + public Rect uvRect; + + /// + /// + /// + public bool rotated; + + /// + /// + /// + public int refCount; + + /// + /// + /// + public float lastActive; + + /// + /// + /// + public DestroyMethod destroyMethod; + + /// + /// This event will trigger when texture reloaded and size changed. + /// + public event Action onSizeChanged; + + /// + /// This event will trigger when ref count is zero. + /// + public event Action onRelease; + + Texture _nativeTexture; + Texture _alphaTexture; + + Rect _region; + Vector2 _offset; + Vector2 _originalSize; + + NTexture _root; + Dictionary _materialManagers; + + internal static Texture2D CreateEmptyTexture() + { + Texture2D emptyTexture = new Texture2D(1, 1, TextureFormat.RGB24, false); + emptyTexture.name = "White Texture"; + emptyTexture.hideFlags = DisplayObject.hideFlags; + emptyTexture.SetPixel(0, 0, Color.white); + emptyTexture.Apply(); + return emptyTexture; + } + + static NTexture _empty; + + /// + /// + /// + public static NTexture Empty + { + get + { + if (_empty == null) + _empty = new NTexture(CreateEmptyTexture()); + + return _empty; + } + } + + /// + /// + /// + public static void DisposeEmpty() + { + if (_empty != null) + { + NTexture tmp = _empty; + _empty = null; + tmp.Dispose(); + } + } + + /// + /// + /// + /// + public NTexture(Texture texture) : this(texture, null, 1, 1) + { + } + + /// + /// + /// + /// + /// + /// + public NTexture(Texture texture, Texture alphaTexture, float xScale, float yScale) + { + _root = this; + _nativeTexture = texture; + _alphaTexture = alphaTexture; + uvRect = new Rect(0, 0, xScale, yScale); + if (yScale < 0) + { + uvRect.y = -yScale; + uvRect.yMax = 0; + } + if (xScale < 0) + { + uvRect.x = -xScale; + uvRect.xMax = 0; + } + if (_nativeTexture != null) + _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); + _region = new Rect(0, 0, _originalSize.x, _originalSize.y); + } + + /// + /// + /// + /// + /// + public NTexture(Texture texture, Rect region) + { + _root = this; + _nativeTexture = texture; + _region = region; + _originalSize = new Vector2(_region.width, _region.height); + if (_nativeTexture != null) + uvRect = new Rect(region.x / _nativeTexture.width, 1 - region.yMax / _nativeTexture.height, + region.width / _nativeTexture.width, region.height / _nativeTexture.height); + else + uvRect.Set(0, 0, 1, 1); + } + + /// + /// + /// + /// + /// + /// + public NTexture(NTexture root, Rect region, bool rotated) + { + _root = root; + this.rotated = rotated; + region.x += root._region.x; + region.y += root._region.y; + uvRect = new Rect(region.x * root.uvRect.width / root.width, 1 - region.yMax * root.uvRect.height / root.height, + region.width * root.uvRect.width / root.width, region.height * root.uvRect.height / root.height); + if (rotated) + { + float tmp = region.width; + region.width = region.height; + region.height = tmp; + + tmp = uvRect.width; + uvRect.width = uvRect.height; + uvRect.height = tmp; + } + _region = region; + _originalSize = _region.size; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public NTexture(NTexture root, Rect region, bool rotated, Vector2 originalSize, Vector2 offset) + : this(root, region, rotated) + { + _originalSize = originalSize; + _offset = offset; + } + + /// + /// + /// + /// + public NTexture(Sprite sprite) + { + Rect rect = sprite.textureRect; + rect.y = sprite.texture.height - rect.yMax; + + _root = this; + _nativeTexture = sprite.texture; + _region = rect; + _originalSize = new Vector2(_region.width, _region.height); + uvRect = new Rect(_region.x / _nativeTexture.width, 1 - _region.yMax / _nativeTexture.height, + _region.width / _nativeTexture.width, _region.height / _nativeTexture.height); + } + + // [Y ޸] + public NTexture(Sprite sprite, bool useRect) + { + Rect rect = sprite.rect; + rect.y = sprite.texture.height - rect.yMax; + + _offset = sprite.textureRectOffset; + _alphaTexture = sprite.associatedAlphaSplitTexture; + + _root = this; + _nativeTexture = sprite.texture; + _region = rect; + _originalSize = new Vector2(_region.width, _region.height); + uvRect = new Rect(_region.x / _nativeTexture.width, 1 - _region.yMax / _nativeTexture.height, + _region.width / _nativeTexture.width, _region.height / _nativeTexture.height); + } + + /// + /// + /// + public int width + { + get { return (int)_region.width; } + } + + /// + /// + /// + public int height + { + get { return (int)_region.height; } + } + + /// + /// + /// + public Vector2 offset + { + get { return _offset; } + set { _offset = value; } + } + + /// + /// + /// + public Vector2 originalSize + { + get { return _originalSize; } + set { _originalSize = value; } + } + + /// + /// + /// + /// + /// + public Rect GetDrawRect(Rect drawRect) + { + if (_originalSize.x == _region.width && _originalSize.y == _region.height) + return drawRect; + + float sx = drawRect.width / _originalSize.x; + float sy = drawRect.height / _originalSize.y; + return new Rect(_offset.x * sx, _offset.y * sy, _region.width * sx, _region.height * sy); + } + + /// + /// + /// + /// + public void GetUV(Vector2[] uv) + { + uv[0] = uvRect.position; + uv[1] = new Vector2(uvRect.xMin, uvRect.yMax); + uv[2] = new Vector2(uvRect.xMax, uvRect.yMax); + uv[3] = new Vector2(uvRect.xMax, uvRect.yMin); + if (rotated) + { + float xMin = uvRect.xMin; + float yMin = uvRect.yMin; + float yMax = uvRect.yMax; + + float tmp; + for (int i = 0; i < 4; i++) + { + Vector2 m = uv[i]; + tmp = m.y; + m.y = yMin + m.x - xMin; + m.x = xMin + yMax - tmp; + uv[i] = m; + } + } + } + + /// + /// + /// + public NTexture root + { + get { return _root; } + } + + /// + /// + /// + public bool disposed + { + get { return _root == null; } + } + + /// + /// + /// + public Texture nativeTexture + { + get { return _root != null ? _root._nativeTexture : null; } + } + + /// + /// + /// + public Texture alphaTexture + { + get { return _root != null ? _root._alphaTexture : null; } + } + + /// + /// + /// + public MaterialManager GetMaterialManager(string shaderName) + { + if (_root != this) + { + if (_root == null) + return null; + else + return _root.GetMaterialManager(shaderName); + } + + if (_materialManagers == null) + _materialManagers = new Dictionary(); + + MaterialManager mm; + if (!_materialManagers.TryGetValue(shaderName, out mm)) + { + mm = new MaterialManager(this, ShaderConfig.GetShader(shaderName)); + _materialManagers.Add(shaderName, mm); + } + + return mm; + } + + /// + /// + /// + public void Unload() + { + Unload(false); + } + + /// + /// + /// + public void Unload(bool destroyMaterials) + { + if (this == _empty) + return; + + if (_root != this) + throw new Exception("Unload is not allow to call on none root NTexture."); + + if (_nativeTexture != null) + { + DestroyTexture(); + + if (destroyMaterials) + DestroyMaterials(); + else + RefreshMaterials(); + } + } + + /// + /// + /// + /// + /// + public void Reload(Texture nativeTexture, Texture alphaTexture) + { + if (_root != this) + throw new System.Exception("Reload is not allow to call on none root NTexture."); + + if (_nativeTexture != null && _nativeTexture != nativeTexture) + DestroyTexture(); + + _nativeTexture = nativeTexture; + _alphaTexture = alphaTexture; + + Vector2 lastSize = _originalSize; + if (_nativeTexture != null) + _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); + else + _originalSize = Vector2.zero; + _region = new Rect(0, 0, _originalSize.x, _originalSize.y); + + RefreshMaterials(); + + if (onSizeChanged != null && lastSize != _originalSize) + onSizeChanged(this); + } + + void DestroyTexture() + { + switch (destroyMethod) + { + case DestroyMethod.Destroy: + Object.DestroyImmediate(_nativeTexture, true); + if (_alphaTexture != null) + Object.DestroyImmediate(_alphaTexture, true); + break; + case DestroyMethod.Unload: + Resources.UnloadAsset(_nativeTexture); + if (_alphaTexture != null) + Resources.UnloadAsset(_alphaTexture); + break; + case DestroyMethod.ReleaseTemp: + RenderTexture.ReleaseTemporary((RenderTexture)_nativeTexture); + if (_alphaTexture is RenderTexture) + RenderTexture.ReleaseTemporary((RenderTexture)_alphaTexture); + break; + case DestroyMethod.Custom: + if (CustomDestroyMethod == null) + Debug.LogWarning("NTexture.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); + else + { + CustomDestroyMethod(_nativeTexture); + if (_alphaTexture != null) + CustomDestroyMethod(_alphaTexture); + } + break; + } + + _nativeTexture = null; + _alphaTexture = null; + } + + void RefreshMaterials() + { + if (_materialManagers != null && _materialManagers.Count > 0) + { + Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); + while (iter.MoveNext()) + iter.Current.Value.RefreshMaterials(); + iter.Dispose(); + } + } + + void DestroyMaterials() + { + if (_materialManagers != null && _materialManagers.Count > 0) + { + Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); + while (iter.MoveNext()) + iter.Current.Value.DestroyMaterials(); + iter.Dispose(); + } + } + + public void AddRef() + { + if (_root == null) //disposed + return; + + if (_root != this && refCount == 0) + _root.AddRef(); + + refCount++; + } + + public void ReleaseRef() + { + if (_root == null) //disposed + return; + + refCount--; + + if (refCount == 0) + { + if (_root != this) + _root.ReleaseRef(); + + if (onRelease != null) + onRelease(this); + } + } + + /// + /// + /// + public void Dispose() + { + if (this == _empty) + return; + + if (_root == this) + Unload(true); + _root = null; + onSizeChanged = null; + onRelease = null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs.meta new file mode 100644 index 0000000..a97d80b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/NTexture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cdb420f5e4ef87d419c4467d1b8f2ddf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs new file mode 100644 index 0000000..57841ad --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs @@ -0,0 +1,95 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public static class ShaderConfig + { + /// + /// + /// + /// + /// + public delegate Shader GetFunction(string name); + + /// + /// + /// + public static GetFunction Get = Shader.Find; + + /// + /// + /// + public static string imageShader = "FairyGUI/Image"; + + /// + /// + /// + public static string textShader = "FairyGUI/Text"; + + /// + /// + /// + public static string bmFontShader = "FairyGUI/BMFont"; + + /// + /// + /// + public static string TMPFontShader = "FairyGUI/TMP"; + + public static int ID_ClipBox; + public static int ID_ClipSoftness; + public static int ID_AlphaTex; + public static int ID_StencilComp; + public static int ID_Stencil; + public static int ID_StencilOp; + public static int ID_StencilReadMask; + public static int ID_ColorMask; + public static int ID_ColorMatrix; + public static int ID_ColorOffset; + public static int ID_BlendSrcFactor; + public static int ID_BlendDstFactor; + public static int ID_ColorOption; + + public static int ID_Stencil2; + + static ShaderConfig() + { + ID_ClipBox = Shader.PropertyToID("_ClipBox"); + ID_ClipSoftness = Shader.PropertyToID("_ClipSoftness"); + ID_AlphaTex = Shader.PropertyToID("_AlphaTex"); + ID_StencilComp = Shader.PropertyToID("_StencilComp"); + ID_Stencil = Shader.PropertyToID("_Stencil"); + ID_StencilOp = Shader.PropertyToID("_StencilOp"); + ID_StencilReadMask = Shader.PropertyToID("_StencilReadMask"); + ID_ColorMask = Shader.PropertyToID("_ColorMask"); + ID_ColorMatrix = Shader.PropertyToID("_ColorMatrix"); + ID_ColorOffset = Shader.PropertyToID("_ColorOffset"); + ID_BlendSrcFactor = Shader.PropertyToID("_BlendSrcFactor"); + ID_BlendDstFactor = Shader.PropertyToID("_BlendDstFactor"); + ID_ColorOption = Shader.PropertyToID("_ColorOption"); + + ID_Stencil2 = Shader.PropertyToID("_StencilRef"); + } + + /// + /// + /// + /// + /// + public static Shader GetShader(string name) + { + Shader shader = Get(name); + if (shader == null) + { + Debug.LogWarning("FairyGUI: shader not found: " + name); + shader = Shader.Find("UI/Default"); + } + shader.hideFlags = DisplayObject.hideFlags; + + return shader; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs.meta new file mode 100644 index 0000000..9622faf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/ShaderConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4eae4be32683c04a96ac1c4cd1834ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs new file mode 100644 index 0000000..150f954 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs @@ -0,0 +1,250 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Shape : DisplayObject + { + /// + /// + /// + public Shape() + { + CreateGameObject("Shape"); + graphics = new NGraphics(gameObject); + graphics.texture = NTexture.Empty; + graphics.meshFactory = null; + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + /// + /// + /// + public void DrawRect(float lineSize, Color lineColor, Color fillColor) + { + RectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawRect(float lineSize, Color32[] colors) + { + RectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.colors = colors; + + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawRoundRect(float lineSize, Color lineColor, Color fillColor, + float topLeftRadius, float topRightRadius, float bottomLeftRadius, float bottomRightRadius) + { + RoundedRectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.topLeftRadius = topLeftRadius; + mesh.topRightRadius = topRightRadius; + mesh.bottomLeftRadius = bottomLeftRadius; + mesh.bottomRightRadius = bottomRightRadius; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + public void DrawEllipse(Color fillColor) + { + EllipseMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = 0; + mesh.startDegree = 0; + mesh.endDegreee = 360; + mesh.fillColor = null; + mesh.centerColor = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawEllipse(float lineSize, Color centerColor, Color lineColor, Color fillColor, float startDegree, float endDegree) + { + EllipseMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + if (centerColor.Equals(fillColor)) + mesh.centerColor = null; + else + mesh.centerColor = centerColor; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.startDegree = startDegree; + mesh.endDegreee = endDegree; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color fillColor) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color32[] colors) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.colors = colors; + + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color fillColor, float lineSize, Color lineColor) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawRegularPolygon(int sides, float lineSize, Color centerColor, Color lineColor, Color fillColor, float rotation, float[] distances) + { + RegularPolygonMesh mesh = graphics.GetMeshFactory(); + mesh.sides = sides; + mesh.lineWidth = lineSize; + mesh.centerColor = centerColor; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.rotation = rotation; + mesh.distances = distances; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + public void Clear() + { + graphics.meshFactory = null; + } + + /// + /// + /// + public bool isEmpty + { + get { return graphics.meshFactory == null; } + } + + protected override DisplayObject HitTest() + { + if (graphics.meshFactory == null) + return null; + + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + + IHitTest ht = graphics.meshFactory as IHitTest; + if (ht != null) + return ht.HitTest(_contentRect, localPoint) ? this : null; + else if (_contentRect.Contains(localPoint)) + return this; + else + return null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs.meta new file mode 100644 index 0000000..e790ffa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Shape.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cbcf11c269a33474aa9adaafd9867711 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs new file mode 100644 index 0000000..4aefa18 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs @@ -0,0 +1,1729 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +#if UNITY_5_3_OR_NEWER +using UnityEngine.SceneManagement; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public class Stage : Container + { + /// + /// [Y 修改] + /// + public string currLang = null; + + [Obsolete("Use size.y")] + public int stageHeight + { + get { return (int)_contentRect.height; } + } + + [Obsolete("Use size.x")] + public int stageWidth + { + get { return (int)_contentRect.width; } + } + + /// + /// + /// + public float soundVolume { get; set; } + + public event Action beforeUpdate; + public event Action afterUpdate; + + DisplayObject _touchTarget; + DisplayObject _focused; + InputTextField _lastInput; + bool _IMEComposite; + UpdateContext _updateContext; + List _rollOutChain; + List _rollOverChain; + TouchInfo[] _touches; + int _touchCount; + Vector2 _touchPosition; + int _frameGotHitTarget; + int _frameGotTouchPosition; + bool _customInput; + Vector2 _customInputPos; + bool _customInputButtonDown; + AudioSource _audio; + List _toCollectTextures = new List(); + EventListener _onStageResized; + List _focusOutChain; + List _focusInChain; + List _focusHistory; + Container _nextFocus; + + class CursorDef + { + public Texture2D texture; + public Vector2 hotspot; + } + + Dictionary _cursors; + string _currentCursor; + + static bool _touchScreen; + internal static int _clickTestThreshold; +#pragma warning disable 0649 + static IKeyboard _keyboard; +#pragma warning restore 0649 + + static Stage _inst; + + /// + /// + /// + public static Stage inst + { + get + { + if (_inst == null) + { + Instantiate(); + } + + return _inst; + } + } + + /// + /// + /// + public static void Instantiate() + { + if (_inst == null) + { + _inst = new Stage(); + GRoot._inst = new GRoot(); + GRoot._inst.ApplyContentScaleFactor(); + _inst.AddChild(GRoot._inst.displayObject); + + StageCamera.CheckMainCamera(); + } + } + + /// + /// 如果是true,表示触摸输入,将使用Input.GetTouch接口读取触摸屏输入。 + /// 如果是false,表示使用鼠标输入,将使用Input.GetMouseButtonXXX接口读取鼠标输入。 + /// 一般来说,不需要设置,底层会自动根据系统环境设置正确的值。 + /// + public static bool touchScreen + { + get { return _touchScreen; } + set + { + _touchScreen = value; + if (_touchScreen) + { +#if !(UNITY_WEBPLAYER || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR) + _keyboard = new FairyGUI.TouchScreenKeyboard(); + keyboardInput = true; +#endif + _clickTestThreshold = 50; + } + else + { + _keyboard = null; + keyboardInput = false; + Stage.inst.ResetInputState(); + _clickTestThreshold = 10; + } + } + } + + /// + /// 如果是true,表示使用屏幕上弹出的键盘输入文字。常见于移动设备。 + /// 如果是false,表示是接受按键消息输入文字。常见于PC。 + /// 一般来说,不需要设置,底层会自动根据系统环境设置正确的值。 + /// + public static bool keyboardInput { get; set; } + + /// + /// + /// + public static bool isTouchOnUI + { + get { return _inst != null && _inst.touchTarget != null; } + } + + /// + /// As unity does not provide ways to detect this, you should set it by yourself. + /// This will effect: + /// 1. compoistion cursor pos. + /// 2. mouse wheel speed. + /// + public static float devicePixelRatio { get; set; } + + /// + /// + /// + public Stage() + : base() + { + _inst = this; + soundVolume = 1; + + _updateContext = new UpdateContext(); + _frameGotHitTarget = -1; + + _touches = new TouchInfo[5]; + for (int i = 0; i < _touches.Length; i++) + _touches[i] = new TouchInfo(); + + bool isOSX = Application.platform == RuntimePlatform.OSXPlayer + || Application.platform == RuntimePlatform.OSXEditor; + if (Application.platform == RuntimePlatform.WindowsPlayer + || Application.platform == RuntimePlatform.WindowsEditor + || isOSX) + touchScreen = false; + else + touchScreen = Input.touchSupported && SystemInfo.deviceType != DeviceType.Desktop; + //在PC上,是否retina屏对输入法位置,鼠标滚轮速度都有影响,但现在没发现Unity有获得的方式。仅判断是否Mac可能不够(外接显示器的情况)。所以最好自行设置。 + devicePixelRatio = (isOSX && Screen.dpi > 96) ? 2 : 1; + + _rollOutChain = new List(); + _rollOverChain = new List(); + _focusOutChain = new List(); + _focusInChain = new List(); + _focusHistory = new List(); + _cursors = new Dictionary(); + + SetSize(Screen.width, Screen.height); + this.cachedTransform.localScale = new Vector3(StageCamera.DefaultUnitsPerPixel, + StageCamera.DefaultUnitsPerPixel, StageCamera.DefaultUnitsPerPixel); + + StageEngine engine = GameObject.FindObjectOfType(); + if (engine != null) + { + if (Application.isPlaying) + { + Object.Destroy(engine.gameObject); + } + else + { + Object.DestroyImmediate(engine.gameObject); + } + } + + this.gameObject.name = "Stage"; + this.gameObject.layer = LayerMask.NameToLayer(StageCamera.LayerName); + this.gameObject.AddComponent(); + this.gameObject.AddComponent(); + this.gameObject.SetActive(true); + // [Y 修改] + //UnityEngine.Object.DontDestroyOnLoad(this.gameObject); + + EnableSound(); + + Timers.inst.Add(5, 0, RunTextureCollector); + +#if UNITY_5_4_OR_NEWER + SceneManager.sceneLoaded += SceneManager_sceneLoaded; +#endif + } + +#if UNITY_5_4_OR_NEWER + void SceneManager_sceneLoaded(Scene scene, LoadSceneMode mode) + { + StageCamera.CheckMainCamera(); + } +#endif + + public override void Dispose() + { + base.Dispose(); + + Timers.inst.Remove(RunTextureCollector); + +#if UNITY_5_4_OR_NEWER + SceneManager.sceneLoaded -= SceneManager_sceneLoaded; +#endif + } + + /// + /// + /// + public EventListener onStageResized + { + get { return _onStageResized ?? (_onStageResized = new EventListener(this, "onStageResized")); } + } + + /// + /// + /// + public DisplayObject touchTarget + { + get + { + if (_frameGotHitTarget != Time.frameCount) + GetHitTarget(); + + if (_touchTarget == this) + return null; + else + return _touchTarget; + } + } + + /// + /// + /// + public DisplayObject focus + { + get + { + if (_focused != null && _focused.isDisposed) + _focused = null; + return _focused; + } + set { SetFocus(value); } + } + + public void SetFocus(DisplayObject newFocus, bool byKey = false) + { + if (newFocus == this) + newFocus = null; + + _nextFocus = null; + + if (_focused == newFocus) + return; + + Container navRoot = null; + DisplayObject element = newFocus; + while (element != null) + { + if (!element.focusable) + return; + else if ((element is Container) && ((Container)element).tabStopChildren) + { + if (navRoot == null) + navRoot = element as Container; + } + + element = element.parent; + } + + DisplayObject oldFocus = _focused; + _focused = newFocus; + + if (navRoot != null) + { + navRoot._lastFocus = _focused; + int pos = _focusHistory.IndexOf(navRoot); + if (pos != -1) + { + if (pos < _focusHistory.Count - 1) + _focusHistory.RemoveRange(pos + 1, _focusHistory.Count - pos - 1); + } + else + { + _focusHistory.Add(navRoot); + if (_focusHistory.Count > 10) + _focusHistory.RemoveAt(0); + } + } + + _focusInChain.Clear(); + _focusOutChain.Clear(); + + element = oldFocus; + while (element != null) + { + if (element.focusable) + _focusOutChain.Add(element); + element = element.parent; + } + + element = _focused; + int i; + while (element != null) + { + i = _focusOutChain.IndexOf(element); + if (i != -1) + { + _focusOutChain.RemoveRange(i, _focusOutChain.Count - i); + break; + } + + if (element.focusable) + _focusInChain.Add(element); + + element = element.parent; + } + + int cnt = _focusOutChain.Count; + if (cnt > 0) + { + for (i = 0; i < cnt; i++) + { + element = _focusOutChain[i]; + if (element.stage != null) + { + element.DispatchEvent("onFocusOut", null); + if (_focused != newFocus) //focus changed in event + return; + } + } + + _focusOutChain.Clear(); + } + + cnt = _focusInChain.Count; + if (cnt > 0) + { + for (i = 0; i < cnt; i++) + { + element = _focusInChain[i]; + if (element.stage != null) + { + element.DispatchEvent("onFocusIn", byKey ? "key" : null); + if (_focused != newFocus) //focus changed in event + return; + } + } + + _focusInChain.Clear(); + } + + if (_focused is InputTextField) + _lastInput = (InputTextField)_focused; + } + + internal void _OnFocusRemoving(Container sender) + { + _nextFocus = sender; + if (_focusHistory.Count > 0) + { + int i = _focusHistory.Count - 1; + DisplayObject test = _focusHistory[i]; + DisplayObject element = _focused; + while (element != null && element != sender) + { + if ((element is Container) && ((Container)element).tabStopChildren && element == test) + { + i--; + if (i < 0) + break; + + test = _focusHistory[i]; + } + + element = element.parent; + } + + if (i != _focusHistory.Count - 1) + { + _focusHistory.RemoveRange(i + 1, _focusHistory.Count - i - 1); + if (_focusHistory.Count > 0) + _nextFocus = _focusHistory[_focusHistory.Count - 1]; + } + } + + if (_focused is InputTextField) + _lastInput = null; + _focused = null; + } + + /// + /// + /// + /// + public void DoKeyNavigate(bool backward) + { + Container navBase = null; + DisplayObject element = _focused; + while (element != null) + { + if ((element is Container) && ((Container)element).tabStopChildren) + { + navBase = element as Container; + break; + } + + element = element.parent; + } + + if (navBase == null) + navBase = this; + + var it = navBase.GetDescendants(backward); + bool started = _focused == null; + DisplayObject test2 = _focused != null ? _focused.parent : null; + + while (it.MoveNext()) + { + DisplayObject dobj = it.Current; + if (started) + { + if (dobj == test2) + test2 = test2.parent; + else if (dobj._AcceptTab()) + return; + } + else if (dobj == _focused) + started = true; + } + + if (started) + { + it.Reset(); + while (it.MoveNext()) + { + DisplayObject dobj = it.Current; + if (dobj == _focused) + break; + + if (dobj == test2) + test2 = test2.parent; + else if (dobj._AcceptTab()) + return; + } + } + } + + /// + /// + /// + public Vector2 touchPosition + { + get + { + UpdateTouchPosition(); + return _touchPosition; + } + } + + /// + /// + /// + /// + /// + public Vector2 GetTouchPosition(int touchId) + { + UpdateTouchPosition(); + + if (touchId < 0) + return _touchPosition; + + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + if (touch.touchId == touchId) + return new Vector2(touch.x, touch.y); + } + + return _touchPosition; + } + + /// + /// + /// + /// + /// + public DisplayObject GetTouchTarget(int touchId) + { + if (_frameGotHitTarget != Time.frameCount) + GetHitTarget(); + + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + if (touch.touchId == touchId) + return touch.target != this ? touch.target : null; + } + + return null; + } + + + /// + /// + /// + public int touchCount + { + get { return _touchCount; } + } + + public int[] GetAllTouch(int[] result) + { + if (result == null) + result = new int[_touchCount]; + int i = 0; + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + if (touch.touchId != -1) + { + result[i++] = touch.touchId; + if (i >= result.Length) + break; + } + } + + return result; + } + + /// + /// + /// + public void ResetInputState() + { + for (int j = 0; j < 5; j++) + _touches[j].Reset(); + + if (!touchScreen) + _touches[0].touchId = 0; + + _touchCount = 0; + } + + + /// + /// + /// + /// + public void CancelClick(int touchId) + { + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + if (touch.touchId == touchId) + touch.clickCancelled = true; + } + } + + /// + /// + /// + public void EnableSound() + { + if (_audio == null) + { + _audio = gameObject.AddComponent(); + _audio.bypassEffects = true; + } + } + + /// + /// + /// + public void DisableSound() + { + if (_audio != null) + { + UnityEngine.Object.Destroy(_audio); + _audio = null; + } + } + + /// + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip, float volumeScale) + { + if (_audio != null && this.soundVolume > 0) + _audio.PlayOneShot(clip, volumeScale * this.soundVolume); + } + + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip) + { + if (_audio != null && this.soundVolume > 0) + _audio.PlayOneShot(clip, this.soundVolume); + } + + /// + /// + /// + public IKeyboard keyboard + { + get { return _keyboard; } + set { _keyboard = value; } + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void OpenKeyboard(string text, bool autocorrection, bool multiline, bool secure, + bool alert, string textPlaceholder, int keyboardType, bool hideInput) + { + if (_keyboard != null) + { + _keyboard.Open(text, autocorrection, multiline, secure, alert, textPlaceholder, keyboardType, + hideInput); + } + } + + /// + /// + /// + public void CloseKeyboard() + { + if (_keyboard != null) + { + _keyboard.Close(); + } + } + + /// + /// 输入字符到当前光标位置 + /// + /// + public void InputString(string value) + { + if (_lastInput != null) + _lastInput.ReplaceSelection(value); + } + + /// + /// + /// + /// + /// + public void SetCustomInput(Vector2 screenPos, bool buttonDown) + { + _customInput = true; + _customInputButtonDown = buttonDown; + _customInputPos = screenPos; + _frameGotHitTarget = 0; + } + + /// + /// + /// + /// + /// + /// + public void SetCustomInput(Vector2 screenPos, bool buttonDown, bool buttonUp) + { + _customInput = true; + if (buttonDown) + _customInputButtonDown = true; + else if (buttonUp) + _customInputButtonDown = false; + _customInputPos = screenPos; + _frameGotHitTarget = 0; + } + + /// + /// + /// + /// + /// + public void SetCustomInput(ref RaycastHit hit, bool buttonDown) + { + Vector2 screenPos = HitTestContext.cachedMainCamera.WorldToScreenPoint(hit.point); + HitTestContext.CacheRaycastHit(HitTestContext.cachedMainCamera, ref hit); + SetCustomInput(screenPos, buttonDown); + } + + /// + /// + /// + /// + /// + /// + public void SetCustomInput(ref RaycastHit hit, bool buttonDown, bool buttonUp) + { + Vector2 screenPos = HitTestContext.cachedMainCamera.WorldToScreenPoint(hit.point); + HitTestContext.CacheRaycastHit(HitTestContext.cachedMainCamera, ref hit); + SetCustomInput(screenPos, buttonDown, buttonUp); + } + + public void ForceUpdate() + { + _updateContext.Begin(); + Update(_updateContext); + _updateContext.End(); + } + + internal void InternalUpdate() + { + HandleEvents(); + + if (_nextFocus != null) + { + if (_nextFocus.stage != null) + { + if (_nextFocus.tabStopChildren) + { + if (_nextFocus._lastFocus != null && _nextFocus.IsAncestorOf(_nextFocus._lastFocus)) + SetFocus(_nextFocus._lastFocus); + else + SetFocus(_nextFocus); + } + else + SetFocus(_nextFocus); + } + + _nextFocus = null; + } + + if (beforeUpdate != null) + beforeUpdate(); + + _updateContext.Begin(); + Update(_updateContext); + _updateContext.End(); + + if (BaseFont.textRebuildFlag) + { + //字体贴图更改了,重新渲染一遍,防止本帧文字显示错误 + _updateContext.Begin(); + Update(_updateContext); + _updateContext.End(); + + BaseFont.textRebuildFlag = false; + } + + if (afterUpdate != null) + afterUpdate(); + } + + void GetHitTarget() + { + if (_frameGotHitTarget == Time.frameCount) + return; + + _frameGotHitTarget = Time.frameCount; + + if (_customInput) + { + Vector2 pos = _customInputPos; + pos.y = _contentRect.height - pos.y; + + TouchInfo touch = _touches[0]; + _touchTarget = HitTest(pos, true); + touch.target = _touchTarget; + } + else if (touchScreen) + { + _touchTarget = null; + for (int i = 0; i < Input.touchCount; ++i) + { + Touch uTouch = Input.GetTouch(i); + + Vector2 pos = uTouch.position; + pos.y = _contentRect.height - pos.y; + + TouchInfo touch = null; + TouchInfo free = null; + for (int j = 0; j < 5; j++) + { + if (_touches[j].touchId == uTouch.fingerId) + { + touch = _touches[j]; + break; + } + + if (_touches[j].touchId == -1) + free = _touches[j]; + } + + if (touch == null) + { + touch = free; + if (touch == null || uTouch.phase != TouchPhase.Began) + continue; + + touch.touchId = uTouch.fingerId; + } + + if (uTouch.phase == TouchPhase.Stationary) + _touchTarget = touch.target; + else + { + _touchTarget = HitTest(pos, true); + touch.target = _touchTarget; + } + } + } + else + { + Vector2 pos = Input.mousePosition; + pos.y = Screen.height - pos.y; + TouchInfo touch = _touches[0]; + if (pos.x < 0 || pos.y < 0) //outside of the window + _touchTarget = this; + else + _touchTarget = HitTest(pos, true); + touch.target = _touchTarget; + } + + HitTestContext.ClearRaycastHitCache(); + } + + internal void HandleScreenSizeChanged(int screenWidth, int screenHeight, float unitsPerPixel) + { + SetSize(screenWidth, screenHeight); + this.cachedTransform.localScale = new Vector3(unitsPerPixel, unitsPerPixel, unitsPerPixel); + + if (!DispatchEvent("onStageResized", null)) + { + UIContentScaler scaler = this.gameObject.GetComponent(); + scaler.ApplyChange(); + GRoot.inst.ApplyContentScaleFactor(); + } + } + + internal void HandleGUIEvents(Event evt) + { + if (evt.rawType == EventType.KeyDown) + { + if (_IMEComposite && Input.compositionString.Length == 0) + { + _IMEComposite = false; + //eat one key on IME closing + if (evt.keyCode != KeyCode.None) + return; + } + + TouchInfo touch = _touches[0]; + touch.keyCode = evt.keyCode; + touch.modifiers = evt.modifiers; + touch.character = evt.character; + + touch.UpdateEvent(); + DisplayObject f = this.focus; + if (f != null) + f.BubbleEvent("onKeyDown", touch.evt); + else + DispatchEvent("onKeyDown", touch.evt); + } + else if (evt.rawType == EventType.KeyUp) + { + TouchInfo touch = _touches[0]; + touch.keyCode = evt.keyCode; + touch.modifiers = evt.modifiers; + touch.character = evt.character; + + touch.UpdateEvent(); + DisplayObject f = this.focus; + if (f != null) + f.BubbleEvent("onKeyUp", touch.evt); + else + DispatchEvent("onKeyUp", touch.evt); + } +#if UNITY_2017_1_OR_NEWER + else if (evt.type == EventType.ScrollWheel) +#else + else if (evt.type == EventType.scrollWheel) +#endif + { + if (_touchTarget != null) + { + TouchInfo touch = _touches[0]; + touch.mouseWheelDelta = evt.delta.y; + touch.UpdateEvent(); + _touchTarget.BubbleEvent("onMouseWheel", touch.evt); + touch.mouseWheelDelta = 0; + } + } + } + + void HandleEvents() + { + GetHitTarget(); + + UpdateTouchPosition(); + + if (_customInput) + { + HandleCustomInput(); + _customInput = false; + } + else if (touchScreen) + HandleTouchEvents(); + else + HandleMouseEvents(); + + if (_focused is InputTextField) + HandleTextInput(); + } + + void UpdateTouchPosition() + { + if (_frameGotTouchPosition != Time.frameCount) + { + _frameGotTouchPosition = Time.frameCount; + if (_customInput) + { + _touchPosition = _customInputPos; + _touchPosition.y = _contentRect.height - _touchPosition.y; + } + else if (touchScreen) + { + for (int i = 0; i < Input.touchCount; ++i) + { + Touch uTouch = Input.GetTouch(i); + _touchPosition = uTouch.position; + _touchPosition.y = _contentRect.height - _touchPosition.y; + } + } + else + { + Vector2 pos = Input.mousePosition; + if (pos.x >= 0 && pos.y >= 0) //编辑器环境下坐标有时是负 + { + pos.y = _contentRect.height - pos.y; + _touchPosition = pos; + } + } + } + } + + void HandleTextInput() + { + _IMEComposite = Input.compositionString.Length > 0; + + InputTextField textField = (InputTextField)_focused; + if (!textField.editable) + return; + + if (keyboardInput) + { + if (textField.keyboardInput && _keyboard != null) + { + string s = _keyboard.GetInput(); + if (s != null) + { + if (_keyboard.supportsCaret) + textField.ReplaceSelection(s); + else + textField.ReplaceText(s); + } + + if (_keyboard.done) + SetFocus(null); + } + } + else + textField.CheckComposition(); + } + + void HandleCustomInput() + { + Vector2 pos = _customInputPos; + pos.y = _contentRect.height - pos.y; + TouchInfo touch = _touches[0]; + + if (touch.x != pos.x || touch.y != pos.y) + { + touch.x = pos.x; + touch.y = pos.y; + touch.Move(); + } + + if (touch.lastRollOver != touch.target) + HandleRollOver(touch); + + if (_customInputButtonDown) + { + if (!touch.began) + { + _touchCount = 1; + touch.Begin(); + touch.button = 0; + touch.touchId = 0; + SetFocus(touch.target); + + touch.UpdateEvent(); + touch.target.BubbleEvent("onTouchBegin", touch.evt); + } + } + else if (touch.began) + { + _touchCount = 0; + touch.End(); + + DisplayObject clickTarget = touch.ClickTest(); + if (clickTarget != null) + { + touch.UpdateEvent(); + clickTarget.BubbleEvent("onClick", touch.evt); + } + + touch.button = -1; + } + } + + void HandleMouseEvents() + { + TouchInfo touch = _touches[0]; + if (touch.x != _touchPosition.x || touch.y != _touchPosition.y) + { + touch.x = _touchPosition.x; + touch.y = _touchPosition.y; + touch.Move(); + } + + if (touch.lastRollOver != touch.target) + HandleRollOver(touch); + + if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2)) + { + if (!touch.began) + { + _touchCount = 1; + touch.Begin(); + touch.button = Input.GetMouseButtonDown(2) ? 2 : (Input.GetMouseButtonDown(1) ? 1 : 0); + SetFocus(touch.target); + + touch.UpdateEvent(); + touch.target.BubbleEvent("onTouchBegin", touch.evt); + } + } + + if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2)) + { + if (touch.began) + { + _touchCount = 0; + touch.End(); + + DisplayObject clickTarget = touch.ClickTest(); + if (clickTarget != null) + { + touch.UpdateEvent(); + + if (Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2)) + clickTarget.BubbleEvent("onRightClick", touch.evt); + else + clickTarget.BubbleEvent("onClick", touch.evt); + } + + touch.button = -1; + } + } + + //We have to do this, coz the cursor will auto change back after a click or dragging + if (Input.GetMouseButtonUp(0) && _currentCursor != null) + _ChangeCursor(_currentCursor); + } + + void HandleTouchEvents() + { + int tc = Input.touchCount; + for (int i = 0; i < tc; ++i) + { + Touch uTouch = Input.GetTouch(i); + + if (uTouch.phase == TouchPhase.Stationary) + continue; + + Vector2 pos = uTouch.position; + pos.y = _contentRect.height - pos.y; + + TouchInfo touch = null; + for (int j = 0; j < 5; j++) + { + if (_touches[j].touchId == uTouch.fingerId) + { + touch = _touches[j]; + break; + } + } + + if (touch == null) + continue; + + if (touch.x != pos.x || touch.y != pos.y) + { + touch.x = pos.x; + touch.y = pos.y; + if (touch.began) + touch.Move(); + } + + if (touch.lastRollOver != touch.target) + HandleRollOver(touch); + + if (uTouch.phase == TouchPhase.Began) + { + if (!touch.began) + { + _touchCount++; + touch.Begin(); + touch.button = 0; + SetFocus(touch.target); + + touch.UpdateEvent(); + touch.target.BubbleEvent("onTouchBegin", touch.evt); + } + } + else if (uTouch.phase == TouchPhase.Canceled || uTouch.phase == TouchPhase.Ended) + { + if (touch.began) + { + _touchCount--; + touch.End(); + + if (uTouch.phase != TouchPhase.Canceled) + { + DisplayObject clickTarget = touch.ClickTest(); + if (clickTarget != null) + { + touch.clickCount = uTouch.tapCount; + touch.UpdateEvent(); + clickTarget.BubbleEvent("onClick", touch.evt); + } + } + + touch.target = null; + HandleRollOver(touch); + + touch.touchId = -1; + } + } + } + } + + void HandleRollOver(TouchInfo touch) + { + DisplayObject element; + _rollOverChain.Clear(); + _rollOutChain.Clear(); + + element = touch.lastRollOver; + while (element != null) + { + _rollOutChain.Add(element); + element = element.parent; + } + + touch.lastRollOver = touch.target; + + string cursor = this.cursor; + if (cursor == null) + { + element = touch.target; + while (element != null) + { + if (element.cursor != null && cursor == null) + cursor = element.cursor; + element = element.parent; + } + } + + element = touch.target; + int i; + while (element != null) + { + i = _rollOutChain.IndexOf(element); + if (i != -1) + { + _rollOutChain.RemoveRange(i, _rollOutChain.Count - i); + break; + } + + _rollOverChain.Add(element); + + element = element.parent; + } + + int cnt = _rollOutChain.Count; + if (cnt > 0) + { + for (i = 0; i < cnt; i++) + { + element = _rollOutChain[i]; + if (element.stage != null) + element.DispatchEvent("onRollOut", null); + } + + _rollOutChain.Clear(); + } + + cnt = _rollOverChain.Count; + if (cnt > 0) + { + for (i = 0; i < cnt; i++) + { + element = _rollOverChain[i]; + if (element.stage != null) + element.DispatchEvent("onRollOver", null); + } + + _rollOverChain.Clear(); + } + + if (cursor != _currentCursor) + _ChangeCursor(cursor); + } + + /// + /// 设置UIPanel/UIPainter等的渲染层次,由UIPanel等内部调用。开发者不需要调用。 + /// + /// + /// + public void ApplyPanelOrder(Container target) + { + int sortingOrder = target._panelOrder; + int numChildren = this.numChildren; + int i = 0; + int j; + int curIndex = -1; + for (; i < numChildren; i++) + { + DisplayObject obj = GetChildAt(i); + if (obj == target) + { + curIndex = i; + continue; + } + + if (obj == GRoot.inst.displayObject) + j = 1000; + else if (obj is Container) + j = ((Container)obj)._panelOrder; + else + continue; + + if (sortingOrder <= j) + { + if (curIndex != -1) + AddChildAt(target, i - 1); + else + AddChildAt(target, i); + break; + } + } + + if (i == numChildren) + AddChild(target); + } + + + static List sTempList1; + static List sTempList2; + static Dictionary sTempDict; + + /// + /// Adjust display order of all UIPanels rendering in worldspace by their z order. + /// + /// Only UIPanel.sortingOrder equals to this value will be involve in this sorting + public void SortWorldSpacePanelsByZOrder(int panelSortingOrder) + { + if (sTempList1 == null) + { + sTempList1 = new List(); + sTempList2 = new List(); + sTempDict = new Dictionary(); + } + + int numChildren = this.numChildren; + for (int i = 0; i < numChildren; i++) + { + Container obj = GetChildAt(i) as Container; + if (obj == null || obj.renderMode != RenderMode.WorldSpace || obj._panelOrder != panelSortingOrder) + continue; + + sTempDict[obj.id] = i; + + sTempList1.Add(obj); + sTempList2.Add(i); + } + + sTempList1.Sort((DisplayObject c1, DisplayObject c2) => + { + int ret = c2.cachedTransform.position.z.CompareTo(c1.cachedTransform.position.z); + if (ret == 0) + { + //如果大家z值一样,使用原来的顺序,防止不停交换顺序(闪烁) + return sTempDict[c1.id].CompareTo(sTempDict[c2.id]); + } + else + return ret; + }); + + ChangeChildrenOrder(sTempList2, sTempList1); + + sTempList1.Clear(); + sTempList2.Clear(); + sTempDict.Clear(); + } + + /// + /// + /// + /// + public void MonitorTexture(NTexture texture) + { + if (_toCollectTextures.IndexOf(texture) == -1) + _toCollectTextures.Add(texture); + } + + void RunTextureCollector(object param) + { + int cnt = _toCollectTextures.Count; + float curTime = Time.time; + int i = 0; + while (i < cnt) + { + NTexture texture = _toCollectTextures[i]; + if (texture.disposed) + { + _toCollectTextures.RemoveAt(i); + cnt--; + } + else if (curTime - texture.lastActive > 5) + { + texture.Dispose(); + _toCollectTextures.RemoveAt(i); + cnt--; + } + else + i++; + } + } + + public void AddTouchMonitor(int touchId, EventDispatcher target) + { + TouchInfo touch = null; + for (int j = 0; j < 5; j++) + { + touch = _touches[j]; + if (touchId == -1 && touch.touchId != -1 + || touchId != -1 && touch.touchId == touchId) + break; + } + + if (touch.touchMonitors.IndexOf(target) == -1) + touch.touchMonitors.Add(target); + } + + public void RemoveTouchMonitor(EventDispatcher target) + { + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + int i = touch.touchMonitors.IndexOf(target); + if (i != -1) + touch.touchMonitors[i] = null; + } + } + + public bool IsTouchMonitoring(EventDispatcher target) + { + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + int i = touch.touchMonitors.IndexOf(target); + if (i != -1) + return true; + } + + return false; + } + + // [Y 修改] + public bool HasTouchMonitor(EventDispatcher target) + { + for (int j = 0; j < 5; j++) + { + TouchInfo touch = _touches[j]; + int i = touch.touchMonitors.IndexOf(target); + if (i != -1) + return true; + } + + return false; + } + + internal Transform CreatePoolManager(string name) + { + GameObject go = new GameObject("[" + name + "]"); + go.SetActive(false); + + Transform t = go.transform; + t.SetParent(cachedTransform, false); + + return t; + } + + /// + /// + /// + /// + /// + /// + public void RegisterCursor(string cursorName, Texture2D texture, Vector2 hotspot) + { + _cursors[cursorName] = new CursorDef() { texture = texture, hotspot = hotspot }; + } + + /// + /// + /// + /// + public string activeCursor + { + get { return _currentCursor; } + } + + /// + /// + /// + /// + internal void _ChangeCursor(string cursorName) + { + CursorDef cursorDef; + if (cursorName != null && _cursors.TryGetValue(cursorName, out cursorDef)) + { + if (_currentCursor == cursorName) + Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto); + _currentCursor = cursorName; + Cursor.SetCursor(cursorDef.texture, cursorDef.hotspot, CursorMode.Auto); + } + else + { + _currentCursor = null; + Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto); + } + } + } + + class TouchInfo + { + public float x; + public float y; + public int touchId; + public int clickCount; + public KeyCode keyCode; + public char character; + public EventModifiers modifiers; + public float mouseWheelDelta; + public int button; + + public float downX; + public float downY; + public float downTime; + public int downFrame; + public bool began; + public bool clickCancelled; + public float lastClickTime; + public float lastClickX; + public float lastClickY; + public int lastClickButton; + public float holdTime; + public DisplayObject target; + public List downTargets; + public DisplayObject lastRollOver; + public List touchMonitors; + + public InputEvent evt; + + static List sHelperChain = new List(); + + public TouchInfo() + { + evt = new InputEvent(); + downTargets = new List(); + touchMonitors = new List(); + Reset(); + } + + public void Reset() + { + touchId = -1; + x = 0; + y = 0; + clickCount = 0; + button = -1; + keyCode = KeyCode.None; + character = '\0'; + modifiers = 0; + mouseWheelDelta = 0; + lastClickTime = 0; + began = false; + target = null; + downTargets.Clear(); + lastRollOver = null; + clickCancelled = false; + touchMonitors.Clear(); + } + + public void UpdateEvent() + { + evt.touchId = this.touchId; + evt.x = this.x; + evt.y = this.y; + evt.clickCount = this.clickCount; + evt.keyCode = this.keyCode; + evt.character = this.character; + evt.modifiers = this.modifiers; + evt.mouseWheelDelta = this.mouseWheelDelta; + evt.button = this.button; + evt.holdTime = this.holdTime; + } + + public void Begin() + { + began = true; + clickCancelled = false; + downX = x; + downY = y; + downTime = Time.unscaledTime; + downFrame = Time.frameCount; + holdTime = 0; + + downTargets.Clear(); + if (target != null) + { + downTargets.Add(target); + DisplayObject obj = target; + while (obj != null) + { + downTargets.Add(obj); + obj = obj.parent; + } + } + } + + public void Move() + { + if (began) + holdTime = (Time.frameCount - downFrame) == 1 + ? (1f / Application.targetFrameRate) + : (Time.unscaledTime - downTime); + + UpdateEvent(); + + if (Mathf.Abs(x - downX) > 50 || Mathf.Abs(y - downY) > 50) clickCancelled = true; + + if (touchMonitors.Count > 0) + { + int len = touchMonitors.Count; + for (int i = 0; i < len; i++) + { + EventDispatcher e = touchMonitors[i]; + if (e != null) + { + if ((e is DisplayObject) && ((DisplayObject)e).stage == null) + continue; + if ((e is GObject) && !((GObject)e).onStage) + continue; + e.GetChainBridges("onTouchMove", sHelperChain, false); + } + } + + Stage.inst.BubbleEvent("onTouchMove", evt, sHelperChain); + sHelperChain.Clear(); + } + else + Stage.inst.DispatchEvent("onTouchMove", evt); + } + + public void End() + { + began = false; + + if (downTargets.Count == 0 + || clickCancelled + || Mathf.Abs(x - downX) > Stage._clickTestThreshold + || Mathf.Abs(y - downY) > Stage._clickTestThreshold) + { + clickCancelled = true; + lastClickTime = 0; + clickCount = 1; + } + else + { + if (Time.unscaledTime - lastClickTime < 0.35f + && Mathf.Abs(x - lastClickX) < Stage._clickTestThreshold + && Mathf.Abs(y - lastClickY) < Stage._clickTestThreshold + && lastClickButton == button) + { + if (clickCount == 2) + clickCount = 1; + else + clickCount++; + } + else + clickCount = 1; + + lastClickTime = Time.unscaledTime; + lastClickX = x; + lastClickY = y; + lastClickButton = button; + } + + //当间隔一帧时,使用帧率计算时间,避免掉帧因素 + holdTime = (Time.frameCount - downFrame) == 1 + ? (1f / Application.targetFrameRate) + : (Time.unscaledTime - downTime); + UpdateEvent(); + + if (touchMonitors.Count > 0) + { + int len = touchMonitors.Count; + for (int i = 0; i < len; i++) + { + EventDispatcher e = touchMonitors[i]; + if (e != null) + e.GetChainBridges("onTouchEnd", sHelperChain, false); + } + + target.BubbleEvent("onTouchEnd", evt, sHelperChain); + + touchMonitors.Clear(); + sHelperChain.Clear(); + } + else + target.BubbleEvent("onTouchEnd", evt); + } + + public DisplayObject ClickTest() + { + if (clickCancelled) + { + downTargets.Clear(); + return null; + } + + DisplayObject obj = downTargets[0]; + if (obj.stage != null) //依然派发到原来的downTarget,虽然可能它已经偏离当前位置,主要是为了正确处理点击缩放的效果 + { + downTargets.Clear(); + return obj; + } + + obj = target; + while (obj != null) + { + int i = downTargets.IndexOf(obj); + if (i != -1 && obj.stage != null) + break; + + obj = obj.parent; + } + + downTargets.Clear(); + + return obj; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs.meta new file mode 100644 index 0000000..c566784 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6650441f8140eae4c896682b7fd5b3e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs new file mode 100644 index 0000000..0cb034b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs @@ -0,0 +1,203 @@ +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Stage Camera is an orthographic camera for UI rendering. + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Camera")] + public class StageCamera : MonoBehaviour + { + /// + /// + /// + public bool constantSize = true; + + /// + /// + /// + [NonSerialized] + public float unitsPerPixel = 0.02f; + + [NonSerialized] + public Transform cachedTransform; + [NonSerialized] + public Camera cachedCamera; + + [NonSerialized] + int screenWidth; + [NonSerialized] + int screenHeight; + [NonSerialized] + bool isMain; + [NonSerialized] + Display _display; + + /// + /// + /// + [NonSerialized] + public static Camera main; + + /// + /// + /// + [NonSerialized] + public static int screenSizeVer = 1; + + public const string Name = "Stage Camera"; + public const string LayerName = "UI"; + //[Y 修改] + //public static float DefaultCameraSize = 5; + public static float DefaultCameraSize = Screen.height / 2 * 0.01f; + //[Y 修改] + //public static float DefaultUnitsPerPixel = 0.02f; + public static float DefaultUnitsPerPixel = 0.01f; + + void OnEnable() + { + cachedTransform = this.transform; + cachedCamera = this.GetComponent(); + if (this.gameObject.name == Name) + { + main = cachedCamera; + isMain = true; + } + + if (Display.displays.Length > 1 && cachedCamera.targetDisplay != 0 && cachedCamera.targetDisplay < Display.displays.Length) + _display = Display.displays[cachedCamera.targetDisplay]; + + if (_display == null) + OnScreenSizeChanged(Screen.width, Screen.height); + else + OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); + } + + void Update() + { + if (_display == null) + { + if (screenWidth != Screen.width || screenHeight != Screen.height) + OnScreenSizeChanged(Screen.width, Screen.height); + } + else + { + if (screenWidth != _display.renderingWidth || screenHeight != _display.renderingHeight) + OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); + } + } + + void OnScreenSizeChanged(int newWidth, int newHeight) + { + if (newWidth == 0 || newHeight == 0) + return; + + screenWidth = newWidth; + screenHeight = newHeight; + + if (constantSize) + { + cachedCamera.orthographicSize = DefaultCameraSize; + unitsPerPixel = cachedCamera.orthographicSize * 2 / screenHeight; + } + else + { + unitsPerPixel = DefaultUnitsPerPixel; + cachedCamera.orthographicSize = screenHeight / 2 * unitsPerPixel; + } + cachedTransform.localPosition = new Vector3(cachedCamera.orthographicSize * screenWidth / screenHeight, -cachedCamera.orthographicSize); + + if (isMain) + { + screenSizeVer++; + if (Application.isPlaying) + Stage.inst.HandleScreenSizeChanged(screenWidth, screenHeight, unitsPerPixel); + else + { + UIContentScaler scaler = GameObject.FindObjectOfType(); + if (scaler != null) + scaler.ApplyChange(); + else + UIContentScaler.scaleFactor = 1; + } + } + } + + void OnRenderObject() + { + //Update和OnGUI在EditMode的调用都不那么及时,OnRenderObject则比较频繁,可以保证界面及时刷新。所以使用OnRenderObject + if (isMain && !Application.isPlaying) + { + EMRenderSupport.Update(); + } + } + + public void ApplyModifiedProperties() + { + screenWidth = 0; //force OnScreenSizeChanged called in next update + } + + /// + /// Check if there is a stage camera in the scene. If none, create one. + /// + public static void CheckMainCamera() + { + // [Y 修改] + //if (GameObject.Find(Name) == null) + if (main == null) + { + int layer = LayerMask.NameToLayer(LayerName); + CreateCamera(Name, 1 << layer); + } + + HitTestContext.cachedMainCamera = Camera.main; + } + + /// + /// + /// + public static void CheckCaptureCamera() + { + // [Y 修改] + //if (GameObject.Find(Name) == null) + if (main == null) + { + int layer = LayerMask.NameToLayer(LayerName); + CreateCamera(Name, 1 << layer); + } + } + + /// + /// + /// + /// + /// + /// + public static Camera CreateCamera(string name, int cullingMask) + { + GameObject cameraObject = new GameObject(name); + Camera camera = cameraObject.AddComponent(); + camera.depth = 1; + camera.cullingMask = cullingMask; + camera.clearFlags = CameraClearFlags.Depth; + camera.orthographic = true; + camera.orthographicSize = DefaultCameraSize; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + +#if UNITY_5_4_OR_NEWER + camera.stereoTargetEye = StereoTargetEyeMask.None; +#endif + +#if UNITY_5_6_OR_NEWER + camera.allowHDR = false; + camera.allowMSAA = false; +#endif + cameraObject.AddComponent(); + + return camera; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs.meta new file mode 100644 index 0000000..61e4fb8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageCamera.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 367e80e3fa958344491a9a196a902b72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs new file mode 100644 index 0000000..5291199 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class StageEngine : MonoBehaviour + { + public int ObjectsOnStage; + public int GraphicsOnStage; + + public static bool beingQuit; + + void Start() + { + useGUILayout = false; + } + + void LateUpdate() + { + Stage.inst.InternalUpdate(); + + ObjectsOnStage = Stats.ObjectCount; + GraphicsOnStage = Stats.GraphicsCount; + } + + void OnGUI() + { + Stage.inst.HandleGUIEvents(Event.current); + } + +#if !UNITY_5_4_OR_NEWER + void OnLevelWasLoaded() + { + StageCamera.CheckMainCamera(); + } +#endif + + void OnApplicationQuit() + { + // [Y ޸] + //if (Application.isEditor) + //{ + // beingQuit = true; + // UIPackage.RemoveAllPackages(); + //} + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs.meta new file mode 100644 index 0000000..87aa048 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/StageEngine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0922848d650639f479e29635982d4a4c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs new file mode 100644 index 0000000..0743e7f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs @@ -0,0 +1,29 @@ + +namespace FairyGUI +{ + /// + /// + /// + public class Stats + { + /// + /// + /// + public static int ObjectCount; + + /// + /// + /// + public static int GraphicsCount; + + /// + /// + /// + public static int LatestObjectCreation; + + /// + /// + /// + public static int LatestGraphicsCreation; + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs.meta new file mode 100644 index 0000000..c02870a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Stats.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: baddfd53a8a771f4eaa567ee3eb2ccc0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text.meta new file mode 100644 index 0000000..ddc1d16 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b6a329985f59cbd4ba1618ac71c89d7d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs new file mode 100644 index 0000000..fd9764e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs @@ -0,0 +1,121 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Base class for all kind of fonts. + /// + public class BaseFont + { + /// + /// [Y 修改] + /// [FGUI字体] 是否使用FGUI自定义的粗体斜体 + /// + public const bool IsFguiCustomBoldAndItalic = true; + + /// + /// [Y 修改] + /// [FGUI字体] 真实字体的名字 + /// + public string realFontName = null; + + /// + /// The name of this font object. + /// + public string name; + + /// + /// The texture of this font object. + /// + public NTexture mainTexture; + + /// + /// Can this font be tinted? Will be true for dynamic font and fonts generated by BMFont. + /// + public bool canTint; + + /// + /// [Y 修改] + /// If true, it will use extra vertices to enhance bold effect + /// + public bool customBold = IsFguiCustomBoldAndItalic; + + /// + /// [Y 修改] + /// If true, it will use extra vertices to enhance bold effect ONLY when it is in italic style. + /// + public bool customBoldAndItalic = IsFguiCustomBoldAndItalic; + + /// + /// If true, it will use extra vertices(4 direction) to enhance outline effect + /// + public bool customOutline; + + /// + /// The shader for this font object. + /// + public string shader; + + /// + /// Keep text crisp. + /// + public bool keepCrisp; + + /// + /// + /// + public int version; + + protected internal static bool textRebuildFlag; + + protected const float SupScale = 0.58f; + protected const float SupOffset = 0.33f; + + virtual public void UpdateGraphics(NGraphics graphics) + { + } + + virtual public void SetFormat(TextFormat format, float fontSizeScale) + { + } + + virtual public void PrepareCharacters(string text) + { + } + + virtual public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + width = 0; + height = 0; + baseline = 0; + return false; + } + + virtual public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public int DrawLine(float x, float y, float width, int fontSize, int type, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public bool HasCharacter(char ch) + { + return false; + } + + virtual public int GetLineHeight(int size) + { + return 0; + } + + virtual public void Dispose() + { + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak new file mode 100644 index 0000000..6e1e11c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Base class for all kind of fonts. + /// + public class BaseFont + { + /// + /// The name of this font object. + /// + public string name; + + /// + /// The texture of this font object. + /// + public NTexture mainTexture; + + /// + /// Can this font be tinted? Will be true for dynamic font and fonts generated by BMFont. + /// + public bool canTint; + + /// + /// If true, it will use extra vertices to enhance bold effect + /// + public bool customBold; + + /// + /// If true, it will use extra vertices to enhance bold effect ONLY when it is in italic style. + /// + public bool customBoldAndItalic; + + /// + /// If true, it will use extra vertices(4 direction) to enhance outline effect + /// + public bool customOutline; + + /// + /// The shader for this font object. + /// + public string shader; + + /// + /// Keep text crisp. + /// + public bool keepCrisp; + + /// + /// + /// + public int version; + + protected internal static bool textRebuildFlag; + + protected const float SupScale = 0.58f; + protected const float SupOffset = 0.33f; + + virtual public void UpdateGraphics(NGraphics graphics) + { + } + + virtual public void SetFormat(TextFormat format, float fontSizeScale) + { + } + + virtual public void PrepareCharacters(string text) + { + } + + virtual public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + width = 0; + height = 0; + baseline = 0; + return false; + } + + virtual public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public int DrawLine(float x, float y, float width, int fontSize, int type, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public bool HasCharacter(char ch) + { + return false; + } + + virtual public int GetLineHeight(int size) + { + return 0; + } + + virtual public void Dispose() + { + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak.meta new file mode 100644 index 0000000..bc44271 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.bak.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 8150a8f2860ff4840bbac39815db2ba7 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.meta new file mode 100644 index 0000000..d4fa1c5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BaseFont.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 242acb07eafac7a43a60dc4107fbd6b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs new file mode 100644 index 0000000..76b480e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs @@ -0,0 +1,177 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class BitmapFont : BaseFont + { + /// + /// + /// + public class BMGlyph + { + public float x; + public float y; + public float width; + public float height; + public int advance; + public int lineHeight; + public Vector2[] uv = new Vector2[4]; + public int channel;//0-n/a, 1-r,2-g,3-b,4-alpha + } + + /// + /// + /// + public int size; + + /// + /// + /// + public bool resizable; + + /// + /// Font generated by BMFont use channels. + /// + public bool hasChannel; + + protected Dictionary _dict; + protected BMGlyph _glyph; + float _scale; + + public BitmapFont() + { + this.canTint = true; + this.hasChannel = false; + this.customOutline = true; + this.shader = ShaderConfig.bmFontShader; + + _dict = new Dictionary(); + _scale = 1; + } + + public void AddChar(char ch, BMGlyph glyph) + { + _dict[ch] = glyph; + } + + override public void SetFormat(TextFormat format, float fontSizeScale) + { + if (resizable) + _scale = (float)format.size / size * fontSizeScale; + else + _scale = fontSizeScale; + + if (canTint) + format.FillVertexColors(vertexColors); + } + + override public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + if (ch == ' ') + { + width = Mathf.RoundToInt(size * _scale / 2); + height = Mathf.RoundToInt(size * _scale); + baseline = height; + _glyph = null; + return true; + } + else if (_dict.TryGetValue((int)ch, out _glyph)) + { + width = Mathf.RoundToInt(_glyph.advance * _scale); + height = Mathf.RoundToInt(_glyph.lineHeight * _scale); + baseline = height; + return true; + } + else + { + width = 0; + height = 0; + baseline = 0; + return false; + } + } + + static Vector3 bottomLeft; + static Vector3 topLeft; + static Vector3 topRight; + static Vector3 bottomRight; + + static Color32[] vertexColors = new Color32[4]; + + override public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + if (_glyph == null) //space + return 0; + + topLeft.x = x + _glyph.x * _scale; + topLeft.y = y + (_glyph.lineHeight - _glyph.y) * _scale; + bottomRight.x = x + (_glyph.x + _glyph.width) * _scale; + bottomRight.y = topLeft.y - _glyph.height * _scale; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvList.AddRange(_glyph.uv); + + if (hasChannel) + { + Vector2 channel = new Vector2(_glyph.channel, 0); + uv2List.Add(channel); + uv2List.Add(channel); + uv2List.Add(channel); + uv2List.Add(channel); + } + + if (canTint) + { + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + else + { + colList.Add(Color.white); + colList.Add(Color.white); + colList.Add(Color.white); + colList.Add(Color.white); + } + + return 4; + } + + override public bool HasCharacter(char ch) + { + return ch == ' ' || _dict.ContainsKey((int)ch); + } + + override public int GetLineHeight(int size) + { + if (_dict.Count > 0) + { + using (var et = _dict.GetEnumerator()) + { + et.MoveNext(); + if (resizable) + return Mathf.RoundToInt((float)et.Current.Value.lineHeight * size / this.size); + else + return et.Current.Value.lineHeight; + } + } + else + return 0; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs.meta new file mode 100644 index 0000000..8aee67b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/BitmapFont.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b1441c09e3389a046827b23ee409a37a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs new file mode 100644 index 0000000..9144e93 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs @@ -0,0 +1,399 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class DynamicFont : BaseFont + { + Font _font; + int _size; + float _ascent; + float _lineHeight; + float _scale; + TextFormat _format; + FontStyle _style; + bool _boldVertice; + CharacterInfo _char; + CharacterInfo _lineChar; + bool _gotLineChar; + + public DynamicFont() + { + this.canTint = true; + this.keepCrisp = true; + this.customOutline = true; + this.shader = ShaderConfig.textShader; + } + + /// + /// + /// + /// + /// + /// + public DynamicFont(string name, Font font) : this() + { + this.name = name; + this.nativeFont = font; + + // [Y 修改] + this.realFontName = _font.name; + } + + /// + /// [Y 修改] + /// + public Font GetRealFont() + { + return _font; + } + + override public void Dispose() + { + Font.textureRebuilt -= textureRebuildCallback; + } + + public Font nativeFont + { + get { return _font; } + set + { + if (_font != null) + Font.textureRebuilt -= textureRebuildCallback; + + _font = value; + Font.textureRebuilt += textureRebuildCallback; + _font.hideFlags = DisplayObject.hideFlags; + _font.material.hideFlags = DisplayObject.hideFlags; + _font.material.mainTexture.hideFlags = DisplayObject.hideFlags; + + if (mainTexture != null) + mainTexture.Dispose(); + mainTexture = new NTexture(_font.material.mainTexture); + mainTexture.destroyMethod = DestroyMethod.None; + + // _ascent = _font.ascent; + // _lineHeight = _font.lineHeight; + _ascent = _font.fontSize; + _lineHeight = _font.fontSize * 1.25f; + } + } + + override public void SetFormat(TextFormat format, float fontSizeScale) + { + _format = format; + float size = format.size * fontSizeScale; + if (keepCrisp) + size *= UIContentScaler.scaleFactor; + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript || _format.specialStyle == TextFormat.SpecialStyle.Superscript) + size *= SupScale; + _size = Mathf.FloorToInt(size); + if (_size == 0) + _size = 1; + _scale = (float)_size / _font.fontSize; + + if (format.bold && !customBold) + { + if (format.italic) + { + if (customBoldAndItalic) + _style = FontStyle.Italic; + else + _style = FontStyle.BoldAndItalic; + } + else + _style = FontStyle.Bold; + } + else + { + if (format.italic) + _style = FontStyle.Italic; + else + _style = FontStyle.Normal; + } + + _boldVertice = format.bold && (customBold || (format.italic && customBoldAndItalic)); + format.FillVertexColors(vertexColors); + } + + override public void PrepareCharacters(string text) + { + _font.RequestCharactersInTexture(text, _size, _style); + } + + override public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + if (!_font.GetCharacterInfo(ch, out _char, _size, _style)) + { + if (ch == ' ') + { + //space may not be prepared, try again + _font.RequestCharactersInTexture(" ", _size, _style); + _font.GetCharacterInfo(ch, out _char, _size, _style); + } + else + { + width = height = baseline = 0; + return false; + } + } + + width = _char.advance; + height = _lineHeight * _scale; + baseline = _ascent * _scale; + if (_boldVertice) + width++; + + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) + { + height /= SupScale; + baseline /= SupScale; + } + else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) + { + height = height / SupScale + baseline * SupOffset; + baseline *= (SupOffset + 1 / SupScale); + } + + height = Mathf.RoundToInt(height); + baseline = Mathf.RoundToInt(baseline); + + if (keepCrisp) + { + width /= UIContentScaler.scaleFactor; + height /= UIContentScaler.scaleFactor; + baseline /= UIContentScaler.scaleFactor; + } + + return true; + } + + static Vector3 bottomLeft; + static Vector3 topLeft; + static Vector3 topRight; + static Vector3 bottomRight; + + static Vector2 uvBottomLeft; + static Vector2 uvTopLeft; + static Vector2 uvTopRight; + static Vector2 uvBottomRight; + + static Color32[] vertexColors = new Color32[4]; + + static Vector3[] BOLD_OFFSET = new Vector3[] + { + new Vector3(-0.5f, 0f, 0f), + new Vector3(0.5f, 0f, 0f), + new Vector3(0f, -0.5f, 0f), + new Vector3(0f, 0.5f, 0f) + }; + + override public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + topLeft.x = _char.minX; + topLeft.y = _char.maxY; + bottomRight.x = _char.maxX; + if (_char.glyphWidth == 0) //zero width, space etc + bottomRight.x = topLeft.x + _size / 2; + bottomRight.y = _char.minY; + + if (keepCrisp) + { + topLeft /= UIContentScaler.scaleFactor; + bottomRight /= UIContentScaler.scaleFactor; + } + + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) + y = y - Mathf.RoundToInt(_ascent * _scale * SupOffset); + else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) + y = y + Mathf.RoundToInt(_ascent * _scale * (1 / SupScale - 1 + SupOffset)); + + topLeft.x += x; + topLeft.y += y; + bottomRight.x += x; + bottomRight.y += y; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvBottomLeft = _char.uvBottomLeft; + uvTopLeft = _char.uvTopLeft; + uvTopRight = _char.uvTopRight; + uvBottomRight = _char.uvBottomRight; + + uvList.Add(uvBottomLeft); + uvList.Add(uvTopLeft); + uvList.Add(uvTopRight); + uvList.Add(uvBottomRight); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + + if (_boldVertice) + { + for (int b = 0; b < 4; b++) + { + Vector3 boldOffset = BOLD_OFFSET[b]; + + vertList.Add(bottomLeft + boldOffset); + vertList.Add(topLeft + boldOffset); + vertList.Add(topRight + boldOffset); + vertList.Add(bottomRight + boldOffset); + + uvList.Add(uvBottomLeft); + uvList.Add(uvTopLeft); + uvList.Add(uvTopRight); + uvList.Add(uvBottomRight); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + + return 20; + } + else + return 4; + } + + override public int DrawLine(float x, float y, float width, int fontSize, int type, + List vertList, List uvList, List uv2List, List colList) + { + if (!_gotLineChar) + { + _gotLineChar = true; + _font.RequestCharactersInTexture("_", 50, FontStyle.Normal); + _font.GetCharacterInfo('_', out _lineChar, 50, FontStyle.Normal); + } + + float thickness; + float offset; + + thickness = Mathf.Max(1, fontSize / 16f); //guest underline size + if (type == 0) + offset = Mathf.RoundToInt(_lineChar.minY * (float)fontSize / 50 + thickness); + else + offset = Mathf.RoundToInt(_ascent * 0.4f * fontSize / _font.fontSize); + if (thickness < 1) + thickness = 1; + + topLeft.x = x; + topLeft.y = y + offset; + bottomRight.x = x + width; + bottomRight.y = topLeft.y - thickness; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvBottomLeft = _lineChar.uvBottomLeft; + uvTopLeft = _lineChar.uvTopLeft; + uvTopRight = _lineChar.uvTopRight; + uvBottomRight = _lineChar.uvBottomRight; + + //取中点的UV + Vector2 u0; + if (_lineChar.uvBottomLeft.x != _lineChar.uvBottomRight.x) + u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvBottomRight.x) * 0.5f; + else + u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvTopLeft.x) * 0.5f; + + if (_lineChar.uvBottomLeft.y != _lineChar.uvTopLeft.y) + u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvTopLeft.y) * 0.5f; + else + u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvBottomRight.y) * 0.5f; + + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + + if (_boldVertice) + { + for (int b = 0; b < 4; b++) + { + Vector3 boldOffset = BOLD_OFFSET[b]; + + vertList.Add(bottomLeft + boldOffset); + vertList.Add(topLeft + boldOffset); + vertList.Add(topRight + boldOffset); + vertList.Add(bottomRight + boldOffset); + + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + + return 20; + } + else + return 4; + } + + override public bool HasCharacter(char ch) + { + return _font.HasCharacter(ch); + } + + override public int GetLineHeight(int size) + { + // if (_font == null) + // { + // return 1; + // } + return Mathf.RoundToInt(_lineHeight * size / _font.fontSize); + } + + void textureRebuildCallback(Font targetFont) + { + if (_font != targetFont) + return; + + if (mainTexture == null || !Application.isPlaying) + { + mainTexture = new NTexture(_font.material.mainTexture); + mainTexture.destroyMethod = DestroyMethod.None; + } + else + mainTexture.Reload(_font.material.mainTexture, null); + + _gotLineChar = false; + + textRebuildFlag = true; + version++; + + //Debug.Log("Font texture rebuild: " + name + "," + mainTexture.width + "," + mainTexture.height); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs.meta new file mode 100644 index 0000000..e92e117 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/DynamicFont.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37b73f8527098974cb0ccf518ff95351 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs new file mode 100644 index 0000000..fb8888f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs @@ -0,0 +1,45 @@ +namespace FairyGUI +{ + /// + /// + /// + public class Emoji + { + /// + /// 代表图片资源url。 + /// + public string url; + + /// + /// 图片宽度。不设置(0)则表示使用原始宽度。 + /// + public int width; + + /// + /// 图片高度。不设置(0)则表示使用原始高度。 + /// + public int height; + + /// + /// + /// + /// + /// + /// + public Emoji(string url, int width, int height) + { + this.url = url; + this.width = width; + this.height = height; + } + + /// + /// + /// + /// + public Emoji(string url) + { + this.url = url; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs.meta new file mode 100644 index 0000000..095aa0f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/Emoji.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3859ae9020061394cadacd1624e04ed9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs new file mode 100644 index 0000000..aa5d8ad --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class FontManager + { + public static Dictionary sFontFactory = new Dictionary(); + + /// + /// [Y 修改] + /// 获取字体工厂 + /// + public static Dictionary GetFontsInfo() + { + Dictionary fonts = new Dictionary(); + foreach (string key in sFontFactory.Keys) + { + fonts.Add(key, sFontFactory[key].realFontName); + } + + return fonts; + } + + /// + /// [Y 修改] + /// + /// + /// + static public void RegisterFont(BaseFont font, string alias = null) + { + if (!sFontFactory.ContainsKey(font.name)) + { + sFontFactory.Add(font.name, font); + } + + if (alias != null) + { + if (!sFontFactory.ContainsKey(alias)) + { + sFontFactory.Add(alias, font); + } + } + } + + /// + /// + /// + /// + static public void UnregisterFont(BaseFont font) + { + List toDelete = new List(); + foreach (KeyValuePair kv in sFontFactory) + { + if (kv.Value == font) + toDelete.Add(kv.Key); + } + + foreach (string key in toDelete) + sFontFactory.Remove(key); + } + + /// + /// + /// + /// + /// + static public BaseFont GetFont(string name) + { + BaseFont font; + if (name == null) + { + return null; + } + + if (name.StartsWith(UIPackage.URL_PREFIX)) + { + font = UIPackage.GetItemAssetByURL(name) as BaseFont; + if (font != null) + return font; + } + + if (sFontFactory.TryGetValue(name, out font)) + return font; + + object asset = Resources.Load(name); + if (asset == null) + asset = Resources.Load("Fonts/" + name); + + //Try to use new API in Uinty5 to load + if (asset == null) + { + if (name.IndexOf(",") != -1) + { + string[] arr = name.Split(','); + int cnt = arr.Length; + for (int i = 0; i < cnt; i++) + arr[i] = arr[i].Trim(); + asset = Font.CreateDynamicFontFromOSFont(arr, 16); + } + else + asset = Font.CreateDynamicFontFromOSFont(name, 16); + } + + if (asset == null) + return Fallback(name); + + if (asset is Font) + { + font = new DynamicFont(); + font.name = name; + sFontFactory.Add(name, font); + + ((DynamicFont)font).nativeFont = (Font)asset; + } + else + { + if (asset.GetType().Name.Contains("TMP_FontAsset")) + Debug.LogWarning("To enable TextMeshPro support, add script define symbol: FAIRYGUI_TMPRO"); + + return Fallback(name); + } + + return font; + } + + static BaseFont Fallback(string name) + { + if (name != UIConfig.defaultFont) + { + BaseFont ff; + if (sFontFactory.TryGetValue(UIConfig.defaultFont, out ff)) + { + sFontFactory[name] = ff; + return ff; + } + } + + Font asset = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); + if (asset == null) + throw new Exception("Failed to load font '" + name + "'"); + + BaseFont font = new DynamicFont(); + font.name = name; + ((DynamicFont)font).nativeFont = asset; + + sFontFactory.Add(name, font); + return font; + } + + /// + /// + /// + static public void Clear() + { + foreach (KeyValuePair kv in sFontFactory) + kv.Value.Dispose(); + + sFontFactory.Clear(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak new file mode 100644 index 0000000..c985223 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class FontManager + { + public static Dictionary sFontFactory = new Dictionary(); + + /// + /// + /// + /// + /// + static public void RegisterFont(BaseFont font, string alias = null) + { + sFontFactory[font.name] = font; + if (alias != null) + sFontFactory[alias] = font; + } + + /// + /// + /// + /// + static public void UnregisterFont(BaseFont font) + { + List toDelete = new List(); + foreach (KeyValuePair kv in sFontFactory) + { + if (kv.Value == font) + toDelete.Add(kv.Key); + } + + foreach (string key in toDelete) + sFontFactory.Remove(key); + } + + /// + /// + /// + /// + /// + static public BaseFont GetFont(string name) + { + BaseFont font; + if (name.StartsWith(UIPackage.URL_PREFIX)) + { + font = UIPackage.GetItemAssetByURL(name) as BaseFont; + if (font != null) + return font; + } + + if (sFontFactory.TryGetValue(name, out font)) + return font; + + object asset = Resources.Load(name); + if (asset == null) + asset = Resources.Load("Fonts/" + name); + + //Try to use new API in Uinty5 to load + if (asset == null) + { + if (name.IndexOf(",") != -1) + { + string[] arr = name.Split(','); + int cnt = arr.Length; + for (int i = 0; i < cnt; i++) + arr[i] = arr[i].Trim(); + asset = Font.CreateDynamicFontFromOSFont(arr, 16); + } + else + asset = Font.CreateDynamicFontFromOSFont(name, 16); + } + + if (asset == null) + return Fallback(name); + + if (asset is Font) + { + font = new DynamicFont(); + font.name = name; + sFontFactory.Add(name, font); + + ((DynamicFont)font).nativeFont = (Font)asset; + } +#if FAIRYGUI_TMPRO + else if (asset is TMPro.TMP_FontAsset) + { + font = new TMPFont(); + font.name = name; + sFontFactory.Add(name, font); + ((TMPFont)font).fontAsset = (TMPro.TMP_FontAsset)asset; + } +#endif + else + { + if (asset.GetType().Name.Contains("TMP_FontAsset")) + Debug.LogWarning("To enable TextMeshPro support, add script define symbol: FAIRYGUI_TMPRO"); + + return Fallback(name); + } + + return font; + } + + static BaseFont Fallback(string name) + { + if (name != UIConfig.defaultFont) + { + BaseFont ff; + if (sFontFactory.TryGetValue(UIConfig.defaultFont, out ff)) + { + sFontFactory[name] = ff; + return ff; + } + } + + Font asset = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); + if (asset == null) + throw new Exception("Failed to load font '" + name + "'"); + + BaseFont font = new DynamicFont(); + font.name = name; + ((DynamicFont)font).nativeFont = asset; + + sFontFactory.Add(name, font); + return font; + } + + /// + /// + /// + static public void Clear() + { + foreach (KeyValuePair kv in sFontFactory) + kv.Value.Dispose(); + + sFontFactory.Clear(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak.meta new file mode 100644 index 0000000..e63dc07 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.bak.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0e2e2644c5e765c44b1074fac1a1c226 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.meta new file mode 100644 index 0000000..20206e2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/FontManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5084c28e388b94a4fa4e2a80485296b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs new file mode 100644 index 0000000..88cacef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs @@ -0,0 +1,42 @@ +namespace FairyGUI +{ + /// + /// 用于文本输入的键盘接口 + /// + public interface IKeyboard + { + /// + /// 键盘已收回,输入已完成 + /// + bool done { get; } + + /// + /// 是否支持在光标处输入。如果为true,GetInput返回的是在当前光标处需要插入的文本,如果为false,GetInput返回的是整个文本。 + /// + bool supportsCaret { get; } + + /// + /// 用户输入的文本。 + /// + /// + string GetInput(); + + /// + /// 打开键盘 + /// + /// + /// + /// + /// + /// + /// + /// + /// + void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput); + + /// + /// 关闭键盘 + /// + void Close(); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs.meta new file mode 100644 index 0000000..bfcfd6b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/IKeyboard.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e3b9d951c903b049b8495c2d16f67fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs new file mode 100644 index 0000000..1666cfe --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs @@ -0,0 +1,1569 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// 接收用户输入的文本控件。因为支持直接输入表情,所以从RichTextField派生。 + /// + public class InputTextField : RichTextField + { + /// + /// + /// + public int maxLength { get; set; } + + /// + /// 如果是true,则当文本获得焦点时,弹出键盘进行输入,如果是false则不会。 + /// 默认是使用Stage.keyboardInput的值。 + /// + public bool keyboardInput { get; set; } + + /// + /// + /// + public int keyboardType { get; set; } + + /// + /// + /// + public bool hideInput { get; set; } + + /// + /// + /// + public bool disableIME { get; set; } + + /// + /// + /// + public bool mouseWheelEnabled { get; set; } + + /// + /// + /// + public static Action onCopy; + + /// + /// + /// + public static Action onPaste; + + /// + /// + /// + public static PopupMenu contextMenu; + + string _text; + string _restrict; + Regex _restrictPattern; + bool _displayAsPassword; + string _promptText; + string _decodedPromptText; + int _border; + int _corner; + Color _borderColor; + Color _backgroundColor; + bool _editable; + + bool _editing; + int _caretPosition; + int _selectionStart; + int _composing; + char _highSurrogateChar; + string _textBeforeEdit; + + EventListener _onChanged; + EventListener _onSubmit; + + Shape _caret; + SelectionShape _selectionShape; + float _nextBlink; + + const int GUTTER_X = 2; + const int GUTTER_Y = 2; + + public InputTextField() + { + gameObject.name = "InputTextField"; + + _text = string.Empty; + maxLength = 0; + _editable = true; + _composing = 0; + keyboardInput = Stage.keyboardInput; + _borderColor = Color.black; + _backgroundColor = Color.clear; + mouseWheelEnabled = true; + this.tabStop = true; + cursor = "text-ibeam"; + + /* 因为InputTextField定义了ClipRect,而ClipRect是四周缩进了2个像素的(GUTTER),默认的点击测试 + * 是使用ClipRect的,那会造成无法点击四周的空白区域。所以这里自定义了一个HitArea + */ + this.hitArea = new RectHitTest(); + this.touchChildren = false; + + onFocusIn.Add(__focusIn); + onFocusOut.AddCapture(__focusOut); + onKeyDown.Add(__keydown); + onTouchBegin.AddCapture(__touchBegin); + onTouchMove.AddCapture(__touchMove); + onMouseWheel.Add(__mouseWheel); + onClick.Add(__click); + onRightClick.Add(__rightClick); + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onSubmit + { + get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } + } + + /// + /// + /// + public override string text + { + get + { + return _text; + } + set + { + _text = value; + ClearSelection(); + UpdateText(); + } + } + + /// + /// + /// + public override TextFormat textFormat + { + get + { + return base.textFormat; + } + set + { + base.textFormat = value; + if (_editing) + { + _caret.height = textField.textFormat.size; + _caret.DrawRect(0, Color.clear, textField.textFormat.color); + } + } + } + + /// + /// + /// + public string restrict + { + get { return _restrict; } + set + { + _restrict = value; + if (string.IsNullOrEmpty(_restrict)) + _restrictPattern = null; + else + _restrictPattern = new Regex(value); + } + } + + /// + /// + /// + public int caretPosition + { + get + { + textField.Redraw(); + return _caretPosition; + } + set + { + SetSelection(value, 0); + } + } + + public int selectionBeginIndex + { + get { return _selectionStart < _caretPosition ? _selectionStart : _caretPosition; } + } + + public int selectionEndIndex + { + get { return _selectionStart < _caretPosition ? _caretPosition : _selectionStart; } + } + + /// + /// + /// + public string promptText + { + get + { + return _promptText; + } + set + { + _promptText = value; + if (!string.IsNullOrEmpty(_promptText)) + _decodedPromptText = UBBParser.inst.Parse(XMLUtils.EncodeString(_promptText)); + else + _decodedPromptText = null; + UpdateText(); + } + } + + /// + /// + /// + public bool displayAsPassword + { + get { return _displayAsPassword; } + set + { + if (_displayAsPassword != value) + { + _displayAsPassword = value; + UpdateText(); + } + } + } + + /// + /// + /// + public bool editable + { + get { return _editable; } + set + { + _editable = value; + if (_caret != null) + _caret.visible = _editable; + } + } + + /// + /// + /// + public int border + { + get { return _border; } + set + { + _border = value; + UpdateShape(); + } + } + + /// + /// + /// + public int corner + { + get { return _corner; } + set + { + _corner = value; + UpdateShape(); + } + } + + /// + /// + /// + public Color borderColor + { + get { return _borderColor; } + set + { + _borderColor = value; + UpdateShape(); + } + } + + /// + /// + /// + public Color backgroundColor + { + get { return _backgroundColor; } + set + { + _backgroundColor = value; + UpdateShape(); + } + } + + void UpdateShape() + { + if (_border > 0 || _backgroundColor.a > 0) + { + CreateGraphics(); + + graphics.enabled = true; + RoundedRectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = _border; + mesh.lineColor = _borderColor; + mesh.fillColor = _backgroundColor; + mesh.topLeftRadius = mesh.topRightRadius = mesh.bottomLeftRadius = mesh.bottomRightRadius = corner; + graphics.SetMeshDirty(); + } + else + { + if (graphics != null) + graphics.enabled = false; + } + } + + /// + /// + /// + /// + /// -1 means the rest count from start + public void SetSelection(int start, int length) + { + if (!_editing) + Stage.inst.focus = this; + + _selectionStart = start; + _caretPosition = length < 0 ? int.MaxValue : (start + length); + if (!textField.Redraw()) + { + int cnt = textField.charPositions.Count; + if (_caretPosition >= cnt) + _caretPosition = cnt - 1; + if (_selectionStart >= cnt) + _selectionStart = cnt - 1; + UpdateCaret(); + } + } + + /// + /// + /// + /// + public void ReplaceSelection(string value) + { + if (keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret) + { + this.text = _text + value; + OnChanged(); + return; + } + + if (!_editing) + Stage.inst.focus = this; + + textField.Redraw(); + + int t0, t1; + if (_selectionStart != _caretPosition) + { + if (_selectionStart < _caretPosition) + { + t0 = _selectionStart; + t1 = _caretPosition; + _caretPosition = _selectionStart; + } + else + { + t0 = _caretPosition; + t1 = _selectionStart; + _selectionStart = _caretPosition; + } + } + else + { + if (string.IsNullOrEmpty(value)) + return; + + t0 = t1 = _caretPosition; + } + + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, t0, buffer); + if (!string.IsNullOrEmpty(value)) + { + value = ValidateInput(value); + buffer.Append(value); + + _caretPosition += GetTextlength(value); + } + GetPartialText(t1 + _composing, -1, buffer); + + string newText = buffer.ToString(); + if (maxLength > 0) + { + string newText2 = TruncateText(newText, maxLength); + if (newText2.Length != newText.Length) + _caretPosition += (newText2.Length - newText.Length); + newText = newText2; + } + + this.text = newText; + OnChanged(); + } + + /// + /// + /// + /// + public void ReplaceText(string value) + { + if (value == _text) + return; + + if (value == null) + value = string.Empty; + + value = ValidateInput(value); + + if (maxLength > 0) + value = TruncateText(value, maxLength); + + _caretPosition = value.Length; + + this.text = value; + OnChanged(); + } + + void GetPartialText(int startIndex, int endIndex, StringBuilder buffer) + { + int elementCount = textField.htmlElements.Count; + int lastIndex = startIndex; + string tt; + if (_displayAsPassword) + tt = _text; + else + tt = textField.parsedText; + if (endIndex < 0) + endIndex = tt.Length; + for (int i = 0; i < elementCount; i++) + { + HtmlElement element = textField.htmlElements[i]; + if (element.htmlObject != null && element.text != null) + { + if (element.charIndex >= startIndex && element.charIndex < endIndex) + { + buffer.Append(tt.Substring(lastIndex, element.charIndex - lastIndex)); + buffer.Append(element.text); + lastIndex = element.charIndex + 1; + } + } + } + if (lastIndex < tt.Length) + buffer.Append(tt.Substring(lastIndex, endIndex - lastIndex)); + } + + int GetTextlength(string value) + { + int textLen = value.Length; + int ret = textLen; + for (int i = 0; i < textLen; i++) + { + if (char.IsHighSurrogate(value[i])) + ret--; + } + return ret; + } + + string TruncateText(string value, int length) + { + int textLen = value.Length; + int len = 0; + int i = 0; + while (i < textLen) + { + if (len == length) + return value.Substring(0, i); + + if (char.IsHighSurrogate(value[i])) + i++; + i++; + len++; + } + return value; + } + + string ValidateInput(string source) + { + if (_restrict != null) + { + StringBuilder sb = new StringBuilder(); + Match mc = _restrictPattern.Match(source); + int lastPos = 0; + string s; + while (mc != Match.Empty) + { + if (mc.Index != lastPos) + { + //保留tab和回车 + for (int i = lastPos; i < mc.Index; i++) + { + if (source[i] == '\n' || source[i] == '\t') + sb.Append(source[i]); + } + } + + s = mc.ToString(); + lastPos = mc.Index + s.Length; + sb.Append(s); + + mc = mc.NextMatch(); + } + for (int i = lastPos; i < source.Length; i++) + { + if (source[i] == '\n' || source[i] == '\t') + sb.Append(source[i]); + } + + return sb.ToString(); + } + else + return source; + } + + void UpdateText() + { + if (!_editing && _text.Length == 0 && !string.IsNullOrEmpty(_decodedPromptText)) + { + textField.htmlText = _decodedPromptText; + return; + } + + if (_displayAsPassword) + textField.text = EncodePasswordText(_text); + else + textField.text = _text; + + _composing = Input.compositionString.Length; + if (_composing > 0) + { + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, _caretPosition, buffer); + buffer.Append(Input.compositionString); + GetPartialText(_caretPosition, -1, buffer); + + textField.text = buffer.ToString(); + } + } + + string EncodePasswordText(string value) + { + int textLen = value.Length; + StringBuilder tmp = new StringBuilder(textLen); + int i = 0; + while (i < textLen) + { + char c = value[i]; + if (c == '\n') + tmp.Append(c); + else + { + if (char.IsHighSurrogate(c)) + i++; + tmp.Append("*"); + } + i++; + } + return tmp.ToString(); + } + + void ClearSelection() + { + if (_selectionStart != _caretPosition) + { + if (_selectionShape != null) + _selectionShape.Clear(); + _selectionStart = _caretPosition; + } + } + + public string GetSelection() + { + if (_selectionStart == _caretPosition) + return string.Empty; + + StringBuilder buffer = new StringBuilder(); + if (_selectionStart < _caretPosition) + GetPartialText(_selectionStart, _caretPosition, buffer); + else + GetPartialText(_caretPosition, _selectionStart, buffer); + return buffer.ToString(); + } + + void Scroll(int hScroll, int vScroll) + { + vScroll = Mathf.Clamp(vScroll, 0, textField.lines.Count - 1); + TextField.LineInfo line = textField.lines[vScroll]; + hScroll = Mathf.Clamp(hScroll, 0, line.charCount - 1); + + TextField.CharPosition cp = GetCharPosition(line.charIndex + hScroll); + Vector2 pt = GetCharLocation(cp); + MoveContent(new Vector2(GUTTER_X - pt.x, GUTTER_Y - pt.y), false); + } + + void AdjustCaret(TextField.CharPosition cp, bool moveSelectionHeader = false) + { + _caretPosition = cp.charIndex; + if (moveSelectionHeader) + _selectionStart = _caretPosition; + + UpdateCaret(); + } + + void UpdateCaret(bool forceUpdate = false) + { + TextField.CharPosition cp; + if (_editing) + cp = GetCharPosition(_caretPosition + Input.compositionString.Length); + else + cp = GetCharPosition(_caretPosition); + + Vector2 pos = GetCharLocation(cp); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + Vector2 offset = pos + textField.xy; + + if (offset.x < textField.textFormat.size) + offset.x += Mathf.Min(50, _contentRect.width * 0.5f); + else if (offset.x > _contentRect.width - GUTTER_X - textField.textFormat.size) + offset.x -= Mathf.Min(50, _contentRect.width * 0.5f); + + if (offset.x < GUTTER_X) + offset.x = GUTTER_X; + else if (offset.x > _contentRect.width - GUTTER_X) + offset.x = Mathf.Max(GUTTER_X, _contentRect.width - GUTTER_X); + + if (offset.y < GUTTER_Y) + offset.y = GUTTER_Y; + else if (offset.y + line.height >= _contentRect.height - GUTTER_Y) + offset.y = Mathf.Max(GUTTER_Y, _contentRect.height - line.height - GUTTER_Y); + + MoveContent(offset - pos, forceUpdate); + + if (_editing) + { + _caret.position = textField.xy + pos; + _caret.height = line.height > 0 ? line.height : textField.textFormat.size; + + if (_editable) + { + Vector2 cursorPos = _caret.LocalToWorld(new Vector2(0, _caret.height)); + cursorPos = StageCamera.main.WorldToScreenPoint(cursorPos); +#if !UNITY_2019_OR_NEWER + if (Stage.devicePixelRatio == 1) + { +#endif + cursorPos.y = Screen.height - cursorPos.y; + cursorPos = cursorPos / Stage.devicePixelRatio; + Input.compositionCursorPos = cursorPos + new Vector2(0, 20); +#if !UNITY_2019_OR_NEWER + } + else + Input.compositionCursorPos = cursorPos - new Vector2(0, 20); +#endif + } + + _nextBlink = Time.time + 0.5f; + _caret.graphics.enabled = true; + + UpdateSelection(cp); + } + } + + void MoveContent(Vector2 pos, bool forceUpdate) + { + float ox = textField.x; + float oy = textField.y; + float nx = pos.x; + float ny = pos.y; + float rectWidth = _contentRect.width - 1; //-1 to avoid cursor be clipped + if (rectWidth - nx > textField.textWidth) + nx = rectWidth - textField.textWidth; + if (_contentRect.height - ny > textField.textHeight) + ny = _contentRect.height - textField.textHeight; + if (nx > 0) + nx = 0; + if (ny > 0) + ny = 0; + nx = (int)nx; + ny = (int)ny; + + if (nx != ox || ny != oy || forceUpdate) + { + if (_caret != null) + { + _caret.SetXY(nx + _caret.x - ox, ny + _caret.y - oy); + _selectionShape.SetXY(nx, ny); + } + textField.SetXY(nx, ny); + + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + element.htmlObject.SetPosition(element.position.x + nx, element.position.y + ny); + } + } + } + + void UpdateSelection(TextField.CharPosition cp) + { + if (_selectionStart == _caretPosition) + { + _selectionShape.Clear(); + return; + } + + TextField.CharPosition start; + if (_editing && Input.compositionString.Length > 0) + { + if (_selectionStart < _caretPosition) + { + cp = GetCharPosition(_caretPosition); + start = GetCharPosition(_selectionStart); + } + else + start = GetCharPosition(_selectionStart + Input.compositionString.Length); + } + else + start = GetCharPosition(_selectionStart); + if (start.charIndex > cp.charIndex) + { + TextField.CharPosition tmp = start; + start = cp; + cp = tmp; + } + + Vector2 v1 = GetCharLocation(start); + Vector2 v2 = GetCharLocation(cp); + + _selectionShape.rects.Clear(); + textField.GetLinesShape(start.lineIndex, v1.x, cp.lineIndex, v2.x, false, _selectionShape.rects); + _selectionShape.Refresh(); + } + + TextField.CharPosition GetCharPosition(int caretIndex) + { + if (caretIndex < 0) + caretIndex = 0; + else if (caretIndex >= textField.charPositions.Count) + caretIndex = textField.charPositions.Count - 1; + + return textField.charPositions[caretIndex]; + } + + /// + /// 通过本地坐标获得字符索引位置 + /// + /// 本地坐标 + /// + TextField.CharPosition GetCharPosition(Vector2 location) + { + if (textField.charPositions.Count <= 1) + return textField.charPositions[0]; + + location.x -= textField.x; + location.y -= textField.y; + + List lines = textField.lines; + int len = lines.Count; + TextField.LineInfo line; + int i; + for (i = 0; i < len; i++) + { + line = lines[i]; + if (line.y + line.height > location.y) + break; + } + if (i == len) + i = len - 1; + + int lineIndex = i; + + len = textField.charPositions.Count; + TextField.CharPosition v; + int firstInLine = -1; + for (i = 0; i < len; i++) + { + v = textField.charPositions[i]; + if (v.lineIndex == lineIndex) + { + if (firstInLine == -1) + firstInLine = i; + if (v.offsetX + v.width * 0.5f > location.x) + return v; + } + else if (firstInLine != -1) + return v; + } + + return textField.charPositions[i - 1]; + } + + /// + /// 获得字符的坐标。 + /// + /// + /// + Vector2 GetCharLocation(TextField.CharPosition cp) + { + TextField.LineInfo line = textField.lines[cp.lineIndex]; + Vector2 pos; + if (line.charCount == 0 || textField.charPositions.Count == 0) + { + if (textField.align == AlignType.Center) + pos.x = (int)(_contentRect.width / 2); + else + pos.x = GUTTER_X; + } + else + { + TextField.CharPosition v = textField.charPositions[Math.Min(cp.charIndex, textField.charPositions.Count - 1)]; + pos.x = v.offsetX; + } + pos.y = line.y; + return pos; + } + + override internal void RefreshObjects() + { + base.RefreshObjects(); + + if (_editing) + { + SetChildIndex(_selectionShape, 0); + SetChildIndex(_caret, this.numChildren - 1); + } + + int cnt = textField.charPositions.Count; + if (_caretPosition >= cnt) + _caretPosition = cnt - 1; + if (_selectionStart >= cnt) + _selectionStart = cnt - 1; + + UpdateCaret(true); + } + + protected void OnChanged() + { + DispatchEvent("onChanged", null); + + TextInputHistory.inst.MarkChanged(this); + } + + protected override void OnSizeChanged() + { + base.OnSizeChanged(); + + Rect rect = _contentRect; + rect.x += GUTTER_X; + rect.y += GUTTER_Y; + rect.width -= GUTTER_X * 2; + rect.height -= GUTTER_Y * 2; + this.clipRect = rect; + ((RectHitTest)this.hitArea).rect = _contentRect; + } + + public override void Update(UpdateContext context) + { + base.Update(context); + + if (_editing) + { + if (_nextBlink < Time.time) + { + _nextBlink = Time.time + 0.5f; + _caret.graphics.enabled = !_caret.graphics.enabled; + } + } + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + _editing = false; + if (_caret != null) + { + _caret.Dispose(); + _selectionShape.Dispose(); + } + + base.Dispose(); + } + + void DoCopy(string value) + { + if (onCopy != null) + { + onCopy(this, value); + return; + } + +#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR + TextEditor textEditor = new TextEditor(); +#if UNITY_5_3_OR_NEWER + textEditor.text = value; +#else + textEditor.content = new GUIContent(value); +#endif + textEditor.OnFocus(); + textEditor.Copy(); +#endif + } + + void DoPaste() + { + if (onPaste != null) + { + onPaste(this); + return; + } + +#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR + TextEditor textEditor = new TextEditor(); +#if UNITY_5_3_OR_NEWER + textEditor.text = string.Empty; +#else + textEditor.content = new GUIContent(string.Empty); +#endif + textEditor.multiline = !textField.singleLine; + textEditor.Paste(); +#if UNITY_5_3_OR_NEWER + string value = textEditor.text; +#else + string value = textEditor.content.text; +#endif + if (!string.IsNullOrEmpty(value)) + ReplaceSelection(value); +#endif + } + + void CreateCaret() + { + _caret = new Shape(); + _caret.gameObject.name = "Caret"; + _caret.touchable = false; + _caret._flags |= Flags.SkipBatching; + _caret.xy = textField.xy; + + _selectionShape = new SelectionShape(); + _selectionShape.gameObject.name = "Selection"; + _selectionShape.color = UIConfig.inputHighlightColor; + _selectionShape._flags |= Flags.SkipBatching; + _selectionShape.touchable = false; + _selectionShape.xy = textField.xy; + } + + void __touchBegin(EventContext context) + { + if (!_editing || textField.charPositions.Count <= 1 + || keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret + || context.inputEvent.button != 0) + return; + + ClearSelection(); + + Vector3 v = Stage.inst.touchPosition; + v = this.GlobalToLocal(v); + TextField.CharPosition cp = GetCharPosition(v); + + AdjustCaret(cp, true); + + context.CaptureTouch(); + } + + void __touchMove(EventContext context) + { + if (!_editing) + return; + + Vector3 v = Stage.inst.touchPosition; + v = this.GlobalToLocal(v); + if (float.IsNaN(v.x)) + return; + + TextField.CharPosition cp = GetCharPosition(v); + if (cp.charIndex != _caretPosition) + AdjustCaret(cp); + } + + void __mouseWheel(EventContext context) + { + if (_editing && mouseWheelEnabled) + { + context.StopPropagation(); + + TextField.CharPosition cp = GetCharPosition(new Vector2(GUTTER_X, GUTTER_Y)); + int vScroll = cp.lineIndex; + int hScroll = cp.charIndex - textField.lines[cp.lineIndex].charIndex; + if (context.inputEvent.mouseWheelDelta < 0) + vScroll--; + else + vScroll++; + Scroll(hScroll, vScroll); + } + } + + void __focusIn(EventContext context) + { + if (!Application.isPlaying) + return; + + _editing = true; + _textBeforeEdit = _text; + + if (_caret == null) + CreateCaret(); + + if (!string.IsNullOrEmpty(_promptText)) + UpdateText(); + + float caretSize; + //如果界面缩小过,光标很容易看不见,这里放大一下 + if (UIConfig.inputCaretSize == 1 && UIContentScaler.scaleFactor < 1) + caretSize = UIConfig.inputCaretSize / UIContentScaler.scaleFactor; + else + caretSize = UIConfig.inputCaretSize; + _caret.SetSize(caretSize, textField.textFormat.size); + _caret.DrawRect(0, Color.clear, textField.textFormat.color); + _caret.visible = _editable; + AddChild(_caret); + + _selectionShape.Clear(); + AddChildAt(_selectionShape, 0); + + if (!textField.Redraw()) + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + AdjustCaret(cp); + } + + if (Stage.keyboardInput) + { + if (keyboardInput) + { + if (_editable) + Stage.inst.OpenKeyboard(_text, false, _displayAsPassword ? false : !textField.singleLine, + _displayAsPassword, false, null, keyboardType, hideInput); + + SetSelection(0, -1); + } + } + else + { + if (!disableIME && !_displayAsPassword) + Input.imeCompositionMode = IMECompositionMode.On; + else + Input.imeCompositionMode = IMECompositionMode.Off; + _composing = 0; + + if ((string)context.data == "key") //select all if got focus by tab key + SetSelection(0, -1); + + TextInputHistory.inst.StartRecord(this); + } + } + + void __focusOut(EventContext contxt) + { + if (!_editing) + return; + + _editing = false; + if (Stage.keyboardInput) + { + if (keyboardInput) + Stage.inst.CloseKeyboard(); + } + else + { + Input.imeCompositionMode = IMECompositionMode.Auto; + TextInputHistory.inst.StopRecord(this); + } + + if (!string.IsNullOrEmpty(_promptText)) + UpdateText(); + + _caret.RemoveFromParent(); + _selectionShape.RemoveFromParent(); + + if (contextMenu != null && contextMenu.contentPane.onStage) + contextMenu.Hide(); + } + + void __keydown(EventContext context) + { + if (!_editing) + return; + + if (HandleKey(context.inputEvent)) + context.StopPropagation(); + } + + bool HandleKey(InputEvent evt) + { + bool keyCodeHandled = true; + switch (evt.keyCode) + { + case KeyCode.Backspace: + { + if (evt.command) + { + //for mac:CMD+Backspace=Delete + if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) + _selectionStart = _caretPosition + 1; + } + else + { + if (_selectionStart == _caretPosition && _caretPosition > 0) + _selectionStart = _caretPosition - 1; + } + if (_editable) + ReplaceSelection(null); + break; + } + + case KeyCode.Delete: + { + if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) + _selectionStart = _caretPosition + 1; + if (_editable) + ReplaceSelection(null); + break; + } + + case KeyCode.LeftArrow: + { + if (!evt.shift) + ClearSelection(); + if (_caretPosition > 0) + { + if (evt.command) //mac keyboard + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + else + { + TextField.CharPosition cp = GetCharPosition(_caretPosition - 1); + AdjustCaret(cp, !evt.shift); + } + } + break; + } + + case KeyCode.RightArrow: + { + if (!evt.shift) + ClearSelection(); + if (_caretPosition < textField.charPositions.Count - 1) + { + if (evt.command) + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + else + { + TextField.CharPosition cp = GetCharPosition(_caretPosition + 1); + AdjustCaret(cp, !evt.shift); + } + } + break; + } + + case KeyCode.UpArrow: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + if (cp.lineIndex > 0) + { + TextField.LineInfo line = textField.lines[cp.lineIndex - 1]; + cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + break; + } + + case KeyCode.DownArrow: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + if (cp.lineIndex == textField.lines.Count - 1) + cp.charIndex = textField.charPositions.Count - 1; + else + { + TextField.LineInfo line = textField.lines[cp.lineIndex + 1]; + cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); + } + AdjustCaret(cp, !evt.shift); + break; + } + + case KeyCode.PageUp: + { + ClearSelection(); + break; + } + + case KeyCode.PageDown: + { + ClearSelection(); + break; + } + + case KeyCode.Home: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + break; + } + + case KeyCode.End: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + + break; + } + + //Select All + case KeyCode.A: + { + if (evt.ctrlOrCmd) + { + _selectionStart = 0; + AdjustCaret(GetCharPosition(int.MaxValue)); + } + break; + } + + //Copy + case KeyCode.C: + { + if (evt.ctrlOrCmd && !_displayAsPassword) + { + string s = GetSelection(); + if (!string.IsNullOrEmpty(s)) + DoCopy(s); + } + break; + } + + //Paste + case KeyCode.V: + { + if (evt.ctrlOrCmd && _editable) + DoPaste(); + break; + } + + //Cut + case KeyCode.X: + { + if (evt.ctrlOrCmd && !_displayAsPassword) + { + string s = GetSelection(); + if (!string.IsNullOrEmpty(s)) + { + DoCopy(s); + if (_editable) + ReplaceSelection(null); + } + } + break; + } + + case KeyCode.Z: + { + if (evt.ctrlOrCmd && _editable) + { + if (evt.shift) + TextInputHistory.inst.Redo(this); + else + TextInputHistory.inst.Undo(this); + } + break; + } + + case KeyCode.Y: + { + if (evt.ctrlOrCmd && _editable) + TextInputHistory.inst.Redo(this); + break; + } + + case KeyCode.Return: + case KeyCode.KeypadEnter: + { + if (textField.singleLine) + { + Stage.inst.focus = parent; + DispatchEvent("onSubmit", null); + DispatchEvent("onKeyDown", null); //for backward compatibility + } + break; + } + + case KeyCode.Tab: + { + if (textField.singleLine) + { + Stage.inst.DoKeyNavigate(evt.shift); + keyCodeHandled = false; + } + break; + } + + case KeyCode.Escape: + { + this.text = _textBeforeEdit; + Stage.inst.focus = parent; + break; + } + + default: + keyCodeHandled = (int)evt.keyCode <= 272 && !evt.ctrlOrCmd; + break; + } + + char c = evt.character; + if (c != 0) + { + if (evt.ctrlOrCmd) + return true; + + if (c == '\r' || c == 3) + c = '\n'; + + if (c == 25)/*shift+tab*/ + c = '\t'; + + if (c == 27/*escape*/ || textField.singleLine && (c == '\n' || c == '\t')) + return true; + + if (char.IsHighSurrogate(c)) + { + _highSurrogateChar = c; + return true; + } + + if (_editable) + { + if (char.IsLowSurrogate(c)) + ReplaceSelection(char.ConvertFromUtf32(((int)c & 0x03FF) + ((((int)_highSurrogateChar & 0x03FF) + 0x40) << 10))); + else + ReplaceSelection(c.ToString()); + } + + return true; + } + else + { + if (Input.compositionString.Length > 0 && _editable) + { + int composing = _composing; + _composing = Input.compositionString.Length; + + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, _caretPosition, buffer); + buffer.Append(Input.compositionString); + GetPartialText(_caretPosition + composing, -1, buffer); + + textField.text = buffer.ToString(); + } + + return keyCodeHandled; + } + } + + internal void CheckComposition() + { + if (_composing != 0 && Input.compositionString.Length == 0) + UpdateText(); + } + + void __click(EventContext context) + { + if (_editing && context.inputEvent.isDoubleClick) + { + context.StopPropagation(); + _selectionStart = 0; + AdjustCaret(GetCharPosition(int.MaxValue)); + } + } + + void __rightClick(EventContext context) + { + if (contextMenu != null) + { + context.StopPropagation(); + contextMenu.Show(); + } + } + } + + class TextInputHistory + { + static TextInputHistory _inst; + public static TextInputHistory inst + { + get + { + if (_inst == null) + _inst = new TextInputHistory(); + return _inst; + } + } + + List _undoBuffer; + List _redoBuffer; + string _currentText; + InputTextField _textField; + bool _lock; + int _changedFrame; + + public const int maxHistoryLength = 5; + + public TextInputHistory() + { + _undoBuffer = new List(); + _redoBuffer = new List(); + } + + public void StartRecord(InputTextField textField) + { + _undoBuffer.Clear(); + _redoBuffer.Clear(); + _textField = textField; + _lock = false; + _currentText = textField.text; + _changedFrame = 0; + } + + public void MarkChanged(InputTextField textField) + { + if (_textField != textField) + return; + + if (_lock) + return; + + string newText = _textField.text; + if (_currentText == newText) + return; + + if (_changedFrame != Time.frameCount) + { + _changedFrame = Time.frameCount; + _undoBuffer.Add(_currentText); + if (_undoBuffer.Count > maxHistoryLength) + _undoBuffer.RemoveAt(0); + } + else + { + int cnt = _undoBuffer.Count; + if (cnt > 0 && newText == _undoBuffer[cnt - 1]) + _undoBuffer.RemoveAt(cnt - 1); + } + _currentText = newText; + } + + public void StopRecord(InputTextField textField) + { + if (_textField != textField) + return; + + _undoBuffer.Clear(); + _redoBuffer.Clear(); + _textField = null; + _currentText = null; + } + + public void Undo(InputTextField textField) + { + if (_textField != textField) + return; + + if (_undoBuffer.Count == 0) + return; + + string text = _undoBuffer[_undoBuffer.Count - 1]; + _undoBuffer.RemoveAt(_undoBuffer.Count - 1); + _redoBuffer.Add(_currentText); + _lock = true; + int caretPos = _textField.caretPosition; + _textField.text = text; + int dlen = text.Length - _currentText.Length; + if (dlen < 0) + _textField.caretPosition = caretPos + dlen; + _currentText = text; + _lock = false; + } + + public void Redo(InputTextField textField) + { + if (_textField != textField) + return; + + if (_redoBuffer.Count == 0) + return; + + string text = _redoBuffer[_redoBuffer.Count - 1]; + _redoBuffer.RemoveAt(_redoBuffer.Count - 1); + _undoBuffer.Add(_currentText); + _lock = true; + int caretPos = _textField.caretPosition; + _textField.text = text; + int dlen = text.Length - _currentText.Length; + if (dlen > 0) + _textField.caretPosition = caretPos + dlen; + _currentText = text; + _lock = false; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs.meta new file mode 100644 index 0000000..6671067 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/InputTextField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87f693de944eb7d4ab4ccb9b65af352a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs new file mode 100644 index 0000000..ae0d5c9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs @@ -0,0 +1,700 @@ +/******************************************************************** + Copyright (c) 2018, Tadpole Studio + All rights reserved + + 文件名称: RTL.cs + 说 明: RTL字符转换 + + 版 本: 1.00 + 时 间: 2018/2/24 9:02:12 + 作 者: AQ QQ:355010366 + 概 述: 新建 + +*********************************************************************/ +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI +{ + public class RTLSupport + { + internal enum CharState + { + isolated, + final, + lead, + middle, + } + + // Bidirectional Character Types + public enum DirectionType + { + UNKNOW = 0, + LTR, + RTL, + NEUTRAL, + } + +#if RTL_TEXT_SUPPORT + public static DirectionType BaseDirection = DirectionType.RTL; // 主体语言是否是RTL的语言 +#else + public static DirectionType BaseDirection = DirectionType.UNKNOW; +#endif + private static bool isCharsInitialized = false; + private static Dictionary mapping = new Dictionary(); + + private static List listFinal = new List(); + private static List listRep = new List(); + private static StringBuilder sbRep = new StringBuilder(); + private static StringBuilder sbN = new StringBuilder(); + private static StringBuilder sbFinal = new StringBuilder(); + private static StringBuilder sbReverse = new StringBuilder(); + + public static bool IsArabicLetter(char ch) + { + if (ch >= 0x600 && ch <= 0x6ff) + { + if ((ch >= 0x660 && ch <= 0x66D) || (ch >= 0x6f0 && ch <= 0x6f9)) // 标准阿拉伯语数字和东阿拉伯语数字 [2019/3/1/ 17:45:18 by aq_1000] + { + return false; + } + return true; + } + else if (ch >= 0x750 && ch <= 0x77f) + return true; + else if (ch >= 0xfb50 && ch <= 0xfc3f) + return true; + else if (ch >= 0xfe70 && ch <= 0xfefc) + return true; + return false; + } + + public static string ConvertNumber(string strNumber) + { + sbRep.Length = 0; + foreach (char ch in strNumber) + { + int un = ch; + if (un == 0x66c || ch == ',') // 去掉逗号 + continue; + else if (un == 0x660 || un == 0x6f0) + sbRep.Append('0'); + else if (un == 0x661 || un == 0x6f1) + sbRep.Append('1'); + else if (un == 0x662 || un == 0x6f2) + sbRep.Append('2'); + else if (un == 0x663 || un == 0x6f3) + sbRep.Append('3'); + else if (un == 0x664 || un == 0x6f4) + sbRep.Append('4'); + else if (un == 0x665 || un == 0x6f5) + sbRep.Append('5'); + else if (un == 0x666 || un == 0x6f6) + sbRep.Append('6'); + else if (un == 0x667 || un == 0x6f7) + sbRep.Append('7'); + else if (un == 0x668 || un == 0x6f8) + sbRep.Append('8'); + else if (un == 0x669 || un == 0x6f9) + sbRep.Append('9'); + else + sbRep.Append(ch); + } + return sbRep.ToString(); + } + + public static bool ContainsArabicLetters(string text) + { + foreach (char character in text) + { + if (character >= 0x600 && character <= 0x6ff) + return true; + + if (character >= 0x750 && character <= 0x77f) + return true; + + if (character >= 0xfb50 && character <= 0xfc3f) + return true; + + if (character >= 0xfe70 && character <= 0xfefc) + return true; + } + return false; + } + + // 检测文本主方向 + public static DirectionType DetectTextDirection(string text) + { + bool isContainRTL = false; + bool isContainLTR = false; + foreach (char ch in text) + { + if (IsArabicLetter(ch)) + { + isContainRTL = true; + if (isContainLTR) + break; + } + else if (char.IsLetter(ch)) + { + isContainLTR = true; + if (isContainRTL) + break; + } + } + if (!isContainRTL) + return DirectionType.UNKNOW; // 这边unknow暂时代表文本一个RTL字符都没有,无需进行RTL转换 + else if (!isContainLTR) + return DirectionType.RTL; + return BaseDirection; + } + + private static bool CheckSeparator(char input) + { + if (!IsArabicLetter(input)) + { + return true; + } + else + { + return (input == '،') || (input == '?') || (input == '؟'); + } + + // if ((input != ' ') && (input != '\t') && (input != '!') && (input != '.') && + // (input != '،') && (input != '?') && (input != '؟') && + // !_IsBracket(input) && // 括号也算 [2018/8/1/ 15:12:20 by aq_1000] + // !_IsNeutrality(input)) + // { + // return false; + // } + // return true; + } + + private static bool CheckSpecific(char input) + { + int num = input; + if ((num != 0x622) && (num != 0x623) && (num != 0x627) && (num != 0x62f) && (num != 0x625) && + (num != 0x630) && (num != 0x631) && (num != 0x632) && (num != 0x698) && (num != 0x648) && + !_CheckSoundmark(input)) + { + return false; + } + return true; + } + + private static bool _CheckSoundmark(char ch) + { + int un = ch; + return (un >= 0x610 && un <= 0x61e) || (un >= 0x64b && un <= 0x65f); + } + + public static string DoMapping(string input) + { + if (!isCharsInitialized) + { + isCharsInitialized = true; + InitChars(); + } + + // 伊斯兰教真主安拉在阿拉伯文里写作الله + // 键盘输入时输入 ل (lam) + ل (lam) + ه (ha) 后会自动转换成带记号的符号。 [2018/3/13 20:03:45 --By aq_1000] + if (input == "الله") + { + input = "ﷲ"; + } + + sbFinal.Length = 0; + sbFinal.Append(input); + char perChar = '\0'; + for (int i = 0; i < sbFinal.Length; i++) + { + if (!mapping.ContainsKey(sbFinal[i])) + { + perChar = sbFinal[i]; + continue; + } + + if ((i + 1) == sbFinal.Length) + { + if (sbFinal.Length == 1) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; + } + } + else if (i == 0) + { + if (!CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + } + else if (CheckSeparator(sbFinal[i + 1])) + { + if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; + } + } + else if (CheckSeparator(perChar)) + { + if (CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + } + else if (CheckSpecific(sbFinal[i + 1])) + { + if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; + } + } + else if (CheckSpecific(perChar)) + { + if (CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; + } + } + return sbFinal.ToString(); + } + + // 主体语言是LTR + public static string ConvertLineL(string source) + { + listFinal.Clear(); + listRep.Clear(); + sbRep.Length = 0; + sbN.Length = 0; + int iReplace = 0; + DirectionType ePre = DirectionType.LTR; + char nextChar = '\0'; + for (int j = 0; j < source.Length; j++) + { + if (j < source.Length - 1) + nextChar = source[j + 1]; + else + nextChar = '\0'; + char item = source[j]; + DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.LTR); + if (eCType == DirectionType.RTL) + { + if (sbRep.Length == 0) + { + listFinal.Add('\x00bf'); + iReplace++; + } + + if (sbN.Length > 0) + sbRep.Append(sbN.ToString()); + sbN.Length = 0; + sbRep.Append(item); + } + else if (eCType == DirectionType.LTR) + { + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + sbRep.Length = 0; + + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + sbN.Length = 0; + + // item = _ProcessBracket(item); // 文本主方向为LTR的话,括号不需要翻转 [2018/12/20/ 17:03:23 by aq_1000] + listFinal.Add(item); + } + else + { + sbN.Append(item); + } + ePre = eCType; + } + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + + // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + + sbRep.Length = 0; + sbN.Length = 0; + sbFinal.Length = 0; + sbFinal.Append(listFinal.ToArray()); + for (int m = 0; m < iReplace; m++) + { + for (int n = 0; n < sbFinal.Length; n++) + { + if (sbFinal[n] == '\x00bf') + { + sbRep.Length = 0; + sbRep.Append(_Reverse(listRep[0])); + listRep.RemoveAt(0); + + // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] + sbN.Length = 0; + for (int num4 = 0; num4 < sbRep.Length; num4++) + { + if (!_IsNeutrality(sbRep[num4])) + break; + sbN.Append(sbRep[num4]); + } + if (sbN.Length > 0) // 词首空格重新放到词尾 + { + sbRep.Remove(0, sbN.Length); + for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 + { + sbRep.Append(sbN[iSpace]); + } + } + + sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); + break; + } + } + } + return sbFinal.ToString(); + } + + // 主体语言是RTL,整个文本就从右往左读,LTR语言就作为嵌入语段处理 + public static string ConvertLineR(string source) + { + listFinal.Clear(); + listRep.Clear(); + sbRep.Length = 0; + sbN.Length = 0; + int iReplace = 0; + DirectionType ePre = DirectionType.RTL; + char nextChar = '\0'; + for (int j = 0; j < source.Length; j++) + { + if (j < source.Length - 1) + nextChar = source[j + 1]; + else + nextChar = '\0'; + char item = source[j]; + DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.RTL); + if (eCType == DirectionType.LTR) + { + if (sbRep.Length == 0) + { + listFinal.Add('\x00bf'); + iReplace++; + } + + if (sbN.Length > 0) + sbRep.Append(sbN.ToString()); + sbN.Length = 0; + sbRep.Append(item); + } + else if (eCType == DirectionType.RTL) + { + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + sbRep.Length = 0; + + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + sbN.Length = 0; + + item = _ProcessBracket(item); + listFinal.Add(item); + } + else + { + sbN.Append(item); + } + ePre = eCType; + } + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + + // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + + sbFinal.Length = 0; + sbFinal.Append(listFinal.ToArray()); + for (int m = 0; m < iReplace; m++) + { + for (int n = 0; n < sbFinal.Length; n++) + { + if (sbFinal[n] == '\x00bf') + { + sbRep.Length = 0; + sbRep.Append(_Reverse(listRep[0])); + listRep.RemoveAt(0); + + // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] + sbN.Length = 0; + for (int num4 = 0; num4 < sbRep.Length; num4++) + { + if (!_IsNeutrality(sbRep[num4])) + break; + sbN.Append(sbRep[num4]); + } + if (sbN.Length > 0) // 词首空格重新放到词尾 + { + sbRep.Remove(0, sbN.Length); + for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 + { + sbRep.Append(sbN[iSpace]); + } + } + + sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); + break; + } + } + } + return sbFinal.ToString(); + } + + + private static string _Reverse(string source) + { + sbReverse.Length = 0; + int len = source.Length; + int i = len - 1; + while (i >= 0) + { + char ch = source[i]; + if (ch == '\r' && i != len - 1 && source[i + 1] == '\n') + { + i--; + continue; + } + + if (char.IsLowSurrogate(ch)) //不要反向高低代理对 + { + sbReverse.Append(source[i - 1]); + sbReverse.Append(ch); + i--; + } + else + sbReverse.Append(ch); + i--; + } + + return sbReverse.ToString(); + } + + private static void InitChars() + { + // {isolated,final,lead,middle} [2018/11/27 16:04:18 --By aq_1000] + mapping.Add(0x621, new char[4] { (char)0xFE80, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // Hamza + mapping.Add(0x627, new char[4] { (char)0xFE8D, (char)0xFE8E, (char)0xFE8D, (char)0xFE8E }); // Alef + mapping.Add(0x623, new char[4] { (char)0xFE83, (char)0xFE84, (char)0xFE83, (char)0xFE84 }); // AlefHamza + mapping.Add(0x624, new char[4] { (char)0xFE85, (char)0xFE85, (char)0xFE85, (char)0xFE85 }); // WawHamza + mapping.Add(0x625, new char[4] { (char)0xFE87, (char)0xFE87, (char)0xFE87, (char)0xFE87 }); // AlefMaksoor + mapping.Add(0x649, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); // AlefMagsora + mapping.Add(0x626, new char[4] { (char)0xFE89, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // HamzaNabera + mapping.Add(0x628, new char[4] { (char)0xFE8F, (char)0xFE90, (char)0xFE91, (char)0xFE92 }); // Ba + mapping.Add(0x62A, new char[4] { (char)0xFE95, (char)0xFE96, (char)0xFE97, (char)0xFE98 }); // Ta + mapping.Add(0x62B, new char[4] { (char)0xFE99, (char)0xFE9A, (char)0xFE9B, (char)0xFE9C }); // Tha2 + mapping.Add(0x62C, new char[4] { (char)0xFE9D, (char)0xFE9E, (char)0xFE9F, (char)0xFEA0 }); // Jeem + mapping.Add(0x62D, new char[4] { (char)0xFEA1, (char)0xFEA2, (char)0xFEA3, (char)0xFEA4 }); // H7aa + mapping.Add(0x62E, new char[4] { (char)0xFEA5, (char)0xFEA6, (char)0xFEA7, (char)0xFEA8 }); // Khaa2 + mapping.Add(0x62F, new char[4] { (char)0xFEA9, (char)0xFEAA, (char)0xFEA9, (char)0xFEAA }); // Dal + mapping.Add(0x630, new char[4] { (char)0xFEAB, (char)0xFEAC, (char)0xFEAB, (char)0xFEAC }); // Thal + mapping.Add(0x631, new char[4] { (char)0xFEAD, (char)0xFEAE, (char)0xFEAD, (char)0xFEAD }); // Ra2 + mapping.Add(0x632, new char[4] { (char)0xFEAF, (char)0xFEB0, (char)0xFEAF, (char)0xFEB0 }); // Zeen + mapping.Add(0x633, new char[4] { (char)0xFEB1, (char)0xFEB2, (char)0xFEB3, (char)0xFEB4 }); // Seen + mapping.Add(0x634, new char[4] { (char)0xFEB5, (char)0xFEB6, (char)0xFEB7, (char)0xFEB8 }); // Sheen + mapping.Add(0x635, new char[4] { (char)0xFEB9, (char)0xFEBA, (char)0xFEBB, (char)0xFEBC }); // S9a + mapping.Add(0x636, new char[4] { (char)0xFEBD, (char)0xFEBE, (char)0xFEBF, (char)0xFEC0 }); // Dha + mapping.Add(0x637, new char[4] { (char)0xFEC1, (char)0xFEC2, (char)0xFEC3, (char)0xFEC4 }); // T6a + mapping.Add(0x638, new char[4] { (char)0xFEC5, (char)0xFEC6, (char)0xFEC7, (char)0xFEC8 }); // T6ha + mapping.Add(0x639, new char[4] { (char)0xFEC9, (char)0xFECA, (char)0xFECB, (char)0xFECC }); // Ain + mapping.Add(0x63A, new char[4] { (char)0xFECD, (char)0xFECE, (char)0xFECF, (char)0xFED0 }); // Gain + mapping.Add(0x641, new char[4] { (char)0xFED1, (char)0xFED2, (char)0xFED3, (char)0xFED4 }); // Fa + mapping.Add(0x642, new char[4] { (char)0xFED5, (char)0xFED6, (char)0xFED7, (char)0xFED8 }); // Gaf + mapping.Add(0x643, new char[4] { (char)0xFED9, (char)0xFEDA, (char)0xFEDB, (char)0xFEDC }); // Kaf + mapping.Add(0x644, new char[4] { (char)0xFEDD, (char)0xFEDE, (char)0xFEDF, (char)0xFEE0 }); // Lam + mapping.Add(0x645, new char[4] { (char)0xFEE1, (char)0xFEE2, (char)0xFEE3, (char)0xFEE4 }); // Meem + mapping.Add(0x646, new char[4] { (char)0xFEE5, (char)0xFEE6, (char)0xFEE7, (char)0xFEE8 }); // Noon + mapping.Add(0x647, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); // Ha + mapping.Add(0x648, new char[4] { (char)0xFEED, (char)0xFEEE, (char)0xFEED, (char)0xFEEE }); // Waw + mapping.Add(0x64A, new char[4] { (char)0xFEF1, (char)0xFEF2, (char)0xFEF3, (char)0xFEF4 }); // Ya + mapping.Add(0x622, new char[4] { (char)0xFE81, (char)0xFE81, (char)0xFE81, (char)0xFE81 }); // AlefMad + mapping.Add(0x629, new char[4] { (char)0xFE93, (char)0xFE94, (char)0xFE94, (char)0xFE94 }); // TaMarboota // 该字符只会出现在末尾 [2018/4/10 16:04:18 --By aq_1000] + mapping.Add(0x67E, new char[4] { (char)0xFB56, (char)0xFB57, (char)0xFB58, (char)0xFB59 }); // PersianPe + mapping.Add(0x686, new char[4] { (char)0xFB7A, (char)0xFB7B, (char)0xFB7C, (char)0xFB7D }); // PersianChe + mapping.Add(0x698, new char[4] { (char)0xFB8A, (char)0xFB8B, (char)0xFB8A, (char)0xFB8B }); // PersianZe + mapping.Add(0x6AF, new char[4] { (char)0xFB92, (char)0xFB93, (char)0xFB94, (char)0xFB95 }); // PersianGaf + mapping.Add(0x6A9, new char[4] { (char)0xFB8E, (char)0xFB8F, (char)0xFB90, (char)0xFB91 }); // PersianGaf2 + + mapping.Add(0x6BE, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); + mapping.Add(0x6CC, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); + } + + // 是否中立方向字符 + private static bool _IsNeutrality(char uc) + { + return (uc == ':' || uc == ':' || uc == ' ' || /*uc == '%' ||*/ /*uc == '+' ||*/ /*uc == '-' ||*/ uc == '\n' || uc == '\r' || uc == '\t' || uc == '@' || + (uc >= 0x2600 && uc <= 0x27BF)); // 表情符号 + } + + // 是否句末标点符号 + private static bool _IsEndPunctuation(char uc, char nextChar) + { + if (uc == '.') + return _IsNeutrality(nextChar); + return (uc == '!' || uc == '!' || uc == '。' || uc == '،' || uc == '?' || uc == '؟'); + } + + // 判断字符方向 + private static DirectionType _GetDirection(char uc, char nextChar, DirectionType ePre, DirectionType eBase) + { + DirectionType eCType = ePre; + int uni = uc; + + if (_IsBracket(uc) || _IsEndPunctuation(uc, nextChar)) + { + eCType = eBase; // 括号和句末标点符号,方向根据上个字符为准 [2018/12/26/ 15:56:24 by aq_1000] + } + else if ((uni >= 0x660) && (uni <= 0x66D)) + { + eCType = DirectionType.LTR; + } + else if (IsArabicLetter(uc) || uc == '+' /*|| uc == '-'*/ || uc == '%') + { + eCType = DirectionType.RTL; + } + else if (uc == '-') + { + if (char.IsNumber(nextChar)) + eCType = DirectionType.LTR; + else + eCType = DirectionType.RTL; + } + else if (_IsNeutrality(uc)) // 中立方向字符,方向就和上一个字符一样 [2018/3/24 16:03:27 --By aq_1000] + { + if (ePre == DirectionType.UNKNOW || ePre == DirectionType.NEUTRAL) + { + if (char.IsNumber(nextChar)) // 数字都是弱LTR方向符,开头中立字符后面紧跟着数字的话,中立字符方向算文本主方向 [IsDigit()只是0-9] [2018/12/20/ 16:32:32 by aq_1000] + { + eCType = BaseDirection; + } + else + eCType = DirectionType.NEUTRAL; + } + else + eCType = ePre; + } + else + eCType = DirectionType.LTR; + + return eCType; + } + + // 是否括号 + private static bool _IsBracket(char uc) + { + return (uc == ')' || uc == '(' || uc == ')' || uc == '(' || + uc == ']' || uc == '[' || uc == '】' || uc == '【' || + uc == '}' || uc == '{' || + // uc == '≥' || uc == '≤' || uc == '>' || uc == '<' || + uc == '》' || uc == '《' || uc == '“' || uc == '”' || uc == '"'); + } + + // 这些配对符,在从右至左排列中应该逆序显示 + private static char _ProcessBracket(char uc) + { + if (uc == '[') return ']'; + else if (uc == ']') return '['; + else if (uc == '【') return '】'; + else if (uc == '】') return '【'; + else if (uc == '{') return '}'; + else if (uc == '}') return '{'; + else if (uc == '(') return ')'; + else if (uc == ')') return '('; + else if (uc == '(') return ')'; + else if (uc == ')') return '('; + else if (uc == '<') return '>'; + else if (uc == '>') return '<'; + else if (uc == '《') return '》'; + else if (uc == '》') return '《'; + else if (uc == '≤') return '≥'; + else if (uc == '≥') return '≤'; + else if (uc == '”') return '“'; + else if (uc == '”') return '“'; + else return uc; + } + } +} + diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs.meta new file mode 100644 index 0000000..2d4c593 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RTLSupport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 575b3af943ee8a04bb4d8feb568b1d2e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs new file mode 100644 index 0000000..1b3a6ef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs @@ -0,0 +1,216 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class RichTextField : Container + { + /// + /// + /// + public IHtmlPageContext htmlPageContext { get; set; } + + /// + /// + /// + public HtmlParseOptions htmlParseOptions { get; private set; } + + /// + /// + /// + public Dictionary emojies { get; set; } + + /// + /// + /// + public TextField textField { get; private set; } + + public RichTextField() + { + gameObject.name = "RichTextField"; + this.opaque = true; + + htmlPageContext = HtmlPageContext.inst; + htmlParseOptions = new HtmlParseOptions(); + + this.textField = new TextField(); + textField.EnableRichSupport(this); + AddChild(textField); + } + + /// + /// + /// + virtual public string text + { + get { return textField.text; } + set { textField.text = value; } + } + + /// + /// + /// + virtual public string htmlText + { + get { return textField.htmlText; } + set { textField.htmlText = value; } + } + + /// + /// + /// + virtual public TextFormat textFormat + { + get { return textField.textFormat; } + set { textField.textFormat = value; } + } + + /// + /// + /// + /// + /// + public HtmlElement GetHtmlElement(string name) + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (name.Equals(element.name, System.StringComparison.OrdinalIgnoreCase)) + return element; + } + + return null; + } + + /// + /// + /// + /// + /// + public HtmlElement GetHtmlElementAt(int index) + { + return textField.htmlElements[index]; + } + + /// + /// + /// + public int htmlElementCount + { + get { return textField.htmlElements.Count; } + } + + /// + /// + /// + /// + /// + public void ShowHtmlObject(int index, bool show) + { + HtmlElement element = textField.htmlElements[index]; + if (element.htmlObject != null && element.type != HtmlElementType.Link) + { + //set hidden flag + if (show) + element.status &= 253; //~(1<<1) + else + element.status |= 2; + + if ((element.status & 3) == 0) //not (hidden and clipped) + { + if ((element.status & 4) == 0) //not added + { + element.status |= 4; + element.htmlObject.Add(); + } + } + else + { + if ((element.status & 4) != 0) //added + { + element.status &= 251; + element.htmlObject.Remove(); + } + } + } + } + + public override void EnsureSizeCorrect() + { + textField.EnsureSizeCorrect(); + } + + override protected void OnSizeChanged() + { + textField.size = _contentRect.size; //千万不可以调用this.size,后者会触发EnsureSizeCorrect + + base.OnSizeChanged(); + } + + public override void Update(UpdateContext context) + { + textField.Redraw(); + + base.Update(context); + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + CleanupObjects(); + + base.Dispose(); + } + + internal void CleanupObjects() + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + { + element.htmlObject.Remove(); + htmlPageContext.FreeObject(element.htmlObject); + } + } + } + + virtual internal void RefreshObjects() + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + { + if ((element.status & 3) == 0) //not (hidden and clipped) + { + if ((element.status & 4) == 0) //not added + { + element.status |= 4; + element.htmlObject.Add(); + } + } + else + { + if ((element.status & 4) != 0) //added + { + element.status &= 251; + element.htmlObject.Remove(); + } + } + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs.meta new file mode 100644 index 0000000..674eafb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/RichTextField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87b472f7ce488fa4bbd8942342458ccf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs new file mode 100644 index 0000000..2ae0c34 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class SelectionShape : DisplayObject, IMeshFactory + { + public readonly List rects; + + public SelectionShape() + { + CreateGameObject("SelectionShape"); + graphics = new NGraphics(gameObject); + graphics.texture = NTexture.Empty; + graphics.meshFactory = this; + + rects = new List(); + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.Tint(); + } + } + + public void Refresh() + { + int count = rects.Count; + if (count > 0) + { + Rect rect = new Rect(); + rect = rects[0]; + Rect tmp; + for (int i = 1; i < count; i++) + { + tmp = rects[i]; + rect = ToolSet.Union(ref rect, ref tmp); + } + SetSize(rect.xMax, rect.yMax); + } + else + SetSize(0, 0); + graphics.SetMeshDirty(); + } + + public void Clear() + { + rects.Clear(); + graphics.SetMeshDirty(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int count = rects.Count; + if (count == 0 || this.color == Color.clear) + return; + + for (int i = 0; i < count; i++) + vb.AddQuad(rects[i]); + vb.AddTriangles(); + } + + protected override DisplayObject HitTest() + { + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + + if (_contentRect.Contains(localPoint)) + { + int count = rects.Count; + for (int i = 0; i < count; i++) + { + if (rects[i].Contains(localPoint)) + return this; + } + } + + return null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs.meta new file mode 100644 index 0000000..7dbb0f2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/SelectionShape.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f1920b8ccf9c8b4ca5f2794991735d9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs new file mode 100644 index 0000000..40873a1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs @@ -0,0 +1,1757 @@ +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class TextField : DisplayObject, IMeshFactory + { + VertAlignType _verticalAlign; + TextFormat _textFormat; + bool _input; + string _text; + AutoSizeType _autoSize; + bool _wordWrap; + bool _singleLine; + bool _html; + RTLSupport.DirectionType _textDirection; + int _maxWidth; + + List _elements; + List _lines; + List _charPositions; + + BaseFont _font; + float _textWidth; + float _textHeight; + bool _textChanged; + float _yOffset; + float _fontSizeScale; + float _renderScale; + int _fontVersion; + string _parsedText; + int _ellipsisCharIndex; + + RichTextField _richTextField; + + const int GUTTER_X = 2; + const int GUTTER_Y = 2; + const float IMAGE_BASELINE = 0.8f; + const int ELLIPSIS_LENGTH = 2; + + static float[] STROKE_OFFSET = new float[] + { + -1, 0, 1, 0, + 0, -1, 0, 1, + -1, -1, 1, -1, + -1, 1, 1, 1 + }; + + static List sLineChars = new List(); + + public TextField() + { + _flags |= Flags.TouchDisabled; + + _textFormat = new TextFormat(); + _fontSizeScale = 1; + _renderScale = UIContentScaler.scaleFactor; + + _wordWrap = false; + _text = string.Empty; + _parsedText = string.Empty; + + _elements = new List(0); + _lines = new List(1); + + CreateGameObject("TextField"); + graphics = new NGraphics(gameObject); + graphics.meshFactory = this; + } + + internal void EnableRichSupport(RichTextField richTextField) + { + _richTextField = richTextField; + if (richTextField is InputTextField) + { + _input = true; + EnableCharPositionSupport(); + } + } + + public void EnableCharPositionSupport() + { + if (_charPositions == null) + { + _charPositions = new List(); + _textChanged = true; + } + } + + /// + /// + /// + public TextFormat textFormat + { + get { return _textFormat; } + set + { + _textFormat = value; + ApplyFormat(); + } + } + + /// + /// + /// + public void ApplyFormat() + { + string fontName = _textFormat.font; + if (string.IsNullOrEmpty(fontName)) + { + fontName = UIConfig.defaultFont; + } + + if (fontName == null) + { + return; + } + + BaseFont newFont = FontManager.GetFont(fontName); + if (_font != newFont) + { + _font = newFont; + _fontVersion = _font.version; + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + } + + if (!string.IsNullOrEmpty(_text)) + _textChanged = true; + } + + /// + /// + /// + public AlignType align + { + get { return _textFormat.align; } + set + { + if (_textFormat.align != value) + { + _textFormat.align = value; + if (!string.IsNullOrEmpty(_text)) + _textChanged = true; + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + if (!_textChanged) + ApplyVertAlign(); + } + } + } + + /// + /// + /// + public string text + { + get { return _text; } + set + { + if (_text == value && !_html) + return; + + _text = value; + _textChanged = true; + _html = false; + } + } + + /// + /// + /// + public string htmlText + { + get { return _text; } + set + { + if (_text == value && _html) + return; + + _text = value; + _textChanged = true; + _html = true; + } + } + + public string parsedText + { + get { return _parsedText; } + } + + /// + /// + /// + public AutoSizeType autoSize + { + get { return _autoSize; } + set + { + if (_autoSize != value) + { + _autoSize = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public bool wordWrap + { + get { return _wordWrap; } + set + { + if (_wordWrap != value) + { + _wordWrap = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public bool singleLine + { + get { return _singleLine; } + set + { + if (_singleLine != value) + { + _singleLine = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public float stroke + { + get { return _textFormat.outline; } + set + { + if (_textFormat.outline != value) + { + _textFormat.outline = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Color strokeColor + { + get { return _textFormat.outlineColor; } + set + { + if (_textFormat.outlineColor != value) + { + _textFormat.outlineColor = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Vector2 shadowOffset + { + get { return _textFormat.shadowOffset; } + set + { + _textFormat.shadowOffset = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public float textWidth + { + get + { + if (_textChanged) + BuildLines(); + + return _textWidth; + } + } + + /// + /// + /// + public float textHeight + { + get + { + if (_textChanged) + BuildLines(); + + return _textHeight; + } + } + + /// + /// + /// + public int maxWidth + { + get { return _maxWidth; } + set + { + if (_maxWidth != value) + { + _maxWidth = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public List htmlElements + { + get + { + if (_textChanged) + BuildLines(); + + return _elements; + } + } + + /// + /// + /// + public List lines + { + get + { + if (_textChanged) + BuildLines(); + + return _lines; + } + } + + /// + /// + /// + public List charPositions + { + get + { + if (_textChanged) + BuildLines(); + + graphics.UpdateMesh(); + + return _charPositions; + } + } + + /// + /// + /// + public RichTextField richTextField + { + get { return _richTextField; } + } + + /// + /// + /// + public bool Redraw() + { + if (_font == null) + { + _font = FontManager.GetFont(UIConfig.defaultFont); + if (_font == null) + { + _font = FontManager.GetFont("Arial"); + } + + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + _fontVersion = _font.version; + _textChanged = true; + } + + if (_font.keepCrisp && _renderScale != UIContentScaler.scaleFactor) + _textChanged = true; + + if (_font.version != _fontVersion) + { + _fontVersion = _font.version; + if (_font.mainTexture != graphics.texture) + { + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + InvalidateBatchingState(); + } + + _textChanged = true; + } + + if (_textChanged) + BuildLines(); + + return graphics.UpdateMesh(); + } + + /// + /// + /// + public bool HasCharacter(char ch) + { + return _font.HasCharacter(ch); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void GetLinesShape(int startLine, float startCharX, int endLine, float endCharX, + bool clipped, + List resultRects) + { + LineInfo line1 = _lines[startLine]; + LineInfo line2 = _lines[endLine]; + bool leftAlign = _textFormat.align == AlignType.Left; + if (startLine == endLine) + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, endCharX, line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + else if (startLine == endLine - 1) + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, + line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + r = Rect.MinMaxRect(GUTTER_X, line1.y + line1.height, endCharX, line2.y + line2.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + else + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, + line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + for (int i = startLine + 1; i < endLine; i++) + { + LineInfo line = _lines[i]; + r = Rect.MinMaxRect(GUTTER_X, r.yMax, leftAlign ? (GUTTER_X + line.width) : _contentRect.xMax, + line.y + line.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + + r = Rect.MinMaxRect(GUTTER_X, r.yMax, endCharX, line2.y + line2.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + } + + override protected void OnSizeChanged() + { + if ((_flags & Flags.UpdatingSize) == 0) + { + if (_autoSize == AutoSizeType.Shrink || _autoSize == AutoSizeType.Ellipsis || + _wordWrap && (_flags & Flags.WidthChanged) != 0) + _textChanged = true; + else if (_autoSize != AutoSizeType.None) + graphics.SetMeshDirty(); + + if (_verticalAlign != VertAlignType.Top) + ApplyVertAlign(); + } + + base.OnSizeChanged(); + } + + public override void EnsureSizeCorrect() + { + if (_textChanged && _autoSize != AutoSizeType.None) + BuildLines(); + } + + public override void Update(UpdateContext context) + { + if (_richTextField == null) //如果是richTextField,会在update前主动调用了Redraw + Redraw(); + + base.Update(context); + } + + /// + /// 准备字体纹理 + /// + void RequestText() + { + if (!_html) + { + _font.SetFormat(_textFormat, _fontSizeScale); + _font.PrepareCharacters(_parsedText); + if (_autoSize == AutoSizeType.Ellipsis) + _font.PrepareCharacters("…"); + } + else + { + int count = _elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = _elements[i]; + if (element.type == HtmlElementType.Text) + { + _font.SetFormat(element.format, _fontSizeScale); + _font.PrepareCharacters(element.text); + if (_autoSize == AutoSizeType.Ellipsis) + _font.PrepareCharacters("…"); + } + } + } + } + + void BuildLines() + { + if (_font == null) + { + _font = FontManager.GetFont(UIConfig.defaultFont); + if (_font == null) + { + _font = FontManager.GetFont("Arial"); + } + _fontVersion = _font.version; + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + } + + _textChanged = false; + graphics.SetMeshDirty(); + _renderScale = UIContentScaler.scaleFactor; + _fontSizeScale = 1; + _ellipsisCharIndex = -1; + + Cleanup(); + + if (_text.Length == 0) + { + LineInfo emptyLine = LineInfo.Borrow(); + emptyLine.width = 0; + emptyLine.height = _font.GetLineHeight(_textFormat.size); + emptyLine.charIndex = emptyLine.charCount = 0; + emptyLine.y = emptyLine.y2 = GUTTER_Y; + _lines.Add(emptyLine); + + _textWidth = _textHeight = 0; + } + else + { + ParseText(); + BuildLines2(); + + if (_autoSize == AutoSizeType.Shrink) + DoShrink(); + } + + if (_autoSize == AutoSizeType.Both) + { + _flags |= Flags.UpdatingSize; + if (_richTextField != null) + { + if (_input) + { + float w = Mathf.Max(_textFormat.size, _textWidth); + float h = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, _textHeight); + _richTextField.SetSize(w, h); + } + else + _richTextField.SetSize(_textWidth, _textHeight); + } + else + SetSize(_textWidth, _textHeight); + + InvalidateBatchingState(); + _flags &= ~Flags.UpdatingSize; + } + else if (_autoSize == AutoSizeType.Height) + { + _flags |= Flags.UpdatingSize; + if (_richTextField != null) + { + if (_input) + _richTextField.height = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, + _textHeight); + else + _richTextField.height = _textHeight; + } + else + this.height = _textHeight; + + InvalidateBatchingState(); + _flags &= ~Flags.UpdatingSize; + } + + _yOffset = 0; + ApplyVertAlign(); + } + + void ParseText() + { +#if RTL_TEXT_SUPPORT + _textDirection = RTLSupport.DetectTextDirection(_text); +#endif + if (_html) + { + HtmlParser.inst.Parse(_text, _textFormat, _elements, + _richTextField != null ? _richTextField.htmlParseOptions : null); + + _parsedText = string.Empty; + } + else + _parsedText = _text; + + int elementCount = _elements.Count; + if (elementCount == 0) + { + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + _parsedText = RTLSupport.DoMapping(_parsedText); + + bool flag = _input || _richTextField != null && _richTextField.emojies != null; + if (!flag) + { + //检查文本中是否有需要转换的字符,如果没有,节省一个new StringBuilder的操作。 + int cnt = _parsedText.Length; + for (int i = 0; i < cnt; i++) + { + char ch = _parsedText[i]; + if (ch == '\r' || char.IsHighSurrogate(ch)) + { + flag = true; + break; + } + } + } + + if (flag) + { + StringBuilder buffer = new StringBuilder(); + ParseText(buffer, _parsedText, -1); + elementCount = _elements.Count; + _parsedText = buffer.ToString(); + } + } + else + { + StringBuilder buffer = new StringBuilder(); + int i = 0; + while (i < elementCount) + { + HtmlElement element = _elements[i]; + element.charIndex = buffer.Length; + if (element.type == HtmlElementType.Text) + { + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + element.text = RTLSupport.DoMapping(element.text); + + i = ParseText(buffer, element.text, i); + elementCount = _elements.Count; + } + else if (element.isEntity) + buffer.Append(' '); + + i++; + } + + _parsedText = buffer.ToString(); + +#if RTL_TEXT_SUPPORT + // element.text拼接完后再进行一次判断文本主语序,避免html标签存在把文本变成混合文本 [2018/12/12/ 16:47:42 by aq_1000] + _textDirection = RTLSupport.DetectTextDirection(_parsedText); +#endif + } + } + + void BuildLines2() + { + float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; + float lineSpacing = (_textFormat.lineSpacing - 1) * _fontSizeScale; + float rectWidth = _contentRect.width - GUTTER_X * 2; + float rectHeight = _contentRect.height > 0 + ? Mathf.Max(_contentRect.height, _font.GetLineHeight(_textFormat.size)) + : 0; + float glyphWidth = 0, glyphHeight = 0, baseline = 0; + short wordLen = 0; + bool wordPossible = false; + float posx = 0; + bool checkEdge = _autoSize == AutoSizeType.Ellipsis; + + TextFormat format = _textFormat; + _font.SetFormat(format, _fontSizeScale); + bool wrap = _wordWrap && !_singleLine; + if (_maxWidth > 0) + { + wrap = true; + rectWidth = _maxWidth - GUTTER_X * 2; + } + + _textWidth = _textHeight = 0; + + RequestText(); + + int elementCount = _elements.Count; + int elementIndex = 0; + HtmlElement element = null; + if (elementCount > 0) + element = _elements[elementIndex]; + int textLength = _parsedText.Length; + + LineInfo line = LineInfo.Borrow(); + _lines.Add(line); + line.y = line.y2 = GUTTER_Y; + sLineChars.Clear(); + + for (int charIndex = 0; charIndex < textLength; charIndex++) + { + char ch = _parsedText[charIndex]; + + glyphWidth = glyphHeight = baseline = 0; + + while (element != null && element.charIndex == charIndex) + { + if (element.type == HtmlElementType.Text) + { + format = element.format; + _font.SetFormat(format, _fontSizeScale); + } + else + { + IHtmlObject htmlObject = element.htmlObject; + if (_richTextField != null && htmlObject == null) + { + element.space = (int)(rectWidth - line.width - 4); + htmlObject = _richTextField.htmlPageContext.CreateObject(_richTextField, element); + element.htmlObject = htmlObject; + } + + if (htmlObject != null) + { + glyphWidth = htmlObject.width + 2; + glyphHeight = htmlObject.height; + baseline = glyphHeight * IMAGE_BASELINE; + } + + if (element.isEntity) + ch = '\0'; //indicate it is a place holder + } + + elementIndex++; + if (elementIndex < elementCount) + element = _elements[elementIndex]; + else + element = null; + } + + if (ch == '\0' || ch == '\n') + { + wordPossible = false; + } + else if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) + { + if (ch == '\t') + glyphWidth *= 4; + + if (wordPossible) + { + if (char.IsWhiteSpace(ch)) + { + wordLen = 0; + } + else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' + || ch >= '0' && ch <= '9' + || ch == '.' || ch == '"' || ch == '\'' + || format.specialStyle == TextFormat.SpecialStyle.Subscript + || format.specialStyle == TextFormat.SpecialStyle.Superscript + || _textDirection != RTLSupport.DirectionType.UNKNOW && + RTLSupport.IsArabicLetter(ch)) + { + wordLen++; + } + else + wordPossible = false; + } + else if (char.IsWhiteSpace(ch)) + { + wordLen = 0; + wordPossible = true; + } + else if (format.specialStyle == TextFormat.SpecialStyle.Subscript + || format.specialStyle == TextFormat.SpecialStyle.Superscript) + { + if (sLineChars.Count > 0) + { + wordLen = 2; //避免上标和下标折到下一行 + wordPossible = true; + } + } + else + wordPossible = false; + } + else + wordPossible = false; + + sLineChars.Add(new LineCharInfo() { width = glyphWidth, height = glyphHeight, baseline = baseline }); + if (glyphWidth != 0) + { + if (posx != 0) + posx += letterSpacing; + posx += glyphWidth; + } + + if (ch == '\n' && !_singleLine) + { + UpdateLineInfo(line, letterSpacing, sLineChars.Count); + + LineInfo newLine = LineInfo.Borrow(); + _lines.Add(newLine); + newLine.y = line.y + (line.height + lineSpacing); + if (newLine.y < GUTTER_Y) //lineSpacing maybe negative + newLine.y = GUTTER_Y; + newLine.y2 = newLine.y; + newLine.charIndex = line.charIndex + line.charCount; + + if (checkEdge && line.y + line.height < rectHeight) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + + sLineChars.Clear(); + wordPossible = false; + posx = 0; + line = newLine; + } + else if (posx > rectWidth) + { + if (wrap) + { + int lineCharCount = sLineChars.Count; + int toMoveChars; + + if (wordPossible && wordLen < 20 && + lineCharCount > 2) //if word had broken, move word to new line + { + toMoveChars = wordLen; + //we caculate the line width WITHOUT the tailing space + UpdateLineInfo(line, letterSpacing, lineCharCount - (toMoveChars + 1)); + line.charCount++; //but keep it in this line. + } + else + { + toMoveChars = + lineCharCount > 1 ? 1 : 0; //if only one char here, we cant move it to new line + UpdateLineInfo(line, letterSpacing, lineCharCount - toMoveChars); + } + + LineInfo newLine = LineInfo.Borrow(); + _lines.Add(newLine); + newLine.y = line.y + (line.height + lineSpacing); + if (newLine.y < GUTTER_Y) + newLine.y = GUTTER_Y; + newLine.y2 = newLine.y; + newLine.charIndex = line.charIndex + line.charCount; + + posx = 0; + if (toMoveChars != 0) + { + for (int i = line.charCount; i < lineCharCount; i++) + { + LineCharInfo ci = sLineChars[i]; + if (posx != 0) + posx += letterSpacing; + posx += ci.width; + } + + sLineChars.RemoveRange(0, line.charCount); + } + else + sLineChars.Clear(); + + if (checkEdge && line.y + line.height < rectHeight) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + + wordPossible = false; + line = newLine; + } + else if (checkEdge && _ellipsisCharIndex == -1) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + } + } + + UpdateLineInfo(line, letterSpacing, sLineChars.Count); + + if (_textWidth > 0) + _textWidth += GUTTER_X * 2; + _textHeight = line.y + line.height + GUTTER_Y; + + if (checkEdge && _textWidth <= _contentRect.width && _textHeight <= _contentRect.height + GUTTER_Y) + _ellipsisCharIndex = -1; + + _textWidth = Mathf.RoundToInt(_textWidth); + _textHeight = Mathf.RoundToInt(_textHeight); + } + + void UpdateLineInfo(LineInfo line, float letterSpacing, int cnt) + { + for (int i = 0; i < cnt; i++) + { + LineCharInfo ci = sLineChars[i]; + if (ci.baseline > line.baseline) + { + line.height += (ci.baseline - line.baseline); + line.baseline = ci.baseline; + } + + if (ci.height - ci.baseline > line.height - line.baseline) + line.height += (ci.height - ci.baseline - (line.height - line.baseline)); + + if (ci.width > 0) + { + if (line.width != 0) + line.width += letterSpacing; + line.width += ci.width; + } + } + + if (line.height == 0) + { + if (_lines.Count == 1) + line.height = _textFormat.size; + else + line.height = _lines[_lines.Count - 2].height; + } + + if (line.width > _textWidth) + _textWidth = line.width; + + line.charCount = (short)cnt; + } + + void DoShrink() + { + if (_lines.Count > 1 && _textHeight > _contentRect.height) + { + //多行的情况,涉及到自动换行,得用二分法查找最合适的比例,会消耗多一点计算资源 + int low = 0; + int high = _textFormat.size; + + //先尝试猜测一个比例 + _fontSizeScale = Mathf.Sqrt(_contentRect.height / _textHeight); + int cur = Mathf.FloorToInt(_fontSizeScale * _textFormat.size); + + while (true) + { + LineInfo.Return(_lines); + BuildLines2(); + + if (_textWidth > _contentRect.width || _textHeight > _contentRect.height) + high = cur; + else + low = cur; + if (high - low > 1 || high != low && cur == high) + { + cur = low + (high - low) / 2; + _fontSizeScale = (float)cur / _textFormat.size; + } + else + break; + } + } + else if (_textWidth > _contentRect.width) + { + _fontSizeScale = _contentRect.width / _textWidth; + + LineInfo.Return(_lines); + BuildLines2(); + + if (_textWidth > _contentRect.width) //如果还超出,缩小一点再来一次 + { + int size = Mathf.FloorToInt(_textFormat.size * _fontSizeScale); + size--; + _fontSizeScale = (float)size / _textFormat.size; + + LineInfo.Return(_lines); + BuildLines2(); + } + } + } + + int ParseText(StringBuilder buffer, string source, int elementIndex) + { + int textLength = source.Length; + int j = 0; + int appendPos = 0; + bool hasEmojies = _richTextField != null && _richTextField.emojies != null; + while (j < textLength) + { + char ch = source[j]; + if (ch == '\r') + { + buffer.Append(source, appendPos, j - appendPos); + if (j != textLength - 1 && source[j + 1] == '\n') + j++; + appendPos = j + 1; + buffer.Append('\n'); + } + else + { + bool highSurrogate = char.IsHighSurrogate(ch); + if (hasEmojies) + { + uint emojiKey = 0; + Emoji emoji; + if (highSurrogate) + emojiKey = ((uint)source[j + 1] & 0x03FF) + ((((uint)ch & 0x03FF) + 0x40) << 10); + else + emojiKey = ch; + if (_richTextField.emojies.TryGetValue(emojiKey, out emoji)) + { + HtmlElement imageElement = HtmlElement.GetElement(HtmlElementType.Image); + imageElement.Set("src", emoji.url); + if (emoji.width != 0) + imageElement.Set("width", emoji.width); + if (emoji.height != 0) + imageElement.Set("height", emoji.height); + if (highSurrogate) + imageElement.text = source.Substring(j, 2); + else + imageElement.text = source.Substring(j, 1); + imageElement.format.align = _textFormat.align; + _elements.Insert(++elementIndex, imageElement); + + buffer.Append(source, appendPos, j - appendPos); + appendPos = j; + imageElement.charIndex = buffer.Length; + } + } + + if (highSurrogate) + { + buffer.Append(source, appendPos, j - appendPos); + appendPos = j + 2; + j++; //跳过lowSurrogate + buffer.Append(' '); + } + } + + j++; + } + + if (appendPos < textLength) + buffer.Append(source, appendPos, j - appendPos); + + return elementIndex; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (_textWidth == 0 && _lines.Count == 1) + { + if (_charPositions != null) + { + _charPositions.Clear(); + _charPositions.Add(new CharPosition()); + } + + if (_richTextField != null) + _richTextField.RefreshObjects(); + + return; + } + + float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; + TextFormat format = _textFormat; + _font.SetFormat(format, _fontSizeScale); + _font.UpdateGraphics(graphics); + + float rectWidth = _contentRect.width > 0 ? (_contentRect.width - GUTTER_X * 2) : 0; + float rectHeight = _contentRect.height > 0 + ? Mathf.Max(_contentRect.height, _font.GetLineHeight(format.size)) + : 0; + + if (_charPositions != null) + _charPositions.Clear(); + + List vertList = vb.vertices; + List uvList = vb.uvs; + List uv2List = vb.uvs2; + List colList = vb.colors; + + HtmlLink currentLink = null; + float linkStartX = 0; + int linkStartLine = 0; + + float posx = 0; + float indent_x; + bool clipping = !_input && (_autoSize == AutoSizeType.None || _autoSize == AutoSizeType.Ellipsis); + bool lineClipped; + AlignType lineAlign; + float glyphWidth, glyphHeight, baseline; + short vertCount; + float underlineStart; + float strikethroughStart; + int minFontSize; + int maxFontSize; + string rtlLine = null; + + int elementIndex = 0; + int elementCount = _elements.Count; + HtmlElement element = null; + if (elementCount > 0) + element = _elements[elementIndex]; + + int lineCount = _lines.Count; + for (int i = 0; i < lineCount; ++i) + { + LineInfo line = _lines[i]; + if (line.charCount == 0) + continue; + + lineClipped = clipping && i != 0 && line.y + line.height > rectHeight; + lineAlign = format.align; + if (element != null && element.charIndex == line.charIndex) + lineAlign = element.format.align; + else + lineAlign = format.align; + + if (_textDirection == RTLSupport.DirectionType.RTL) + { + if (lineAlign == AlignType.Center) + indent_x = (int)((rectWidth + line.width) / 2); + else if (lineAlign == AlignType.Right) + indent_x = rectWidth; + else + indent_x = line.width + GUTTER_X * 2; + + if (indent_x > rectWidth) + indent_x = rectWidth; + + posx = indent_x - GUTTER_X; + } + else + { + if (lineAlign == AlignType.Center) + indent_x = (int)((rectWidth - line.width) / 2); + else if (lineAlign == AlignType.Right) + indent_x = rectWidth - line.width; + else + indent_x = 0; + + if (indent_x < 0) + indent_x = 0; + + posx = GUTTER_X + indent_x; + } + + int lineCharCount = line.charCount; + underlineStart = posx; + strikethroughStart = posx; + minFontSize = maxFontSize = format.size; + + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + { + rtlLine = _parsedText.Substring(line.charIndex, lineCharCount); + if (_textDirection == RTLSupport.DirectionType.RTL) + rtlLine = RTLSupport.ConvertLineR(rtlLine); + else + rtlLine = RTLSupport.ConvertLineL(rtlLine); + lineCharCount = rtlLine.Length; + } + + for (int j = 0; j < lineCharCount; j++) + { + int charIndex = line.charIndex + j; + char ch = rtlLine != null ? rtlLine[j] : _parsedText[charIndex]; + bool isEllipsis = charIndex == _ellipsisCharIndex; + + while (element != null && charIndex == element.charIndex) + { + if (element.type == HtmlElementType.Text) + { + vertCount = 0; + if (format.underline != element.format.underline) + { + if (format.underline) + { + if (!lineClipped) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping + ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) + : posx) - underlineStart; + else + lineWidth = underlineStart - (clipping + ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) + : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine( + underlineStart < posx ? underlineStart : posx, + -(line.y + line.baseline), lineWidth, + maxFontSize, 0, vertList, uvList, uv2List, colList); + } + + maxFontSize = 0; + } + else + underlineStart = posx; + } + + if (format.strikethrough != element.format.strikethrough) + { + if (format.strikethrough) + { + if (!lineClipped) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping + ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) + : posx) - strikethroughStart; + else + lineWidth = strikethroughStart - (clipping + ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) + : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine( + strikethroughStart < posx ? strikethroughStart : posx, + -(line.y + line.baseline), lineWidth, + minFontSize, 1, vertList, uvList, uv2List, colList); + } + + minFontSize = int.MaxValue; + } + else + strikethroughStart = posx; + } + + if (vertCount > 0 && _charPositions != null) + { + CharPosition cp = _charPositions[_charPositions.Count - 1]; + cp.vertCount += vertCount; + _charPositions[_charPositions.Count - 1] = cp; + } + + format = element.format; + minFontSize = Math.Min(minFontSize, format.size); + maxFontSize = Math.Max(maxFontSize, format.size); + _font.SetFormat(format, _fontSizeScale); + } + else if (element.type == HtmlElementType.Link) + { + currentLink = (HtmlLink)element.htmlObject; + if (currentLink != null) + { + element.position = Vector2.zero; + currentLink.SetPosition(0, 0); + linkStartX = posx; + linkStartLine = i; + } + } + else if (element.type == HtmlElementType.LinkEnd) + { + if (currentLink != null) + { + currentLink.SetArea(linkStartLine, linkStartX, i, posx); + currentLink = null; + } + } + else + { + IHtmlObject htmlObj = element.htmlObject; + if (htmlObj != null) + { + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= htmlObj.width - 2; + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.imgIndex = (short)(elementIndex + 1); + cp.offsetX = posx; + cp.width = (short)htmlObj.width; + _charPositions.Add(cp); + } + + if (isEllipsis || lineClipped || clipping && (posx < GUTTER_X || + posx > GUTTER_X && + posx + htmlObj.width > + _contentRect.width - GUTTER_X)) + element.status |= 1; + else + element.status &= 254; + + element.position = new Vector2(posx + 1, + line.y + line.baseline - htmlObj.height * IMAGE_BASELINE); + htmlObj.SetPosition(element.position.x, element.position.y); + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += htmlObj.width + letterSpacing + 2; + } + } + + if (element.isEntity) + ch = '\0'; + + elementIndex++; + if (elementIndex < elementCount) + element = _elements[elementIndex]; + else + element = null; + } + + if (isEllipsis) + ch = '…'; + else if (ch == '\0') + continue; + + if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) + { + if (ch == '\t') + glyphWidth *= 4; + + if (!isEllipsis) + { + if (_textDirection == RTLSupport.DirectionType.RTL) + { + if (lineClipped || clipping && (rectWidth < 7 || posx != (indent_x - GUTTER_X)) && + posx < GUTTER_X - 0.5f) //超出区域,剪裁 + { + posx -= (letterSpacing + glyphWidth); + continue; + } + + posx -= glyphWidth; + } + else + { + if (lineClipped || clipping && (rectWidth < 7 || posx != (GUTTER_X + indent_x)) && + posx + glyphWidth > _contentRect.width - GUTTER_X + 0.5f) //超出区域,剪裁 + { + posx += letterSpacing + glyphWidth; + continue; + } + } + } + + vertCount = (short)_font.DrawGlyph(posx, -(line.y + line.baseline), vertList, uvList, uv2List, + colList); + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.vertCount = vertCount; + cp.offsetX = posx; + cp.width = (short)glyphWidth; + _charPositions.Add(cp); + } + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += letterSpacing + glyphWidth; + } + else //if GetGlyph failed + { + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.offsetX = posx; + _charPositions.Add(cp); + } + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += letterSpacing; + } + + if (isEllipsis) + lineClipped = true; + } //text loop + + if (!lineClipped) + { + vertCount = 0; + if (format.underline) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - + underlineStart; + else + lineWidth = underlineStart - + (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(underlineStart < posx ? underlineStart : posx, + -(line.y + line.baseline), lineWidth, + maxFontSize, 0, vertList, uvList, uv2List, colList); + } + + if (format.strikethrough) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - + strikethroughStart; + else + lineWidth = strikethroughStart - + (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(strikethroughStart < posx ? strikethroughStart : posx, + -(line.y + line.baseline), lineWidth, + minFontSize, 1, vertList, uvList, uv2List, colList); + } + + if (vertCount > 0 && _charPositions != null) + { + CharPosition cp = _charPositions[_charPositions.Count - 1]; + cp.vertCount += vertCount; + _charPositions[_charPositions.Count - 1] = cp; + } + } + } //line loop + + if (element != null && element.type == HtmlElementType.LinkEnd && currentLink != null) + currentLink.SetArea(linkStartLine, linkStartX, lineCount - 1, posx); + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)(lineCount - 1); + cp.charIndex = _charPositions.Count; + cp.offsetX = posx; + _charPositions.Add(cp); + } + + int count = vertList.Count; + if (count > 65000) + { + Debug.LogWarning("Text is too large. A mesh may not have more than 65000 vertices."); + vertList.RemoveRange(65000, count - 65000); + colList.RemoveRange(65000, count - 65000); + uvList.RemoveRange(65000, count - 65000); + if (uv2List.Count > 0) + uv2List.RemoveRange(65000, count - 65000); + count = 65000; + } + + if (_font.customOutline) + { + bool hasShadow = _textFormat.shadowOffset.x != 0 || _textFormat.shadowOffset.y != 0; + int allocCount = count; + int drawDirs = 0; + if (_textFormat.outline != 0) + { + drawDirs = UIConfig.enhancedTextOutlineEffect ? 8 : 4; + allocCount += count * drawDirs; + } + + if (hasShadow) + allocCount += count; + if (allocCount > 65000) + { + Debug.LogWarning("Text is too large. Outline/shadow effect cannot be completed."); + allocCount = count; + } + + if (allocCount != count) + { + VertexBuffer vb2 = VertexBuffer.Begin(); + List vertList2 = vb2.vertices; + List colList2 = vb2.colors; + + Color32 col = _textFormat.outlineColor; + float outline = _textFormat.outline; + if (outline != 0) + { + for (int j = 0; j < drawDirs; j++) + { + for (int i = 0; i < count; i++) + { + Vector3 vert = vertList[i]; + vertList2.Add(new Vector3(vert.x + STROKE_OFFSET[j * 2] * outline, + vert.y + STROKE_OFFSET[j * 2 + 1] * outline, 0)); + colList2.Add(col); + } + + vb2.uvs.AddRange(uvList); + if (uv2List.Count > 0) + vb2.uvs2.AddRange(uv2List); + } + } + + if (hasShadow) + { + col = _textFormat.shadowColor; + Vector2 offset = _textFormat.shadowOffset; + for (int i = 0; i < count; i++) + { + Vector3 vert = vertList[i]; + vertList2.Add(new Vector3(vert.x + offset.x, vert.y - offset.y, 0)); + colList2.Add(col); + } + + vb2.uvs.AddRange(uvList); + if (uv2List.Count > 0) + vb2.uvs2.AddRange(uv2List); + } + + vb.Insert(vb2); + vb2.End(); + } + } + + vb.AddTriangles(); + + if (_richTextField != null) + _richTextField.RefreshObjects(); + } + + void Cleanup() + { + if (_richTextField != null) + _richTextField.CleanupObjects(); + + HtmlElement.ReturnElements(_elements); + LineInfo.Return(_lines); + _textWidth = 0; + _textHeight = 0; + _parsedText = string.Empty; + _textDirection = RTLSupport.DirectionType.UNKNOW; + + if (_charPositions != null) + _charPositions.Clear(); + } + + void ApplyVertAlign() + { + float oldOffset = _yOffset; + if (_autoSize == AutoSizeType.Both || _autoSize == AutoSizeType.Height + || _verticalAlign == VertAlignType.Top) + _yOffset = 0; + else + { + float dh; + if (_textHeight == 0 && _lines.Count > 0) + dh = _contentRect.height - _lines[0].height; + else + dh = _contentRect.height - _textHeight; + if (dh < 0) + dh = 0; + if (_verticalAlign == VertAlignType.Middle) + _yOffset = (int)(dh / 2); + else + _yOffset = dh; + } + + if (oldOffset != _yOffset) + { + int cnt = _lines.Count; + for (int i = 0; i < cnt; i++) + _lines[i].y = _lines[i].y2 + _yOffset; + + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public class LineInfo + { + /// + /// 行的宽度 + /// + public float width; + + /// + /// 行的高度 + /// + public float height; + + /// + /// 文字渲染基线 + /// + public float baseline; + + /// + /// 行首的字符索引 + /// + public int charIndex; + + /// + /// 行包括的字符个数 + /// + public short charCount; + + /// + /// 行的y轴位置 + /// + public float y; + + /// + /// 行的y轴位置的备份 + /// + internal float y2; + + static Stack pool = new Stack(); + + /// + /// + /// + /// + public static LineInfo Borrow() + { + if (pool.Count > 0) + { + LineInfo ret = pool.Pop(); + ret.width = ret.height = ret.baseline = 0; + ret.y = ret.y2 = 0; + ret.charIndex = ret.charCount = 0; + return ret; + } + else + return new LineInfo(); + } + + /// + /// + /// + /// + public static void Return(LineInfo value) + { + pool.Push(value); + } + + /// + /// + /// + /// + public static void Return(List values) + { + int cnt = values.Count; + for (int i = 0; i < cnt; i++) + pool.Push(values[i]); + + values.Clear(); + } + } + + /// + /// + /// + public struct LineCharInfo + { + public float width; + public float height; + public float baseline; + } + + /// + /// + /// + public struct CharPosition + { + /// + /// 字符索引 + /// + public int charIndex; + + /// + /// 字符所在的行索引 + /// + public short lineIndex; + + /// + /// 字符的x偏移 + /// + public float offsetX; + + /// + /// 字符占用的顶点数量。 + /// + public short vertCount; + + /// + /// 字符的宽度 + /// + public short width; + + /// + /// 大于0表示图片索引。 + /// + public short imgIndex; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs.meta new file mode 100644 index 0000000..5bfae6a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8a05d6d82201104cb6b5156ca294f54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs new file mode 100644 index 0000000..361f376 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs @@ -0,0 +1,175 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public partial class TextFormat + { + public enum SpecialStyle + { + None, + Superscript, + Subscript + } + + /// + /// + /// + public int size; + + /// + /// + /// + public string font; + + /// + /// + /// + public Color color; + + /// + /// + /// + public int lineSpacing; + + /// + /// + /// + public int letterSpacing; + + /// + /// + /// + public bool bold; + + /// + /// + /// + public bool underline; + + /// + /// + /// + public bool italic; + + /// + /// + /// + public bool strikethrough; + + /// + /// + /// + public Color32[] gradientColor; + + /// + /// + /// + public AlignType align; + + /// + /// + /// + public SpecialStyle specialStyle; + + /// + /// + /// + public float outline; + + /// + /// + /// + public Color outlineColor; + + /// + /// + /// + public Vector2 shadowOffset; + + /// + /// + /// + public Color shadowColor; + + public TextFormat() + { + color = Color.black; + size = 12; + lineSpacing = 3; + outlineColor = shadowColor = Color.black; + } + + /// + /// + /// + /// + public void SetColor(uint value) + { + uint rr = (value >> 16) & 0x0000ff; + uint gg = (value >> 8) & 0x0000ff; + uint bb = value & 0x0000ff; + float r = rr / 255.0f; + float g = gg / 255.0f; + float b = bb / 255.0f; + color = new Color(r, g, b, 1); + } + + /// + /// + /// + /// + /// + public bool EqualStyle(TextFormat aFormat) + { + return size == aFormat.size && color == aFormat.color + && bold == aFormat.bold && underline == aFormat.underline + && italic == aFormat.italic + && strikethrough == aFormat.strikethrough + && gradientColor == aFormat.gradientColor + && align == aFormat.align + && specialStyle == aFormat.specialStyle; + } + + /// + /// Only base NOT all formats will be copied + /// + /// + public void CopyFrom(TextFormat source) + { + this.size = source.size; + this.font = source.font; + this.color = source.color; + this.lineSpacing = source.lineSpacing; + this.letterSpacing = source.letterSpacing; + this.bold = source.bold; + this.underline = source.underline; + this.italic = source.italic; + this.strikethrough = source.strikethrough; + if (source.gradientColor != null) + { + this.gradientColor = new Color32[4]; + source.gradientColor.CopyTo(this.gradientColor, 0); + } + else + this.gradientColor = null; + this.align = source.align; + this.specialStyle = source.specialStyle; + } + + public void FillVertexColors(Color32[] vertexColors) + { + if (gradientColor == null) + vertexColors[0] = vertexColors[1] = vertexColors[2] = vertexColors[3] = color; + else + { + vertexColors[0] = gradientColor[1]; + vertexColors[1] = gradientColor[0]; + vertexColors[2] = gradientColor[2]; + vertexColors[3] = gradientColor[3]; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs.meta new file mode 100644 index 0000000..a06fedc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TextFormat.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ecffbe294c108da4ab8a1c573e3d4dfd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs new file mode 100644 index 0000000..85505e6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs @@ -0,0 +1,65 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class TouchScreenKeyboard : IKeyboard + { + UnityEngine.TouchScreenKeyboard _keyboard; + + public bool done + { +#if UNITY_2017_2_OR_NEWER + get + { + return _keyboard == null + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Done + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Canceled + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.LostFocus; + } +#else + get { return _keyboard == null || _keyboard.done || _keyboard.wasCanceled; } +#endif + } + + public bool supportsCaret + { + get { return false; } + } + + public string GetInput() + { + if (_keyboard != null) + { + string s = _keyboard.text; + + if (this.done) + _keyboard = null; + + return s; + } + else + return null; + } + + public void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput) + { + if (_keyboard != null) + return; + + UnityEngine.TouchScreenKeyboard.hideInput = hideInput; + _keyboard = UnityEngine.TouchScreenKeyboard.Open(text, (TouchScreenKeyboardType)keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); + } + + public void Close() + { + if (_keyboard != null) + { + _keyboard.active = false; + _keyboard = null; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs.meta new file mode 100644 index 0000000..fc988e9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TouchScreenKeyboard.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb24d1c92a1114a4f9db5688cc3fa35b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs new file mode 100644 index 0000000..0195b2c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs @@ -0,0 +1,252 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 文字打字效果。先调用Start,然后Print。 + /// + public class TypingEffect + { + protected TextField _textField; + protected Vector3[] _backupVerts; + protected Vector3[] _vertices; + + protected bool _stroke; + protected bool _shadow; + + protected int _printIndex; + protected int _mainLayerStart; + protected int _strokeLayerStart; + protected int _strokeDrawDirs; + protected int _vertIndex; + protected int _mainLayerVertCount; + + protected bool _started; + + /// + /// + /// + /// + public TypingEffect(TextField textField) + { + _textField = textField; + _textField.EnableCharPositionSupport(); + } + + /// + /// + /// + /// + public TypingEffect(GTextField textField) + { + if (textField is GRichTextField) + _textField = ((RichTextField)textField.displayObject).textField; + else + _textField = (TextField)textField.displayObject; + _textField.EnableCharPositionSupport(); + } + + /// + /// 总输出次数 + /// + public int totalTimes + { + get + { + int times = 0; + List charPositions = _textField.charPositions; + for (int i = 0; i < charPositions.Count - 1; i++) + { + if (charPositions[i].imgIndex > 0) //这是一个图片 + times++; + else if (!char.IsWhiteSpace(_textField.parsedText[i])) + times++; + } + + return times; + } + } + + /// + /// 开始打字效果。可以重复调用重复启动。 + /// + public void Start() + { + _textField.graphics.meshModifier -= OnMeshModified; + _textField.Redraw(); + _textField.graphics.meshModifier += OnMeshModified; + + _stroke = false; + _shadow = false; + _strokeDrawDirs = 4; + _mainLayerStart = 0; + _mainLayerVertCount = 0; + _printIndex = 0; + _vertIndex = 0; + _started = true; + + int vertCount = _textField.graphics.mesh.vertexCount; + _backupVerts = _textField.graphics.mesh.vertices; + if (_vertices == null || _vertices.Length != vertCount) + _vertices = new Vector3[vertCount]; + Vector3 zero = Vector3.zero; + for (int i = 0; i < vertCount; i++) + _vertices[i] = zero; + _textField.graphics.mesh.vertices = _vertices; + + //隐藏所有混排的对象 + if (_textField.richTextField != null) + { + int ec = _textField.richTextField.htmlElementCount; + for (int i = 0; i < ec; i++) + _textField.richTextField.ShowHtmlObject(i, false); + } + + int charCount = _textField.charPositions.Count; + for (int i = 0; i < charCount; i++) + { + TextField.CharPosition cp = _textField.charPositions[i]; + _mainLayerVertCount += cp.vertCount; + } + + if (_mainLayerVertCount < vertCount) //说明有描边或者阴影 + { + int repeat = vertCount / _mainLayerVertCount; + _stroke = repeat > 2; + _shadow = repeat % 2 == 0; + _mainLayerStart = vertCount - vertCount / repeat; + _strokeLayerStart = _shadow ? (vertCount / repeat) : 0; + _strokeDrawDirs = repeat > 8 ? 8 : 4; + } + } + + /// + /// 输出一个字符。如果已经没有剩余的字符,返回false。 + /// + /// + public bool Print() + { + if (!_started) + return false; + + TextField.CharPosition cp; + List charPositions = _textField.charPositions; + int listCnt = charPositions.Count; + + while (_printIndex < listCnt - 1) //最后一个是占位的,无效的,所以-1 + { + cp = charPositions[_printIndex++]; + if (cp.vertCount > 0) + output(cp.vertCount); + if (cp.imgIndex > 0) //这是一个图片 + { + _textField.richTextField.ShowHtmlObject(cp.imgIndex - 1, true); + return true; + } + else if (!char.IsWhiteSpace(_textField.parsedText[_printIndex - 1])) + return true; + } + + Cancel(); + return false; + } + + private void output(int vertCount) + { + int start, end; + + start = _mainLayerStart + _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + _vertices[i] = _backupVerts[i]; + + if (_stroke) + { + start = _strokeLayerStart + _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + { + for (int j = 0; j < _strokeDrawDirs; j++) + { + int k = i + _mainLayerVertCount * j; + _vertices[k] = _backupVerts[k]; + } + } + } + + if (_shadow) + { + start = _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + { + _vertices[i] = _backupVerts[i]; + } + } + + if (_textField.graphics.mesh != null) + { + _textField.graphics.mesh.vertices = _vertices; + } + + _vertIndex += vertCount; + } + + /// + /// 打印的协程。 + /// + /// 每个字符输出的时间间隔 + /// + public IEnumerator Print(float interval) + { + while (Print()) + yield return new WaitForSeconds(interval); + } + + /// + /// 使用固定时间间隔完成整个打印过程。 + /// + /// + public void PrintAll(float interval) + { + Timers.inst.StartCoroutine(Print(interval)); + } + + public void Cancel() + { + if (!_started) + return; + + _started = false; + _textField.graphics.meshModifier -= OnMeshModified; + _textField.graphics.SetMeshDirty(); + } + + /// + /// 当打字过程中,文本可能会由于字体纹理更改而发生字体重建,要处理这种情况。 + /// 图片对象不需要处理,因为HtmlElement.status里设定的隐藏标志不会因为Mesh更新而被冲掉。 + /// + void OnMeshModified() + { + if (_textField.graphics.mesh.vertexCount != _backupVerts.Length) //可能文字都改了 + { + Cancel(); + return; + } + + _backupVerts = _textField.graphics.mesh.vertices; + + int vertCount = _vertices.Length; + Vector3 zero = Vector3.zero; + for (int i = 0; i < vertCount; i++) + { + if (_vertices[i] != zero) + _vertices[i] = _backupVerts[i]; + } + + _textField.graphics.mesh.vertices = _vertices; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs.meta new file mode 100644 index 0000000..15eedb4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/Text/TypingEffect.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 213be0a4bfae47c4ebf643f5ee856399 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs new file mode 100644 index 0000000..dc0bc5d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// UpdateContext is for internal use. + /// + public class UpdateContext + { + public struct ClipInfo + { + public Rect rect; + public Vector4 clipBox; + public bool soft; + public Vector4 softness;//left-top-right-bottom + public uint clipId; + public int rectMaskDepth; + public int referenceValue; + public bool reversed; + } + + Stack _clipStack; + + public bool clipped; + public ClipInfo clipInfo; + + public int renderingOrder; + public int batchingDepth; + public int rectMaskDepth; + public int stencilReferenceValue; + public int stencilCompareValue; + + public float alpha; + public bool grayed; + + public static UpdateContext current; + public static bool working; + + public static event Action OnBegin; + public static event Action OnEnd; + + static Action _tmpBegin; + + public UpdateContext() + { + _clipStack = new Stack(); + } + + /// + /// + /// + public void Begin() + { + current = this; + + renderingOrder = 0; + batchingDepth = 0; + rectMaskDepth = 0; + stencilReferenceValue = 0; + alpha = 1; + grayed = false; + + clipped = false; + _clipStack.Clear(); + + Stats.ObjectCount = 0; + Stats.GraphicsCount = 0; + + _tmpBegin = OnBegin; + OnBegin = null; + + //允许OnBegin里再次Add,这里没有做死锁检查 + while (_tmpBegin != null) + { + _tmpBegin.Invoke(); + _tmpBegin = OnBegin; + OnBegin = null; + } + + working = true; + } + + /// + /// + /// + public void End() + { + working = false; + + if (OnEnd != null) + OnEnd.Invoke(); + + OnEnd = null; + } + + /// + /// + /// + /// + /// + /// + public void EnterClipping(uint clipId, Rect clipRect, Vector4? softness) + { + _clipStack.Push(clipInfo); + + if (rectMaskDepth > 0) + clipRect = ToolSet.Intersection(ref clipInfo.rect, ref clipRect); + + clipped = true; + clipInfo.rectMaskDepth = ++rectMaskDepth; + /* clipPos = xy * clipBox.zw + clipBox.xy + * 利用这个公式,使clipPos变为当前顶点距离剪切区域中心的距离值,剪切区域的大小为2x2 + * 那么abs(clipPos)>1的都是在剪切区域外 + */ + clipInfo.rect = clipRect; + clipRect.x = clipRect.x + clipRect.width * 0.5f; + clipRect.y = clipRect.y + clipRect.height * 0.5f; + clipRect.width *= 0.5f; + clipRect.height *= 0.5f; + if (clipRect.width == 0 || clipRect.height == 0) + clipInfo.clipBox = new Vector4(-2, -2, 0, 0); + else + clipInfo.clipBox = new Vector4(-clipRect.x / clipRect.width, -clipRect.y / clipRect.height, + 1.0f / clipRect.width, 1.0f / clipRect.height); + clipInfo.clipId = clipId; + clipInfo.soft = softness != null; + if (clipInfo.soft) + { + clipInfo.softness = (Vector4)softness; + float vx = clipInfo.rect.width * Screen.height * 0.25f; + float vy = clipInfo.rect.height * Screen.height * 0.25f; + + if (clipInfo.softness.x > 0) + clipInfo.softness.x = vx / clipInfo.softness.x; + else + clipInfo.softness.x = 10000f; + + if (clipInfo.softness.y > 0) + clipInfo.softness.y = vy / clipInfo.softness.y; + else + clipInfo.softness.y = 10000f; + + if (clipInfo.softness.z > 0) + clipInfo.softness.z = vx / clipInfo.softness.z; + else + clipInfo.softness.z = 10000f; + + if (clipInfo.softness.w > 0) + clipInfo.softness.w = vy / clipInfo.softness.w; + else + clipInfo.softness.w = 10000f; + } + } + + /// + /// + /// + /// + /// + public void EnterClipping(uint clipId, bool reversedMask) + { + _clipStack.Push(clipInfo); + + if (stencilReferenceValue == 0) + stencilReferenceValue = 1; + else + stencilReferenceValue = stencilReferenceValue << 1; + + if (reversedMask) + { + if (clipInfo.reversed) + stencilCompareValue = (stencilReferenceValue >> 1) - 1; + else + stencilCompareValue = stencilReferenceValue - 1; + } + else + stencilCompareValue = (stencilReferenceValue << 1) - 1; + + clipInfo.clipId = clipId; + clipInfo.referenceValue = stencilReferenceValue; + clipInfo.reversed = reversedMask; + clipped = true; + } + + /// + /// + /// + public void LeaveClipping() + { + clipInfo = _clipStack.Pop(); + stencilReferenceValue = clipInfo.referenceValue; + rectMaskDepth = clipInfo.rectMaskDepth; + clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; + } + + public void EnterPaintingMode() + { + //Reset clipping + _clipStack.Push(clipInfo); + + clipInfo.rectMaskDepth = 0; + clipInfo.referenceValue = 0; + clipInfo.reversed = false; + clipped = false; + } + + public void LeavePaintingMode() + { + clipInfo = _clipStack.Pop(); + stencilReferenceValue = clipInfo.referenceValue; + rectMaskDepth = clipInfo.rectMaskDepth; + clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; + } + + public void ApplyClippingProperties(Material mat, bool isStdMaterial) + { + if (rectMaskDepth > 0) //在矩形剪裁下,且不是遮罩对象 + { + mat.SetVector(ShaderConfig.ID_ClipBox, clipInfo.clipBox); + if (clipInfo.soft) + mat.SetVector(ShaderConfig.ID_ClipSoftness, clipInfo.softness); + } + + if (stencilReferenceValue > 0) + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, stencilCompareValue); + mat.SetInt(ShaderConfig.ID_Stencil2, stencilCompareValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); + mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue | (stencilReferenceValue - 1)); + mat.SetInt(ShaderConfig.ID_ColorMask, 15); + } + else + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); + mat.SetInt(ShaderConfig.ID_Stencil, 0); + mat.SetInt(ShaderConfig.ID_Stencil2, 0); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); + mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); + mat.SetInt(ShaderConfig.ID_ColorMask, 15); + } + + if (!isStdMaterial) + { + if (rectMaskDepth > 0) + { + if (clipInfo.soft) + mat.EnableKeyword("SOFT_CLIPPED"); + else + mat.EnableKeyword("CLIPPED"); + } + else + { + mat.DisableKeyword("CLIPPED"); + mat.DisableKeyword("SOFT_CLIPPED"); + } + } + } + + public void ApplyAlphaMaskProperties(Material mat, bool erasing) + { + if (!erasing) + { + if (stencilReferenceValue == 1) + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); + mat.SetInt(ShaderConfig.ID_Stencil, 1); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + else + { + if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.NotEqual); + else + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, stencilReferenceValue | (stencilReferenceValue - 1)); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue - 1); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + } + else + { + if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) + { + int refValue = stencilReferenceValue | (stencilReferenceValue - 1); + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, refValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Zero); + mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + else + { + int refValue = stencilReferenceValue - 1; + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, refValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs.meta new file mode 100644 index 0000000..7f82531 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Core/UpdateContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa81e163380612a4a9591fe57a5b442c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor.meta new file mode 100644 index 0000000..6982075 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0476fc08b4424e34b81f61fe76eb30c8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs new file mode 100644 index 0000000..060253b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs @@ -0,0 +1,126 @@ +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(DisplayObjectInfo))] + public class DisplayObjectEditor : Editor + { + void OnEnable() + { + } + + public override void OnInspectorGUI() + { + DisplayObject obj = (target as DisplayObjectInfo).displayObject; + if (obj == null) + return; + + EditorGUILayout.LabelField(obj.GetType().Name + ": " + obj.id, (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + EditorGUI.BeginChangeCheck(); + string name = EditorGUILayout.TextField("Name", obj.name); + if (EditorGUI.EndChangeCheck()) + obj.name = name; + if (obj is Container) + { + EditorGUI.BeginChangeCheck(); + bool fairyBatching = EditorGUILayout.Toggle("FairyBatching", ((Container)obj).fairyBatching); + if (EditorGUI.EndChangeCheck()) + ((Container)obj).fairyBatching = fairyBatching; + } + + GObject gObj = obj.gOwner; + if (gObj != null) + { + EditorGUILayout.Separator(); + EditorGUILayout.LabelField(gObj.GetType().Name + ": " + gObj.id, (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + + if (!string.IsNullOrEmpty(gObj.resourceURL)) + { + PackageItem pi = UIPackage.GetItemByURL(gObj.resourceURL); + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Resource"); + EditorGUILayout.LabelField(pi.name + "@" + pi.owner.name); + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.BeginChangeCheck(); + name = EditorGUILayout.TextField("Name", gObj.name); + if (EditorGUI.EndChangeCheck()) + gObj.name = name; + + if (gObj.parent != null) + { + string[] options = new string[gObj.parent.numChildren]; + int[] values = new int[options.Length]; + for (int i = 0; i < options.Length; i++) + { + options[i] = i.ToString(); + values[i] = i; + } + EditorGUI.BeginChangeCheck(); + int childIndex = EditorGUILayout.IntPopup("Child Index", gObj.parent.GetChildIndex(gObj), options, values); + if (EditorGUI.EndChangeCheck()) + gObj.parent.SetChildIndex(gObj, childIndex); + } + else + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Child Index"); + EditorGUILayout.LabelField("No Parent"); + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.BeginChangeCheck(); + Vector3 position = EditorGUILayout.Vector3Field("Position", gObj.position); + if (EditorGUI.EndChangeCheck()) + gObj.position = position; + + EditorGUI.BeginChangeCheck(); + Vector3 rotation = EditorGUILayout.Vector3Field("Rotation", new Vector3(gObj.rotationX, gObj.rotationY, gObj.rotation)); + if (EditorGUI.EndChangeCheck()) + { + gObj.rotationX = rotation.x; + gObj.rotationY = rotation.y; + gObj.rotation = rotation.z; + } + + EditorGUI.BeginChangeCheck(); + Vector2 scale = EditorGUILayout.Vector2Field("Scale", gObj.scale); + if (EditorGUI.EndChangeCheck()) + gObj.scale = scale; + + EditorGUI.BeginChangeCheck(); + Vector2 skew = EditorGUILayout.Vector2Field("Skew", gObj.skew); + if (EditorGUI.EndChangeCheck()) + gObj.skew = skew; + + EditorGUI.BeginChangeCheck(); + Vector2 size = EditorGUILayout.Vector2Field("Size", gObj.size); + if (EditorGUI.EndChangeCheck()) + gObj.size = size; + + EditorGUI.BeginChangeCheck(); + Vector2 pivot = EditorGUILayout.Vector2Field("Pivot", gObj.pivot); + if (EditorGUI.EndChangeCheck()) + gObj.pivot = pivot; + + EditorGUI.BeginChangeCheck(); + string text = EditorGUILayout.TextField("Text", gObj.text); + if (EditorGUI.EndChangeCheck()) + gObj.text = text; + + EditorGUI.BeginChangeCheck(); + string icon = EditorGUILayout.TextField("Icon", gObj.icon); + if (EditorGUI.EndChangeCheck()) + gObj.icon = icon; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs.meta new file mode 100644 index 0000000..55d8290 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/DisplayObjectEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2f78faa29e5e1547837f976bf4b39f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs new file mode 100644 index 0000000..287838e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs @@ -0,0 +1,135 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + public class EditorToolSet + { + public static GUIContent[] packagesPopupContents; + + static bool _loaded; + + [InitializeOnLoadMethod] + static void Startup() + { + EditorApplication.update += EditorApplication_Update; + } + + [MenuItem("GameObject/FairyGUI/UI Panel", false, 0)] + static void CreatePanel() + { + EditorApplication.update -= EditorApplication_Update; + EditorApplication.update += EditorApplication_Update; + + StageCamera.CheckMainCamera(); + + GameObject panelObject = new GameObject("UIPanel"); + if (Selection.activeGameObject != null) + { + panelObject.transform.parent = Selection.activeGameObject.transform; + panelObject.layer = Selection.activeGameObject.layer; + } + else + { + int layer = LayerMask.NameToLayer(StageCamera.LayerName); + panelObject.layer = layer; + } + panelObject.AddComponent(); + Selection.objects = new Object[] { panelObject }; + } + + [MenuItem("GameObject/FairyGUI/UI Camera", false, 0)] + static void CreateCamera() + { + StageCamera.CheckMainCamera(); + Selection.objects = new Object[] { StageCamera.main.gameObject }; + } + + [MenuItem("Window/FairyGUI - Refresh Packages And Panels")] + static void RefreshPanels() + { + ReloadPackages(); + } + + static void EditorApplication_Update() + { + if (Application.isPlaying) + return; + + if (_loaded || !EMRenderSupport.hasTarget) + return; + + LoadPackages(); + } + + public static void ReloadPackages() + { + if (!Application.isPlaying) + { + _loaded = false; + LoadPackages(); + Debug.Log("FairyGUI - Refresh Packages And Panels complete."); + } + else + EditorUtility.DisplayDialog("FairyGUI", "Cannot run in play mode.", "OK"); + } + + public static void LoadPackages() + { + if (Application.isPlaying || _loaded) + return; + + EditorApplication.update -= EditorApplication_Update; + EditorApplication.update += EditorApplication_Update; + + _loaded = true; + + UIPackage.RemoveAllPackages(); + FontManager.Clear(); + NTexture.DisposeEmpty(); + UIObjectFactory.Clear(); + + string[] ids = AssetDatabase.FindAssets("_fui t:textAsset"); + int cnt = ids.Length; + for (int i = 0; i < cnt; i++) + { + string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]); + int pos = assetPath.LastIndexOf("_fui"); + if (pos == -1) + continue; + + assetPath = assetPath.Substring(0, pos); + if (AssetDatabase.AssetPathToGUID(assetPath) != null) + UIPackage.AddPackage(assetPath, + (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + return AssetDatabase.LoadAssetAtPath(name + extension, type); + } + ); + } + + List pkgs = UIPackage.GetPackages(); + pkgs.Sort(CompareUIPackage); + + cnt = pkgs.Count; + packagesPopupContents = new GUIContent[cnt + 1]; + for (int i = 0; i < cnt; i++) + packagesPopupContents[i] = new GUIContent(pkgs[i].name); + packagesPopupContents[cnt] = new GUIContent("Please Select"); + + EMRenderSupport.Reload(); + } + + static int CompareUIPackage(UIPackage u1, UIPackage u2) + { + return u1.name.CompareTo(u2.name); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs.meta new file mode 100644 index 0000000..be1d317 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/EditorToolSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35dcb233f95ffd54c94f09d731db89ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs new file mode 100644 index 0000000..e0480d1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs @@ -0,0 +1,201 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +#if UNITY_2018_3_OR_NEWER +using UnityEditor.Experimental.SceneManagement; +#endif +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + public class PackagesWindow : EditorWindow + { + Vector2 scrollPos1; + Vector2 scrollPos2; + GUIStyle itemStyle; + + int selectedPackage; + string selectedPackageName; + string selectedComponentName; + + public PackagesWindow() + { + this.maxSize = new Vector2(550, 400); + this.minSize = new Vector2(550, 400); + } + + public void SetSelection(string packageName, string componentName) + { + selectedPackageName = packageName; + selectedComponentName = componentName; + } + + void OnGUI() + { + if (itemStyle == null) + itemStyle = new GUIStyle(GUI.skin.GetStyle("Tag MenuItem")); + + EditorGUILayout.BeginHorizontal(); + + //package list start------ + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(5); + + EditorGUILayout.BeginVertical(); + GUILayout.Space(10); + + EditorGUILayout.LabelField("Packages", (GUIStyle)"OL Title", GUILayout.Width(300)); + GUILayout.Space(5); + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(4); + + scrollPos1 = EditorGUILayout.BeginScrollView(scrollPos1, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(300)); + EditorToolSet.LoadPackages(); + List pkgs = UIPackage.GetPackages(); + int cnt = pkgs.Count; + if (cnt == 0) + { + selectedPackage = -1; + selectedPackageName = null; + } + else + { + for (int i = 0; i < cnt; i++) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(selectedPackageName == pkgs[i].name, pkgs[i].name, itemStyle, GUILayout.ExpandWidth(true))) + { + selectedPackage = i; + selectedPackageName = pkgs[i].name; + } + EditorGUILayout.EndHorizontal(); + } + } + EditorGUILayout.EndScrollView(); + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndHorizontal(); + + //package list end------ + + //component list start------ + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(5); + + EditorGUILayout.BeginVertical(); + GUILayout.Space(10); + + EditorGUILayout.LabelField("Components", (GUIStyle)"OL Title", GUILayout.Width(220)); + GUILayout.Space(5); + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(4); + + scrollPos2 = EditorGUILayout.BeginScrollView(scrollPos2, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(220)); + if (selectedPackage >= 0) + { + List items = pkgs[selectedPackage].GetItems(); + int i = 0; + foreach (PackageItem pi in items) + { + if (pi.type == PackageItemType.Component && pi.exported) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(selectedComponentName == pi.name, pi.name, itemStyle, GUILayout.ExpandWidth(true))) + selectedComponentName = pi.name; + i++; + EditorGUILayout.EndHorizontal(); + } + } + } + EditorGUILayout.EndScrollView(); + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndHorizontal(); + + //component list end------ + + GUILayout.Space(10); + + EditorGUILayout.EndHorizontal(); + + GUILayout.Space(20); + + //buttons start--- + EditorGUILayout.BeginHorizontal(); + + GUILayout.Space(180); + + if (GUILayout.Button("Refresh", GUILayout.Width(100))) + EditorToolSet.ReloadPackages(); + + GUILayout.Space(20); + if (GUILayout.Button("OK", GUILayout.Width(100)) && selectedPackage >= 0) + { + UIPackage selectedPkg = pkgs[selectedPackage]; + string tmp = selectedPkg.assetPath.ToLower(); + string packagePath; + int pos = tmp.LastIndexOf("/resources/"); + if (pos != -1) + packagePath = selectedPkg.assetPath.Substring(pos + 11); + else + { + pos = tmp.IndexOf("resources/"); + if (pos == 0) + packagePath = selectedPkg.assetPath.Substring(pos + 10); + else + packagePath = selectedPkg.assetPath; + } + if (Selection.activeGameObject != null) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(Selection.activeGameObject) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(Selection.activeGameObject) == PrefabType.Prefab; +#endif + Selection.activeGameObject.SendMessage("OnUpdateSource", + new object[] { selectedPkg.name, packagePath, selectedComponentName, !isPrefab }, + SendMessageOptions.DontRequireReceiver); + } + +#if UNITY_2018_3_OR_NEWER + PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); + if (prefabStage != null) + EditorSceneManager.MarkSceneDirty(prefabStage.scene); + else + ApplyChange(); +#else + ApplyChange(); +#endif + this.Close(); + } + + EditorGUILayout.EndHorizontal(); + } + + void ApplyChange() + { +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(Selection.activeGameObject); +#endif + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs.meta new file mode 100644 index 0000000..edce905 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/PackagesWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83ed477a96af9c94f9f2ccc24b5a24c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs new file mode 100644 index 0000000..50939b6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs @@ -0,0 +1,29 @@ +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(StageCamera))] + public class StageCameraEditor : Editor + { + string[] propertyToExclude; + + void OnEnable() + { + propertyToExclude = new string[] { "m_Script" }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + if (serializedObject.ApplyModifiedProperties()) + (target as StageCamera).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs.meta new file mode 100644 index 0000000..20225a6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/StageCameraEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b99582678b83dc46986b02984c665a3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs new file mode 100644 index 0000000..d69a80f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs @@ -0,0 +1,226 @@ +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIConfig))] + public class UIConfigEditor : Editor + { + string[] propertyToExclude; + bool itemsFoldout; + bool packagesFoldOut; + int errorState; + + private const float kButtonWidth = 18f; + + void OnEnable() + { + propertyToExclude = new string[] { "m_Script", "Items", "PreloadPackages" }; + + itemsFoldout = EditorPrefs.GetBool("itemsFoldOut"); + packagesFoldOut = EditorPrefs.GetBool("packagesFoldOut"); + errorState = 0; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + UIConfig config = (UIConfig)target; + + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + itemsFoldout = EditorGUILayout.Foldout(itemsFoldout, "Config Items"); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetBool("itemsFoldOut", itemsFoldout); + EditorGUILayout.EndHorizontal(); + + bool modified = false; + + if (itemsFoldout) + { + Undo.RecordObject(config, "Items"); + + int len = config.Items.Count; + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Add"); + UIConfig.ConfigKey selectedKey = (UIConfig.ConfigKey)EditorGUILayout.EnumPopup((System.Enum)UIConfig.ConfigKey.PleaseSelect); + + if (selectedKey != UIConfig.ConfigKey.PleaseSelect) + { + int index = (int)selectedKey; + + if (index > len - 1) + { + for (int i = len; i < index; i++) + config.Items.Add(new UIConfig.ConfigValue()); + + UIConfig.ConfigValue value = new UIConfig.ConfigValue(); + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + config.Items.Add(value); + } + else + { + UIConfig.ConfigValue value = config.Items[index]; + if (value == null) + { + value = new UIConfig.ConfigValue(); + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + config.Items[index] = value; + } + else if (!value.valid) + { + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + } + } + } + EditorGUILayout.EndHorizontal(); + + for (int i = 0; i < len; i++) + { + UIConfig.ConfigValue value = config.Items[i]; + if (value == null || !value.valid) + continue; + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(((UIConfig.ConfigKey)i).ToString()); + switch ((UIConfig.ConfigKey)i) + { + case UIConfig.ConfigKey.ClickDragSensitivity: + case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount: + case UIConfig.ConfigKey.DefaultScrollStep: + case UIConfig.ConfigKey.TouchDragSensitivity: + case UIConfig.ConfigKey.TouchScrollSensitivity: + case UIConfig.ConfigKey.InputCaretSize: + value.i = EditorGUILayout.IntField(value.i); + break; + + case UIConfig.ConfigKey.ButtonSound: + case UIConfig.ConfigKey.GlobalModalWaiting: + case UIConfig.ConfigKey.HorizontalScrollBar: + case UIConfig.ConfigKey.LoaderErrorSign: + case UIConfig.ConfigKey.PopupMenu: + case UIConfig.ConfigKey.PopupMenu_seperator: + case UIConfig.ConfigKey.TooltipsWin: + case UIConfig.ConfigKey.VerticalScrollBar: + case UIConfig.ConfigKey.WindowModalWaiting: + case UIConfig.ConfigKey.DefaultFont: + value.s = EditorGUILayout.TextField(value.s); + break; + + case UIConfig.ConfigKey.DefaultScrollBounceEffect: + case UIConfig.ConfigKey.DefaultScrollTouchEffect: + case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop: + case UIConfig.ConfigKey.AllowSoftnessOnTopOrLeftSide: + case UIConfig.ConfigKey.DepthSupportForPaintingMode: + value.b = EditorGUILayout.Toggle(value.b); + break; + + case UIConfig.ConfigKey.ButtonSoundVolumeScale: + value.f = EditorGUILayout.Slider(value.f, 0, 1); + break; + + case UIConfig.ConfigKey.ModalLayerColor: + case UIConfig.ConfigKey.InputHighlightColor: + value.c = EditorGUILayout.ColorField(value.c); + break; + + case UIConfig.ConfigKey.Branch: + EditorGUI.BeginChangeCheck(); + value.s = EditorGUILayout.TextField(value.s); + if (EditorGUI.EndChangeCheck()) + modified = true; + break; + } + + if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) + { + config.Items[i].Reset(); + UIConfig.SetDefaultValue((UIConfig.ConfigKey)i, config.Items[i]); + modified = true; + } + EditorGUILayout.EndHorizontal(); + } + } + + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + packagesFoldOut = EditorGUILayout.Foldout(packagesFoldOut, "Preload Packages"); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetBool("packagesFoldOut", packagesFoldOut); + EditorGUILayout.EndHorizontal(); + + if (packagesFoldOut) + { + Undo.RecordObject(config, "PreloadPackages"); + + EditorToolSet.LoadPackages(); + + if (EditorToolSet.packagesPopupContents != null) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Add"); + int selected = EditorGUILayout.Popup(EditorToolSet.packagesPopupContents.Length - 1, EditorToolSet.packagesPopupContents); + EditorGUILayout.EndHorizontal(); + + if (selected != EditorToolSet.packagesPopupContents.Length - 1) + { + UIPackage pkg = UIPackage.GetPackages()[selected]; + string tmp = pkg.assetPath.ToLower(); + int pos = tmp.LastIndexOf("resources/"); + if (pos != -1) + { + string packagePath = pkg.assetPath.Substring(pos + 10); + if (config.PreloadPackages.IndexOf(packagePath) == -1) + config.PreloadPackages.Add(packagePath); + + errorState = 0; + } + else + { + errorState = 10; + } + } + } + + if (errorState > 0) + { + errorState--; + EditorGUILayout.HelpBox("Package is not in resources folder.", MessageType.Warning); + } + + int cnt = config.PreloadPackages.Count; + int pi = 0; + while (pi < cnt) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("" + pi + "."); + config.PreloadPackages[pi] = EditorGUILayout.TextField(config.PreloadPackages[pi]); + if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) + { + config.PreloadPackages.RemoveAt(pi); + cnt--; + } + else + pi++; + EditorGUILayout.EndHorizontal(); + } + } + else + errorState = 0; + + if (serializedObject.ApplyModifiedProperties() || modified) + (target as UIConfig).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs.meta new file mode 100644 index 0000000..8d77c36 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIConfigEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 74df68b10ee56a54a8105d88312571ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs new file mode 100644 index 0000000..b249352 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs @@ -0,0 +1,64 @@ +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIContentScaler))] + public class UIContentScalerEditor : Editor + { + SerializedProperty scaleMode; + SerializedProperty screenMatchMode; + SerializedProperty designResolutionX; + SerializedProperty designResolutionY; + SerializedProperty fallbackScreenDPI; + SerializedProperty defaultSpriteDPI; + SerializedProperty constantScaleFactor; + SerializedProperty ignoreOrientation; + + string[] propertyToExclude; + + void OnEnable() + { + scaleMode = serializedObject.FindProperty("scaleMode"); + screenMatchMode = serializedObject.FindProperty("screenMatchMode"); + designResolutionX = serializedObject.FindProperty("designResolutionX"); + designResolutionY = serializedObject.FindProperty("designResolutionY"); + fallbackScreenDPI = serializedObject.FindProperty("fallbackScreenDPI"); + defaultSpriteDPI = serializedObject.FindProperty("defaultSpriteDPI"); + constantScaleFactor = serializedObject.FindProperty("constantScaleFactor"); + ignoreOrientation = serializedObject.FindProperty("ignoreOrientation"); + + propertyToExclude = new string[] { "m_Script", "scaleMode", "screenMatchMode", "designResolutionX", "designResolutionY", + "fallbackScreenDPI", "defaultSpriteDPI", "constantScaleFactor", "ignoreOrientation"}; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.PropertyField(scaleMode); + if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ScaleWithScreenSize) + { + EditorGUILayout.PropertyField(designResolutionX); + EditorGUILayout.PropertyField(designResolutionY); + EditorGUILayout.PropertyField(screenMatchMode); + EditorGUILayout.PropertyField(ignoreOrientation); + } + else if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ConstantPhysicalSize) + { + EditorGUILayout.PropertyField(fallbackScreenDPI); + EditorGUILayout.PropertyField(defaultSpriteDPI); + } + else + EditorGUILayout.PropertyField(constantScaleFactor); + + if (serializedObject.ApplyModifiedProperties()) + (target as UIContentScaler).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs.meta new file mode 100644 index 0000000..b4c91a3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIContentScalerEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69174d19fa9521b4283e0b8f0e85acc8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs new file mode 100644 index 0000000..ab03cc8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs @@ -0,0 +1,96 @@ +using UnityEngine; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIPainter))] + public class UIPainterEditor : Editor + { + SerializedProperty packageName; + SerializedProperty componentName; + SerializedProperty renderCamera; + SerializedProperty fairyBatching; + SerializedProperty touchDisabled; + SerializedProperty sortingOrder; + + string[] propertyToExclude; + + void OnEnable() + { + packageName = serializedObject.FindProperty("packageName"); + componentName = serializedObject.FindProperty("componentName"); + renderCamera = serializedObject.FindProperty("renderCamera"); + fairyBatching = serializedObject.FindProperty("fairyBatching"); + touchDisabled = serializedObject.FindProperty("touchDisabled"); + sortingOrder = serializedObject.FindProperty("sortingOrder"); + + propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", + "renderCamera", "fairyBatching", "touchDisabled","sortingOrder" + }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + UIPainter panel = target as UIPainter; + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Name"); + if (GUILayout.Button(packageName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + + if (GUILayout.Button("Clear", GUILayout.Width(50))) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); + +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(panel); +#endif + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Component Name"); + if (GUILayout.Button(componentName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + EditorGUILayout.EndHorizontal(); + int oldSortingOrder = panel.sortingOrder; + EditorGUILayout.PropertyField(sortingOrder); + EditorGUILayout.PropertyField(renderCamera); + EditorGUILayout.PropertyField(fairyBatching); + EditorGUILayout.PropertyField(touchDisabled); + + if (serializedObject.ApplyModifiedProperties()) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + if (!isPrefab) + { + panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs.meta new file mode 100644 index 0000000..647a636 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPainterEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5cb0f73c030157845aaa7b42a2b8d577 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs new file mode 100644 index 0000000..b4dee1b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs @@ -0,0 +1,163 @@ +using UnityEngine; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +using UnityEditor; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(FairyGUI.UIPanel))] + public class UIPanelEditor : Editor + { + SerializedProperty packageName; + SerializedProperty componentName; + SerializedProperty packagePath; + SerializedProperty renderMode; + SerializedProperty renderCamera; + SerializedProperty sortingOrder; + SerializedProperty position; + SerializedProperty scale; + SerializedProperty rotation; + SerializedProperty fairyBatching; + SerializedProperty fitScreen; + SerializedProperty touchDisabled; + SerializedProperty hitTestMode; + SerializedProperty setNativeChildrenOrder; + + string[] propertyToExclude; + + void OnEnable() + { + packageName = serializedObject.FindProperty("packageName"); + componentName = serializedObject.FindProperty("componentName"); + packagePath = serializedObject.FindProperty("packagePath"); + renderMode = serializedObject.FindProperty("renderMode"); + renderCamera = serializedObject.FindProperty("renderCamera"); + sortingOrder = serializedObject.FindProperty("sortingOrder"); + position = serializedObject.FindProperty("position"); + scale = serializedObject.FindProperty("scale"); + rotation = serializedObject.FindProperty("rotation"); + fairyBatching = serializedObject.FindProperty("fairyBatching"); + fitScreen = serializedObject.FindProperty("fitScreen"); + touchDisabled = serializedObject.FindProperty("touchDisabled"); + hitTestMode = serializedObject.FindProperty("hitTestMode"); + setNativeChildrenOrder = serializedObject.FindProperty("setNativeChildrenOrder"); + + + propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", "renderMode", + "renderCamera", "sortingOrder", "position", "scale", "rotation", "fairyBatching", "fitScreen","touchDisabled", + "hitTestMode","cachedUISize","setNativeChildrenOrder" + }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + FairyGUI.UIPanel panel = target as FairyGUI.UIPanel; + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Name"); + if (GUILayout.Button(packageName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + + if (GUILayout.Button("Clear", GUILayout.Width(50))) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); + +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(panel); +#endif + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Component Name"); + if (GUILayout.Button(componentName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Path"); + EditorGUILayout.LabelField(packagePath.stringValue, (GUIStyle)"helpbox"); + EditorGUILayout.EndHorizontal(); + + if (Application.isPlaying) + EditorGUILayout.EnumPopup("Render Mode", panel.container.renderMode); + else + EditorGUILayout.PropertyField(renderMode); + if ((RenderMode)renderMode.enumValueIndex != RenderMode.ScreenSpaceOverlay) + EditorGUILayout.PropertyField(renderCamera); + + int oldSortingOrder = panel.sortingOrder; + EditorGUILayout.PropertyField(sortingOrder); + EditorGUILayout.PropertyField(fairyBatching); + EditorGUILayout.PropertyField(hitTestMode); + EditorGUILayout.PropertyField(touchDisabled); + EditorGUILayout.PropertyField(setNativeChildrenOrder); + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("UI Transform", (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(position); + EditorGUILayout.PropertyField(rotation); + EditorGUILayout.PropertyField(scale); + EditorGUILayout.Space(); + + FairyGUI.FitScreen oldFitScreen = (FairyGUI.FitScreen)fitScreen.enumValueIndex; + EditorGUILayout.PropertyField(fitScreen); + + if (serializedObject.ApplyModifiedProperties()) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + if (!isPrefab) + { + panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder, (FairyGUI.FitScreen)fitScreen.enumValueIndex != oldFitScreen); + } + } + } + + void OnSceneGUI() + { + FairyGUI.UIPanel panel = (target as FairyGUI.UIPanel); + if (panel.container == null) + return; + + Vector3 pos = panel.GetUIWorldPosition(); + float sizeFactor = HandleUtility.GetHandleSize(pos); +#if UNITY_2017_1_OR_NEWER + var fmh_147_58_638610608245431676 = Quaternion.identity; Vector3 newPos = Handles.FreeMoveHandle(pos, sizeFactor, Vector3.one, Handles.ArrowHandleCap); +#else + Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowCap); +#endif + if (newPos != pos) + { + Vector2 v1 = HandleUtility.WorldToGUIPoint(pos); + Vector2 v2 = HandleUtility.WorldToGUIPoint(newPos); + Vector3 delta = v2 - v1; + delta.x = (int)delta.x; + delta.y = (int)delta.y; + + panel.MoveUI(delta); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs.meta new file mode 100644 index 0000000..f7919f8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Editor/UIPanelEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 94949994c6eda08448145f618d0db72f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event.meta new file mode 100644 index 0000000..ff97444 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: faa71f0e576742d46865b6bb7422b7f0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs new file mode 100644 index 0000000..38bd08a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs @@ -0,0 +1,176 @@ +#if FAIRYGUI_TOLUA +using System; +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + class EventBridge + { + public EventDispatcher owner; + + EventCallback0 _callback0; + EventCallback1 _callback1; + EventCallback1 _captureCallback; + internal bool _dispatching; + + public EventBridge(EventDispatcher owner) + { + this.owner = owner; + } + + public void AddCapture(EventCallback1 callback) + { + _captureCallback -= callback; + _captureCallback += callback; + } + + public void RemoveCapture(EventCallback1 callback) + { + _captureCallback -= callback; + } + + public void Add(EventCallback1 callback) + { + _callback1 -= callback; + _callback1 += callback; + } + + public void Remove(EventCallback1 callback) + { + _callback1 -= callback; + } + + public void Add(EventCallback0 callback) + { + _callback0 -= callback; + _callback0 += callback; + } + + public void Remove(EventCallback0 callback) + { + _callback0 -= callback; + } + +#if FAIRYGUI_TOLUA + public void Add(LuaFunction func, LuaTable self) + { + EventCallback1 callback; + if(self != null) + callback = (EventCallback1)DelegateTraits.Create(func, self); + else + callback = (EventCallback1)DelegateTraits.Create(func); + _callback1 -= callback; + _callback1 += callback; + } + + public void Add(LuaFunction func, GComponent self) + { + if (self._peerTable == null) + throw new Exception("self is not connected to lua."); + + Add(func, self._peerTable); + } + + public void Remove(LuaFunction func, LuaTable self) + { + LuaState state = func.GetLuaState(); + LuaDelegate target; + if (self != null) + target = state.GetLuaDelegate(func, self); + else + target = state.GetLuaDelegate(func); + + Delegate[] ds = _callback1.GetInvocationList(); + + for (int i = 0; i < ds.Length; i++) + { + LuaDelegate ld = ds[i].Target as LuaDelegate; + if (ld != null && ld.Equals(target)) + { + _callback1 = (EventCallback1)Delegate.Remove(_callback1, ds[i]); + //DelayDispose will cause problem + //state.DelayDispose(ld.func); + //if (ld.self != null) + // state.DelayDispose(ld.self); + break; + } + } + } + + public void Remove(LuaFunction func, GComponent self) + { + if (self._peerTable == null) + throw new Exception("self is not connected to lua."); + + Remove(func, self._peerTable); + } +#endif + + public bool isEmpty + { + get { return _callback1 == null && _callback0 == null && _captureCallback == null; } + } + + public void Clear() + { +#if FAIRYGUI_TOLUA + //if (_callback1 != null) + //{ + // Delegate[] ds = _callback1.GetInvocationList(); + // for (int i = 0; i < ds.Length; i++) + // { + // LuaDelegate ld = ds[i].Target as LuaDelegate; + // if (ld != null) + // { + // LuaState state = ld.func.GetLuaState(); + // state.DelayDispose(ld.func); + // if (ld.self != null) + // state.DelayDispose(ld.self); + // } + // } + //} +#endif + _callback1 = null; + _callback0 = null; + _captureCallback = null; + } + + public void CallInternal(EventContext context) + { + _dispatching = true; + context.sender = owner; + try + { + if (_callback1 != null) + _callback1(context); + if (_callback0 != null) + _callback0(); + } + finally + { + _dispatching = false; + } + } + + public void CallCaptureInternal(EventContext context) + { + if (_captureCallback == null) + return; + + _dispatching = true; + context.sender = owner; + try + { + _captureCallback(context); + } + finally + { + _dispatching = false; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs.meta new file mode 100644 index 0000000..b6c4085 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventBridge.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e9712bee5e6977647989e012a6a332a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs new file mode 100644 index 0000000..2ff8134 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs @@ -0,0 +1,94 @@ +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + public class EventContext + { + /// + /// + /// + public EventDispatcher sender { get; internal set; } + + /// + /// / + /// + public object initiator { get; internal set; } + + /// + /// / + /// + public InputEvent inputEvent { get; internal set; } + + /// + /// + /// + public string type; + + /// + /// + /// + public object data; + + internal bool _defaultPrevented; + internal bool _stopsPropagation; + internal bool _touchCapture; + + internal List callChain = new List(); + + /// + /// + /// + public void StopPropagation() + { + _stopsPropagation = true; + } + + /// + /// + /// + public void PreventDefault() + { + _defaultPrevented = true; + } + + /// + /// + /// + public void CaptureTouch() + { + _touchCapture = true; + } + + /// + /// + /// + public bool isDefaultPrevented + { + get { return _defaultPrevented; } + } + + static Stack pool = new Stack(); + internal static EventContext Get() + { + if (pool.Count > 0) + { + EventContext context = pool.Pop(); + context._stopsPropagation = false; + context._defaultPrevented = false; + context._touchCapture = false; + return context; + } + else + return new EventContext(); + } + + internal static void Return(EventContext value) + { + pool.Push(value); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs.meta new file mode 100644 index 0000000..bc3781f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3391a1fa2fc33b7448dfdf3e7c48880d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs new file mode 100644 index 0000000..e3f2b21 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs @@ -0,0 +1,515 @@ +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + public delegate void EventCallback0(); + public delegate void EventCallback1(EventContext context); + + /// + /// + /// + public class EventDispatcher : IEventDispatcher + { + Dictionary _dic; + + public EventDispatcher() + { + } + + /// + /// + /// + /// + /// + public void AddEventListener(string strType, EventCallback1 callback) + { + GetBridge(strType).Add(callback); + } + + /// + /// + /// + /// + /// + public void AddEventListener(string strType, EventCallback0 callback) + { + GetBridge(strType).Add(callback); + } + + /// + /// + /// + /// + /// + public void RemoveEventListener(string strType, EventCallback1 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Remove(callback); + } + + /// + /// + /// + /// + /// + public void RemoveEventListener(string strType, EventCallback0 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Remove(callback); + } + + /// + /// + /// + /// + /// + public void AddCapture(string strType, EventCallback1 callback) + { + GetBridge(strType).AddCapture(callback); + } + + /// + /// + /// + /// + /// + public void RemoveCapture(string strType, EventCallback1 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.RemoveCapture(callback); + } + + /// + /// + /// + public void RemoveEventListeners() + { + RemoveEventListeners(null); + } + + /// + /// + /// + /// + public void RemoveEventListeners(string strType) + { + if (_dic == null) + return; + + if (strType != null) + { + EventBridge bridge; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Clear(); + } + else + { + foreach (KeyValuePair kv in _dic) + kv.Value.Clear(); + } + } + + /// + /// + /// + /// + /// + public bool hasEventListeners(string strType) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge == null) + return false; + + return !bridge.isEmpty; + } + + /// + /// + /// + /// + /// + public bool isDispatching(string strType) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge == null) + return false; + + return bridge._dispatching; + } + + internal EventBridge TryGetEventBridge(string strType) + { + if (_dic == null) + return null; + + EventBridge bridge = null; + _dic.TryGetValue(strType, out bridge); + return bridge; + } + + internal EventBridge GetEventBridge(string strType) + { + if (_dic == null) + _dic = new Dictionary(); + + EventBridge bridge = null; + if (!_dic.TryGetValue(strType, out bridge)) + { + bridge = new EventBridge(this); + _dic[strType] = bridge; + } + return bridge; + } + + /// + /// + /// + /// + /// + public bool DispatchEvent(string strType) + { + return DispatchEvent(strType, null); + } + + /// + /// + /// + /// + /// + /// + public bool DispatchEvent(string strType, object data) + { + return InternalDispatchEvent(strType, null, data, null); + } + + public bool DispatchEvent(string strType, object data, object initiator) + { + return InternalDispatchEvent(strType, null, data, initiator); + } + + static InputEvent sCurrentInputEvent = new InputEvent(); + + internal bool InternalDispatchEvent(string strType, EventBridge bridge, object data, object initiator) + { + if (bridge == null) + bridge = TryGetEventBridge(strType); + + EventBridge gBridge = null; + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); + + bool b1 = bridge != null && !bridge.isEmpty; + bool b2 = gBridge != null && !gBridge.isEmpty; + if (b1 || b2) + { + EventContext context = EventContext.Get(); + context.initiator = initiator != null ? initiator : this; + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + + if (b1) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + + if (b2) + { + gBridge.CallCaptureInternal(context); + gBridge.CallInternal(context); + } + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + + return context._defaultPrevented; + } + else + return false; + } + + /// + /// + /// + /// + /// + public bool DispatchEvent(EventContext context) + { + EventBridge bridge = TryGetEventBridge(context.type); + EventBridge gBridge = null; + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(context.type); + + EventDispatcher savedSender = context.sender; + + if (bridge != null && !bridge.isEmpty) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + + if (gBridge != null && !gBridge.isEmpty) + { + gBridge.CallCaptureInternal(context); + gBridge.CallInternal(context); + } + + context.sender = savedSender; + return context._defaultPrevented; + } + + /// + /// + /// + /// + /// + /// + /// + internal bool BubbleEvent(string strType, object data, List addChain) + { + EventContext context = EventContext.Get(); + context.initiator = this; + + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + List bubbleChain = context.callChain; + bubbleChain.Clear(); + + GetChainBridges(strType, bubbleChain, true); + + int length = bubbleChain.Count; + for (int i = length - 1; i >= 0; i--) + { + bubbleChain[i].CallCaptureInternal(context); + if (context._touchCapture) + { + context._touchCapture = false; + if (strType == "onTouchBegin") + Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); + } + } + + if (!context._stopsPropagation) + { + for (int i = 0; i < length; ++i) + { + bubbleChain[i].CallInternal(context); + + if (context._touchCapture) + { + context._touchCapture = false; + if (strType == "onTouchBegin") + Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); + } + + if (context._stopsPropagation) + break; + } + + if (addChain != null) + { + length = addChain.Count; + for (int i = 0; i < length; ++i) + { + EventBridge bridge = addChain[i]; + if (bubbleChain.IndexOf(bridge) == -1) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + } + } + } + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + return context._defaultPrevented; + } + + /// + /// + /// + /// + /// + /// + public bool BubbleEvent(string strType, object data) + { + return BubbleEvent(strType, data, null); + } + + /// + /// + /// + /// + /// + /// + public bool BroadcastEvent(string strType, object data) + { + EventContext context = EventContext.Get(); + context.initiator = this; + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + List bubbleChain = context.callChain; + bubbleChain.Clear(); + + if (this is Container) + GetChildEventBridges(strType, (Container)this, bubbleChain); + else if (this is GComponent) + GetChildEventBridges(strType, (GComponent)this, bubbleChain); + + int length = bubbleChain.Count; + for (int i = 0; i < length; ++i) + bubbleChain[i].CallInternal(context); + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + return context._defaultPrevented; + } + + EventBridge GetBridge(string strType) + { + if (strType == null) + throw new Exception("event type cant be null"); + + if (_dic == null) + _dic = new Dictionary(); + + EventBridge bridge = null; + if (!_dic.TryGetValue(strType, out bridge)) + { + bridge = new EventBridge(this); + _dic[strType] = bridge; + } + + return bridge; + } + + static void GetChildEventBridges(string strType, Container container, List bridges) + { + EventBridge bridge = container.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + if (container.gOwner != null) + { + bridge = container.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + } + + int count = container.numChildren; + for (int i = 0; i < count; ++i) + { + DisplayObject obj = container.GetChildAt(i); + if (obj is Container) + GetChildEventBridges(strType, (Container)obj, bridges); + else + { + bridge = obj.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + + if (obj.gOwner != null) + { + bridge = obj.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + } + } + } + } + + static void GetChildEventBridges(string strType, GComponent container, List bridges) + { + EventBridge bridge = container.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + + int count = container.numChildren; + for (int i = 0; i < count; ++i) + { + GObject obj = container.GetChildAt(i); + if (obj is GComponent) + GetChildEventBridges(strType, (GComponent)obj, bridges); + else + { + bridge = obj.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + } + } + } + + internal void GetChainBridges(string strType, List chain, bool bubble) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + { + bridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + + if (!bubble) + return; + + if (this is DisplayObject) + { + DisplayObject element = (DisplayObject)this; + while ((element = element.parent) != null) + { + bridge = element.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + + if (element.gOwner != null) + { + bridge = element.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + } + } + else if (this is GObject) + { + GObject element = (GObject)this; + while ((element = element.parent) != null) + { + bridge = element.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs.meta new file mode 100644 index 0000000..52ef516 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f31d18fa6488bb469504c7128522d21 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs new file mode 100644 index 0000000..3373ea4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs @@ -0,0 +1,267 @@ +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public class EventListener + { + EventBridge _bridge; + string _type; + + public EventListener(EventDispatcher owner, string type) + { + _bridge = owner.GetEventBridge(type); + _type = type; + } + + /// + /// + /// + public string type + { + get { return _type; } + } + + /// + /// + /// + /// + public void AddCapture(EventCallback1 callback) + { + _bridge.AddCapture(callback); + } + + /// + /// + /// + /// + public void RemoveCapture(EventCallback1 callback) + { + _bridge.RemoveCapture(callback); + } + + /// + /// + /// + /// + public void Add(EventCallback1 callback) + { + _bridge.Add(callback); + } + + /// + /// + /// + /// + public void Remove(EventCallback1 callback) + { + _bridge.Remove(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Add(EventCallback0 callback) + { + _bridge.Add(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Remove(EventCallback0 callback) + { + _bridge.Remove(callback); + } + + /// + /// + /// + /// + public void Set(EventCallback1 callback) + { + _bridge.Clear(); + if (callback != null) + _bridge.Add(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Set(EventCallback0 callback) + { + _bridge.Clear(); + if (callback != null) + _bridge.Add(callback); + } + +#if FAIRYGUI_TOLUA + /// + /// + /// + /// + /// + public void Add(LuaFunction func, LuaTable self) + { + _bridge.Add(func, self); + } + + /// + /// + /// + /// + /// + public void Add(LuaFunction func, GComponent self) + { + _bridge.Add(func, self); + } + + /// + /// + /// + /// + /// + public void Remove(LuaFunction func, LuaTable self) + { + _bridge.Remove(func, self); + } + + /// + /// + /// + /// + /// + public void Remove(LuaFunction func, GComponent self) + { + _bridge.Remove(func, self); + } + + /// + /// + /// + /// + /// + public void Set(LuaFunction func, LuaTable self) + { + _bridge.Clear(); + if (func != null) + Add(func, self); + } + + /// + /// + /// + /// + /// + public void Set(LuaFunction func, GComponent self) + { + _bridge.Clear(); + if (func != null) + Add(func, self); + } +#endif + + /// + /// + /// + public bool isEmpty + { + get + { + return !_bridge.owner.hasEventListeners(_type); + } + } + + /// + /// + /// + public bool isDispatching + { + get + { + return _bridge.owner.isDispatching(_type); + } + } + + /// + /// + /// + public void Clear() + { + _bridge.Clear(); + } + + /// + /// + /// + /// + public bool Call() + { + return _bridge.owner.InternalDispatchEvent(_type, _bridge, null, null); + } + + /// + /// + /// + /// + /// + public bool Call(object data) + { + return _bridge.owner.InternalDispatchEvent(_type, _bridge, data, null); + } + + /// + /// + /// + /// + /// + public bool BubbleCall(object data) + { + return _bridge.owner.BubbleEvent(_type, data); + } + + /// + /// + /// + /// + public bool BubbleCall() + { + return _bridge.owner.BubbleEvent(_type, null); + } + + /// + /// + /// + /// + /// + public bool BroadcastCall(object data) + { + return _bridge.owner.BroadcastEvent(_type, data); + } + + /// + /// + /// + /// + public bool BroadcastCall() + { + return _bridge.owner.BroadcastEvent(_type, null); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs.meta new file mode 100644 index 0000000..78de4c5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/EventListener.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8747c4706bc8c864786f691555eaa2fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs new file mode 100644 index 0000000..dc50a54 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs @@ -0,0 +1,17 @@ +namespace FairyGUI +{ + /// + /// + /// + public interface IEventDispatcher + { + void AddEventListener(string strType, EventCallback0 callback); + void AddEventListener(string strType, EventCallback1 callback); + void RemoveEventListener(string strType, EventCallback0 callback); + void RemoveEventListener(string strType, EventCallback1 callback); + bool DispatchEvent(EventContext context); + bool DispatchEvent(string strType); + bool DispatchEvent(string strType, object data); + bool DispatchEvent(string strType, object data, object initiator); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs.meta new file mode 100644 index 0000000..2dfa6cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/IEventDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a8dfc3c6bb6a91445b52cee1e916c398 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs new file mode 100644 index 0000000..d5d95df --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs @@ -0,0 +1,149 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class InputEvent + { + /// + /// x position in stage coordinates. + /// + public float x { get; internal set; } + + /// + /// y position in stage coordinates. + /// + public float y { get; internal set; } + + /// + /// + /// + public KeyCode keyCode { get; internal set; } + + /// + /// + /// + public char character { get; internal set; } + + /// + /// + /// + public EventModifiers modifiers { get; internal set; } + + /// + /// + /// + public float mouseWheelDelta { get; internal set; } + + /// + /// + /// + public int touchId { get; internal set; } + + /// + /// -1-none,0-left,1-right,2-middle + /// + public int button { get; internal set; } + + /// + /// + /// + /// + public int clickCount { get; internal set; } + + /// + /// Duraion of holding the button. You can read this in touchEnd or click event. + /// + /// + public float holdTime { get; internal set; } + + public InputEvent() + { + touchId = -1; + x = 0; + y = 0; + clickCount = 0; + keyCode = KeyCode.None; + character = '\0'; + modifiers = 0; + mouseWheelDelta = 0; + } + + /// + /// + /// + public Vector2 position + { + get { return new Vector2(x, y); } + } + + /// + /// + /// + public bool isDoubleClick + { + get { return clickCount > 1 && button == 0; } + } + + /// + /// + /// + public bool ctrlOrCmd + { + get + { + return ctrl || command; + } + } + + /// + /// + /// + public bool ctrl + { + get + { + return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); + } + } + + /// + /// + /// + public bool shift + { + get + { + return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); + } + } + + /// + /// + /// + public bool alt + { + get + { + return Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); + } + } + + /// + /// + /// + public bool command + { + get + { + //In win, as long as the win key and other keys are pressed at the same time, the getKey will continue to return true. So it can only be shielded. + if (Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXEditor) + return Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightCommand); + else + return false; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs.meta new file mode 100644 index 0000000..96474f6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Event/InputEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc16eca0c17d9344882b6e63f26ecc9e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter.meta new file mode 100644 index 0000000..b6bd4b5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 433dd68fcd8eedd489b1c789a3bdd726 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs new file mode 100644 index 0000000..6d5160e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs @@ -0,0 +1,101 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class BlurFilter : IFilter + { + //ref http://blog.csdn.net/u011047171/article/details/47947397 + + /// + /// + /// + public float blurSize; + + DisplayObject _target; + Material _blitMaterial; + + public BlurFilter() + { + blurSize = 1f; + } + + public DisplayObject target + { + get { return _target; } + set + { + _target = value; + _target.EnterPaintingMode(1, null); + _target.onPaint += OnRenderImage; + + _blitMaterial = new Material(ShaderConfig.GetShader("FairyGUI/BlurFilter")); + _blitMaterial.hideFlags = DisplayObject.hideFlags; + } + } + + public void Dispose() + { + _target.LeavePaintingMode(1); + _target.onPaint -= OnRenderImage; + _target = null; + + if (Application.isPlaying) + Material.Destroy(_blitMaterial); + else + Material.DestroyImmediate(_blitMaterial); + } + + public void Update() + { + } + + void FourTapCone(RenderTexture source, RenderTexture dest, int iteration) + { + float off = blurSize * iteration + 0.5f; + Graphics.BlitMultiTap(source, dest, _blitMaterial, + new Vector2(-off, -off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); + } + + void DownSample4x(RenderTexture source, RenderTexture dest) + { + float off = 1.0f; + Graphics.BlitMultiTap(source, dest, _blitMaterial, + new Vector2(off, off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); + } + + void OnRenderImage() + { + if (blurSize < 0.01) + return; + + RenderTexture sourceTexture = (RenderTexture)_target.paintingGraphics.texture.nativeTexture; + int rtW = sourceTexture.width / 8; + int rtH = sourceTexture.height / 8; + RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0); + + DownSample4x(sourceTexture, buffer); + + for (int i = 0; i < 2; i++) + { + RenderTexture buffer2 = RenderTexture.GetTemporary(rtW, rtH, 0); + FourTapCone(buffer, buffer2, i); + RenderTexture.ReleaseTemporary(buffer); + buffer = buffer2; + } + Graphics.Blit(buffer, sourceTexture); + + RenderTexture.ReleaseTemporary(buffer); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs.meta new file mode 100644 index 0000000..7e86c3f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/BlurFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 93a10729ff0ced14c97c9ae9d4771c4c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs new file mode 100644 index 0000000..ac7f1db --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs @@ -0,0 +1,237 @@ +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class ColorFilter : IFilter + { + // Most of the color transformation math was taken from the excellent ColorMatrixFilter class in Starling Framework + + DisplayObject _target; + float[] _matrix; + + const float LUMA_R = 0.299f; + const float LUMA_G = 0.587f; + const float LUMA_B = 0.114f; + + static float[] IDENTITY = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; + static float[] tmp = new float[20]; + + public ColorFilter() + { + _matrix = new float[20]; + Array.Copy(IDENTITY, _matrix, _matrix.Length); + } + + public DisplayObject target + { + get { return _target; } + set + { + _target = value; + + //这里做一个优化,如果对象是图片或者动画,则通过直接修改目标的材质完成滤镜功能 + if ((_target is Image) || (_target is MovieClip)) + _target.graphics.ToggleKeyword("COLOR_FILTER", true); + else //否则通过绘画模式,需要建立一张RT,所以会有一定消耗 + { + _target.EnterPaintingMode(1, null); + _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", true); + } + + UpdateMatrix(); + } + } + + public void Dispose() + { + if (!_target.isDisposed) + { + if ((_target is Image) || (_target is MovieClip)) + _target.graphics.ToggleKeyword("COLOR_FILTER", false); + else + { + _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", false); + _target.LeavePaintingMode(1); + } + } + + _target = null; + } + + public void Update() + { + } + + public void Invert() + { + _ConcatValues(0, -1, 0, 0, 0, 1); + _ConcatValues(1, 0, -1, 0, 0, 1); + _ConcatValues(2, 0, 0, -1, 0, 1); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the saturation. Typical values are in the range (-1, 1). + /// Values above zero will raise, values below zero will reduce the saturation. + /// '-1' will produce a grayscale image. + /// + /// + public void AdjustSaturation(float sat) + { + sat += 1; + + float invSat = 1 - sat; + float invLumR = invSat * LUMA_R; + float invLumG = invSat * LUMA_G; + float invLumB = invSat * LUMA_B; + + _ConcatValues(0, (invLumR + sat), invLumG, invLumB, 0, 0); + _ConcatValues(1, invLumR, (invLumG + sat), invLumB, 0, 0); + _ConcatValues(2, invLumR, invLumG, (invLumB + sat), 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the contrast. Typical values are in the range (-1, 1). + /// Values above zero will raise, values below zero will reduce the contrast. + /// + /// + public void AdjustContrast(float value) + { + float s = value + 1; + float o = 128f / 255 * (1 - s); + + _ConcatValues(0, s, 0, 0, 0, o); + _ConcatValues(1, 0, s, 0, 0, o); + _ConcatValues(2, 0, 0, s, 0, o); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the brightness. Typical values are in the range (-1, 1). + /// Values above zero will make the image brighter, values below zero will make it darker. + /// + /// + public void AdjustBrightness(float value) + { + _ConcatValues(0, 1, 0, 0, 0, value); + _ConcatValues(1, 0, 1, 0, 0, value); + _ConcatValues(2, 0, 0, 1, 0, value); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + ///Changes the hue of the image. Typical values are in the range (-1, 1). + /// + /// + public void AdjustHue(float value) + { + value *= Mathf.PI; + + float cos = Mathf.Cos(value); + float sin = Mathf.Sin(value); + + _ConcatValues(0, ((LUMA_R + (cos * (1 - LUMA_R))) + (sin * -(LUMA_R))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * -(LUMA_G))), ((LUMA_B + (cos * -(LUMA_B))) + (sin * (1 - LUMA_B))), 0, 0); + _ConcatValues(1, ((LUMA_R + (cos * -(LUMA_R))) + (sin * 0.143f)), ((LUMA_G + (cos * (1 - LUMA_G))) + (sin * 0.14f)), ((LUMA_B + (cos * -(LUMA_B))) + (sin * -0.283f)), 0, 0); + _ConcatValues(2, ((LUMA_R + (cos * -(LUMA_R))) + (sin * -((1 - LUMA_R)))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * LUMA_G)), ((LUMA_B + (cos * (1 - LUMA_B))) + (sin * LUMA_B)), 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Tints the image in a certain color, analog to what can be done in Adobe Animate. + /// + /// the RGB color with which the image should be tinted. + /// the intensity with which tinting should be applied. Range (0, 1). + public void Tint(Color color, float amount = 1.0f) + { + float q = 1 - amount; + + float rA = amount * color.r; + float gA = amount * color.g; + float bA = amount * color.b; + + _ConcatValues(0, q + rA * LUMA_R, rA * LUMA_G, rA * LUMA_B, 0, 0); + _ConcatValues(1, gA * LUMA_R, q + gA * LUMA_G, gA * LUMA_B, 0, 0); + _ConcatValues(2, bA * LUMA_R, bA * LUMA_G, q + bA * LUMA_B, 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the filter matrix back to the identity matrix + /// + public void Reset() + { + Array.Copy(IDENTITY, _matrix, _matrix.Length); + + UpdateMatrix(); + } + + void _ConcatValues(int index, float f0, float f1, float f2, float f3, float f4) + { + int i = index * 5; + for (int x = 0; x < 5; ++x) + { + tmp[i + x] = f0 * _matrix[x] + f1 * _matrix[x + 5] + f2 * _matrix[x + 10] + f3 * _matrix[x + 15] + (x == 4 ? f4 : 0); + } + + if (index == 3) + { + Array.Copy(tmp, _matrix, tmp.Length); + + UpdateMatrix(); + } + } + + /// + /// + /// + /// + public void ConcatValues(params float[] values) + { + int i = 0; + + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 5; ++x) + { + tmp[i + x] = values[i] * _matrix[x] + + values[i + 1] * _matrix[x + 5] + + values[i + 2] * _matrix[x + 10] + + values[i + 3] * _matrix[x + 15] + + (x == 4 ? values[i + 4] : 0); + } + i += 5; + } + Array.Copy(tmp, _matrix, tmp.Length); + + UpdateMatrix(); + } + + void UpdateMatrix() + { + if (_target == null) + return; + + Matrix4x4 matrix = new Matrix4x4(); + matrix.SetRow(0, new Vector4(_matrix[0], _matrix[1], _matrix[2], _matrix[3])); + matrix.SetRow(1, new Vector4(_matrix[5], _matrix[6], _matrix[7], _matrix[8])); + matrix.SetRow(2, new Vector4(_matrix[10], _matrix[11], _matrix[12], _matrix[13])); + matrix.SetRow(3, new Vector4(_matrix[15], _matrix[16], _matrix[17], _matrix[18])); + + Vector4 offset = new Vector4(_matrix[4], _matrix[9], _matrix[14], _matrix[19]); + + MaterialPropertyBlock block; + if ((_target is Image) || (_target is MovieClip)) + block = _target.graphics.materialPropertyBlock; + else + block = _target.paintingGraphics.materialPropertyBlock; + + block.SetMatrix(ShaderConfig.ID_ColorMatrix, matrix); + block.SetVector(ShaderConfig.ID_ColorOffset, offset); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs.meta new file mode 100644 index 0000000..6bf7b82 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/ColorFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f03204401ceeb6d4dad6b55e0889c0ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs new file mode 100644 index 0000000..202895f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs @@ -0,0 +1,20 @@ +namespace FairyGUI +{ + public interface IFilter + { + /// + /// + /// + DisplayObject target { get; set; } + + /// + /// + /// + void Update(); + + /// + /// + /// + void Dispose(); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs.meta new file mode 100644 index 0000000..3ff4229 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Filter/IFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c508023e115ed34a94f92161160ef24 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture.meta new file mode 100644 index 0000000..cbd6839 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1208c6212379851499f0b304870357dd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs new file mode 100644 index 0000000..eab3d32 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs @@ -0,0 +1,153 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 长按手势。当按下一定时间后(duration),派发onAction,如果once为false,则间隔duration时间持续派发onAction,直到手指释放。 + /// + public class LongPressGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当手指按下时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手指按下后一段时间后派发该事件。并且在手指离开前按一定周期派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 第一次派发事件的触发时间。单位秒 + /// + public float trigger; + + /// + /// 派发onAction事件的时间间隔。单位秒。 + /// + public float interval; + + /// + /// 如果为真,则onAction再一次按下释放过程只派发一次。如果为假,则每隔duration时间派发一次。 + /// + public bool once; + + /// + /// 手指按住后,移动超出此半径范围则手势停止。 + /// + public int holdRangeRadius; + + Vector2 _startPoint; + bool _started; + int _touchId; + + public static float TRIGGER = 1.5f; + public static float INTERVAL = 1f; + + public LongPressGesture(GObject host) + { + this.host = host; + trigger = TRIGGER; + interval = INTERVAL; + holdRangeRadius = 50; + Enable(true); + + onBegin = new EventListener(this, "onLongPressBegin"); + onEnd = new EventListener(this, "onLongPressEnd"); + onAction = new EventListener(this, "onLongPressAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchEnd.Remove(__touchEnd); + } + Timers.inst.Remove(__timer); + } + } + + public void Cancel() + { + Timers.inst.Remove(__timer); + _started = false; + } + + void __touchBegin(EventContext context) + { + InputEvent evt = context.inputEvent; + _startPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + _started = false; + _touchId = evt.touchId; + + Timers.inst.Add(trigger, 1, __timer); + context.CaptureTouch(); + } + + void __timer(object param) + { + Vector2 pt = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touchId)); + if (Mathf.Pow(pt.x - _startPoint.x, 2) + Mathf.Pow(pt.y - _startPoint.y, 2) > Mathf.Pow(holdRangeRadius, 2)) + { + Timers.inst.Remove(__timer); + return; + } + if (!_started) + { + _started = true; + onBegin.Call(); + + if (!once) + Timers.inst.Add(interval, 0, __timer); + } + + onAction.Call(); + } + + void __touchEnd(EventContext context) + { + Timers.inst.Remove(__timer); + + if (_started) + { + _started = false; + onEnd.Call(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs.meta new file mode 100644 index 0000000..28ce4aa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/LongPressGesture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 036b702098f47c24ea9cda6c2948507d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs new file mode 100644 index 0000000..fbacf00 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs @@ -0,0 +1,154 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 两个指头捏或者放的手势。 + /// + public class PinchGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当两个手指开始呈捏手势时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 当其中一个手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手势动作时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 总共缩放的量。 + /// + public float scale; + + /// + /// 从上次通知后的改变量。 + /// + public float delta; + + float _startDistance; + float _lastScale; + int[] _touches; + bool _started; + bool _touchBegan; + + public PinchGesture(GObject host) + { + this.host = host; + Enable(true); + + _touches = new int[2]; + + onBegin = new EventListener(this, "onPinchBegin"); + onEnd = new EventListener(this, "onPinchEnd"); + onAction = new EventListener(this, "onPinchAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount == 2) + { + if (!_started && !_touchBegan) + { + _touchBegan = true; + Stage.inst.GetAllTouch(_touches); + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + _startDistance = Vector2.Distance(pt1, pt2); + + context.CaptureTouch(); + } + } + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount != 2) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + float dist = Vector2.Distance(pt1, pt2); + + if (!_started && Mathf.Abs(dist - _startDistance) > UIConfig.touchDragSensitivity) + { + _started = true; + scale = 1; + _lastScale = 1; + + onBegin.Call(evt); + } + + if (_started) + { + float ss = dist / _startDistance; + delta = ss - _lastScale; + _lastScale = ss; + this.scale += delta; + onAction.Call(evt); + } + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs.meta new file mode 100644 index 0000000..b5f39b3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/PinchGesture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dc85a819551042448a16308b82054c89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs new file mode 100644 index 0000000..8363688 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs @@ -0,0 +1,167 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 手指反向操作的手势。 + /// + public class RotationGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当两个手指开始呈反向操作时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 当其中一个手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手势动作时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 总共旋转的角度。 + /// + public float rotation; + + /// + /// 从上次通知后的改变量。 + /// + public float delta; + + /// + /// 是否把变化量强制为整数。默认true。 + /// + public bool snapping; + + Vector2 _startVector; + float _lastRotation; + int[] _touches; + bool _started; + bool _touchBegan; + + public RotationGesture(GObject host) + { + this.host = host; + Enable(true); + + _touches = new int[2]; + snapping = true; + + onBegin = new EventListener(this, "onRotationBegin"); + onEnd = new EventListener(this, "onRotationEnd"); + onAction = new EventListener(this, "onRotationAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount == 2) + { + if (!_started && !_touchBegan) + { + _touchBegan = true; + Stage.inst.GetAllTouch(_touches); + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + _startVector = pt1 - pt2; + + context.CaptureTouch(); + } + } + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount != 2) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + Vector2 vec = pt1 - pt2; + + float rot = Mathf.Rad2Deg * ((Mathf.Atan2(vec.y, vec.x) - Mathf.Atan2(_startVector.y, _startVector.x))); + if (snapping) + { + rot = Mathf.Round(rot); + if (rot == 0) + return; + } + + if (!_started && rot > 5) + { + _started = true; + rotation = 0; + _lastRotation = 0; + + onBegin.Call(evt); + } + + if (_started) + { + delta = rot - _lastRotation; + _lastRotation = rot; + this.rotation += delta; + onAction.Call(evt); + } + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs.meta new file mode 100644 index 0000000..e479c76 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/RotationGesture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 155eda39968f1194d9b4b7bbd63596ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs new file mode 100644 index 0000000..226cf13 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs @@ -0,0 +1,226 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 滑动手势。你可以通过onBegin+onMove+onEnd关心整个滑动过程,也可以只使用onAction关注最后的滑动结果。滑动结果包括方向和加速度,可以从position和velocity获得。 + /// 注意onAction仅当滑动超过一定距离(actionDistance)时才触发。 + /// + public class SwipeGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当手指开始扫动时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 手指在滑动时派发该事件。 + /// + public EventListener onMove { get; private set; } + /// + /// 当手指从按下到离开经过的距离大于actionDistance时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 手指离开时的加速度 + /// + public Vector2 velocity; + + /// + /// 你可以在onBegin事件中设置这个值,那个后续将根据手指移动的距离修改这个值。如果不设置,那position初始为(0,0),反映手指扫过的距离。 + /// + public Vector2 position; + + /// + /// 移动的变化值 + /// + public Vector2 delta; + + /// + /// The min distance to fire onAction event + /// 派发onAction事件的最小距离。如果手指扫过的距离少于此值,onAction不会触发(但onEnd仍然会派发) + /// + public int actionDistance; + + /// + /// 是否把变化量强制为整数。默认true。 + /// + public bool snapping; + + Vector2 _startPoint; + Vector2 _lastPoint; + float _time; + bool _started; + bool _touchBegan; + + public static int ACTION_DISTANCE = 200; + + public SwipeGesture(GObject host) + { + this.host = host; + actionDistance = ACTION_DISTANCE; + snapping = true; + Enable(true); + + onBegin = new EventListener(this, "onSwipeBegin"); + onEnd = new EventListener(this, "onSwipeEnd"); + onMove = new EventListener(this, "onSwipeMove"); + onAction = new EventListener(this, "onnSwipeAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount > 1) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + return; + } + + InputEvent evt = context.inputEvent; + _startPoint = _lastPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + _lastPoint = _startPoint; + + _time = Time.unscaledTime; + _started = false; + velocity = Vector2.zero; + position = Vector2.zero; + _touchBegan = true; + + context.CaptureTouch(); + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount > 1) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + delta = pt - _lastPoint; + if (snapping) + { + delta.x = Mathf.Round(delta.x); + delta.y = Mathf.Round(delta.y); + if (delta.x == 0 && delta.y == 0) + return; + } + + float deltaTime = Time.unscaledDeltaTime; + float elapsed = (Time.unscaledTime - _time) * 60 - 1; + if (elapsed > 1) //速度衰减 + velocity = velocity * Mathf.Pow(0.833f, elapsed); + velocity = Vector3.Lerp(velocity, delta / deltaTime, deltaTime * 10); + _time = Time.unscaledTime; + position += delta; + _lastPoint = pt; + + if (!_started) + { //灵敏度检查,为了和点击区分 + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchDragSensitivity; + else + sensitivity = 5; + + if (Mathf.Abs(delta.x) < sensitivity && Mathf.Abs(delta.y) < sensitivity) + return; + + _started = true; + onBegin.Call(evt); + } + + onMove.Call(evt); + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + + if (!_started) + return; + + _started = false; + + InputEvent evt = context.inputEvent; + Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + delta = pt - _lastPoint; + if (snapping) + { + delta.x = Mathf.Round(delta.x); + delta.y = Mathf.Round(delta.y); + } + position += delta; + + //更新速度 + float elapsed = (Time.unscaledTime - _time) * 60 - 1; + if (elapsed > 1) + velocity = velocity * Mathf.Pow(0.833f, elapsed); + if (snapping) + { + velocity.x = Mathf.Round(velocity.x); + velocity.y = Mathf.Round(velocity.y); + } + onEnd.Call(evt); + + pt -= _startPoint; + if (Mathf.Abs(pt.x) > actionDistance || Mathf.Abs(pt.y) > actionDistance) + onAction.Call(evt); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs.meta new file mode 100644 index 0000000..1aef839 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Gesture/SwipeGesture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7bed3df24eb979345a4d3ed9cd34ca0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween.meta new file mode 100644 index 0000000..11b848b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: af2102ef32b55854c993041a6940127e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs new file mode 100644 index 0000000..c4e282b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs @@ -0,0 +1,248 @@ +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2014/07/19 14:11 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php +// +// ============================================================= +// Contains Daniele Giardini's C# port of the easing equations created by Robert Penner +// (all easing equations except for Flash, InFlash, OutFlash, InOutFlash, +// which use some parts of Robert Penner's equations but were created by Daniele Giardini) +// http://robertpenner.com/easing, see license below: +// ============================================================= +// +// TERMS OF USE - EASING EQUATIONS +// +// Open source under the BSD License. +// +// Copyright ? 2001 Robert Penner +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +// - Neither the name of the author nor the names of contributors may be used to endorse +// or promote products derived from this software without specific prior written permission. +// - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +using System; +using UnityEngine; + +#pragma warning disable 1591 +namespace FairyGUI +{ + public static class EaseManager + { + const float _PiOver2 = Mathf.PI * 0.5f; + const float _TwoPi = Mathf.PI * 2; + + /// + /// Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected + /// + public static float Evaluate(EaseType easeType, float time, float duration, + float overshootOrAmplitude = 1.70158f, + float period = 0, + CustomEase customEase = null) + { + if (duration <= 0) + return 1; + + switch (easeType) + { + case EaseType.Linear: + return time / duration; + case EaseType.SineIn: + return -(float)Math.Cos(time / duration * _PiOver2) + 1; + case EaseType.SineOut: + return (float)Math.Sin(time / duration * _PiOver2); + case EaseType.SineInOut: + return -0.5f * ((float)Math.Cos(Mathf.PI * time / duration) - 1); + case EaseType.QuadIn: + return (time /= duration) * time; + case EaseType.QuadOut: + return -(time /= duration) * (time - 2); + case EaseType.QuadInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time; + return -0.5f * ((--time) * (time - 2) - 1); + case EaseType.CubicIn: + return (time /= duration) * time * time; + case EaseType.CubicOut: + return ((time = time / duration - 1) * time * time + 1); + case EaseType.CubicInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time; + return 0.5f * ((time -= 2) * time * time + 2); + case EaseType.QuartIn: + return (time /= duration) * time * time * time; + case EaseType.QuartOut: + return -((time = time / duration - 1) * time * time * time - 1); + case EaseType.QuartInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time; + return -0.5f * ((time -= 2) * time * time * time - 2); + case EaseType.QuintIn: + return (time /= duration) * time * time * time * time; + case EaseType.QuintOut: + return ((time = time / duration - 1) * time * time * time * time + 1); + case EaseType.QuintInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time * time; + return 0.5f * ((time -= 2) * time * time * time * time + 2); + case EaseType.ExpoIn: + return (time == 0) ? 0 : (float)Math.Pow(2, 10 * (time / duration - 1)); + case EaseType.ExpoOut: + if (time == duration) return 1; + return (-(float)Math.Pow(2, -10 * time / duration) + 1); + case EaseType.ExpoInOut: + if (time == 0) return 0; + if (time == duration) return 1; + if ((time /= duration * 0.5f) < 1) return 0.5f * (float)Math.Pow(2, 10 * (time - 1)); + return 0.5f * (-(float)Math.Pow(2, -10 * --time) + 2); + case EaseType.CircIn: + return -((float)Math.Sqrt(1 - (time /= duration) * time) - 1); + case EaseType.CircOut: + return (float)Math.Sqrt(1 - (time = time / duration - 1) * time); + case EaseType.CircInOut: + if ((time /= duration * 0.5f) < 1) return -0.5f * ((float)Math.Sqrt(1 - time * time) - 1); + return 0.5f * ((float)Math.Sqrt(1 - (time -= 2) * time) + 1); + case EaseType.ElasticIn: + float s0; + if (time == 0) return 0; + if ((time /= duration) == 1) return 1; + if (period == 0) period = duration * 0.3f; + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s0 = period / 4; + } + else s0 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + return -(overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s0) * _TwoPi / period)); + case EaseType.ElasticOut: + float s1; + if (time == 0) return 0; + if ((time /= duration) == 1) return 1; + if (period == 0) period = duration * 0.3f; + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s1 = period / 4; + } + else s1 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + return (overshootOrAmplitude * (float)Math.Pow(2, -10 * time) * (float)Math.Sin((time * duration - s1) * _TwoPi / period) + 1); + case EaseType.ElasticInOut: + float s; + if (time == 0) return 0; + if ((time /= duration * 0.5f) == 2) return 1; + if (period == 0) period = duration * (0.3f * 1.5f); + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s = period / 4; + } + else s = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + if (time < 1) return -0.5f * (overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period)); + return overshootOrAmplitude * (float)Math.Pow(2, -10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period) * 0.5f + 1; + case EaseType.BackIn: + return (time /= duration) * time * ((overshootOrAmplitude + 1) * time - overshootOrAmplitude); + case EaseType.BackOut: + return ((time = time / duration - 1) * time * ((overshootOrAmplitude + 1) * time + overshootOrAmplitude) + 1); + case EaseType.BackInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * (time * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time - overshootOrAmplitude)); + return 0.5f * ((time -= 2) * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time + overshootOrAmplitude) + 2); + case EaseType.BounceIn: + return Bounce.EaseIn(time, duration); + case EaseType.BounceOut: + return Bounce.EaseOut(time, duration); + case EaseType.BounceInOut: + return Bounce.EaseInOut(time, duration); + + case EaseType.Custom: + return customEase != null ? customEase.Evaluate(time / duration) : (time / duration); + + default: + return -(time /= duration) * (time - 2); + } + } + + /// + /// This class contains a C# port of the easing equations created by Robert Penner (http://robertpenner.com/easing). + /// + static class Bounce + { + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseIn(float time, float duration) + { + return 1 - EaseOut(duration - time, duration); + } + + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseOut(float time, float duration) + { + if ((time /= duration) < (1 / 2.75f)) + { + return (7.5625f * time * time); + } + if (time < (2 / 2.75f)) + { + return (7.5625f * (time -= (1.5f / 2.75f)) * time + 0.75f); + } + if (time < (2.5f / 2.75f)) + { + return (7.5625f * (time -= (2.25f / 2.75f)) * time + 0.9375f); + } + return (7.5625f * (time -= (2.625f / 2.75f)) * time + 0.984375f); + } + + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseInOut(float time, float duration) + { + if (time < duration * 0.5f) + { + return EaseIn(time * 2, duration) * 0.5f; + } + return EaseOut(time * 2 - duration, duration) * 0.5f + 0.5f; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs.meta new file mode 100644 index 0000000..386e67e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 080d1dce1c76e154c9c8f50151e6d69e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs new file mode 100644 index 0000000..4e3fe4b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public enum EaseType + { + Linear, + SineIn, + SineOut, + SineInOut, + QuadIn, + QuadOut, + QuadInOut, + CubicIn, + CubicOut, + CubicInOut, + QuartIn, + QuartOut, + QuartInOut, + QuintIn, + QuintOut, + QuintInOut, + ExpoIn, + ExpoOut, + ExpoInOut, + CircIn, + CircOut, + CircInOut, + ElasticIn, + ElasticOut, + ElasticInOut, + BackIn, + BackOut, + BackInOut, + BounceIn, + BounceOut, + BounceInOut, + Custom + } + + /// + /// + /// + public class CustomEase + { + Vector2[] _points; + int _pointDensity; + + static GPath helperPath = new GPath(); + + /// + /// + /// + /// + public CustomEase(int pointDensity = 200) + { + _points = new Vector2[pointDensity + 1]; + _pointDensity = pointDensity; + } + + /// + /// + /// + /// + public void Create(IEnumerable pathPoints) + { + helperPath.Create(pathPoints); + for (int i = 0; i <= _pointDensity; i++) + { + Vector3 pt = helperPath.GetPointAt(i / (float)_pointDensity); + _points[i] = pt; + } + _points[0] = Vector2.zero; + _points[_pointDensity] = Vector2.one; + + Array.Sort(_points, (Vector2 p1, Vector2 p2) => + { + return p1.x.CompareTo(p2.x); + }); + } + + /// + /// + /// + /// + /// + public float Evaluate(float time) + { + if (time <= 0) + return 0; + else if (time >= 1) + return 1; + + int low = 0; + int high = _pointDensity; + int cur = 0; + while (low != high) + { + cur = low + (int)((high - low) / 2f); + float x = _points[cur].x; + if (time == x) + break; + else if (time > x) + { + if (low == cur) + { + cur = high; + break; + } + low = cur; + } + else + { + if (high == cur) + { + cur = low; + break; + } + high = cur; + } + } + + Vector2 v0 = _points[cur]; + Vector2 v1; + if (cur == _pointDensity) + v1 = Vector2.one; + else + v1 = _points[cur + 1]; + float k = (v1.y - v0.y) / (v1.x - v0.x); + if (float.IsNaN(k)) + k = 0; + + return v0.y + (time - v0.x) * k; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs.meta new file mode 100644 index 0000000..d94317f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/EaseType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b3faa49ad96d1cb45acf0a5534094d09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs new file mode 100644 index 0000000..08e8119 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs @@ -0,0 +1,475 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [System.Serializable] + public struct GPathPoint + { + /// + /// + /// + public Vector3 pos; + + /// + /// + /// + public Vector3 control1; + + /// + /// + /// + public Vector3 control2; + + /// + /// + /// + public CurveType curveType; + + /// + /// + /// + public bool smooth; + + /// + /// + /// + public enum CurveType + { + CRSpline, + Bezier, + CubicBezier, + Straight + } + + /// + /// + /// + /// + public GPathPoint(Vector3 pos) + { + this.pos = pos; + this.control1 = Vector3.zero; + this.control2 = Vector3.zero; + this.curveType = CurveType.CRSpline; + this.smooth = true; + } + + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, Vector3 control) + { + this.pos = pos; + this.control1 = control; + this.control2 = Vector3.zero; + this.curveType = CurveType.Bezier; + this.smooth = true; + } + + /// + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, Vector3 control1, Vector3 control2) + { + this.pos = pos; + this.control1 = control1; + this.control2 = control2; + this.curveType = CurveType.CubicBezier; + this.smooth = true; + } + + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, CurveType curveType) + { + this.pos = pos; + this.control1 = Vector3.zero; + this.control2 = Vector3.zero; + this.curveType = curveType; + this.smooth = true; + } + } + + /// + /// + /// + public class GPath + { + protected struct Segment + { + public GPathPoint.CurveType type; + public float length; + public int ptStart; + public int ptCount; + } + + protected List _segments; + protected List _points; + protected float _fullLength; + + static List helperList = new List(); + static List splinePoints = new List(); + + public GPath() + { + _segments = new List(); + _points = new List(); + } + + /// + /// + /// + public float length + { + get { return _fullLength; } + } + + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + Create(helperList); + } + + /// + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + helperList.Add(pt3); + Create(helperList); + } + + /// + /// + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3, GPathPoint pt4) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + helperList.Add(pt3); + helperList.Add(pt4); + Create(helperList); + } + + /// + /// + /// + /// + public void Create(IEnumerable points) + { + _segments.Clear(); + _points.Clear(); + splinePoints.Clear(); + _fullLength = 0; + + var et = points.GetEnumerator(); + if (!et.MoveNext()) + return; + + GPathPoint prev = et.Current; + if (prev.curveType == GPathPoint.CurveType.CRSpline) + splinePoints.Add(prev.pos); + + while (et.MoveNext()) + { + GPathPoint current = et.Current; + + if (prev.curveType != GPathPoint.CurveType.CRSpline) + { + Segment seg = new Segment(); + seg.type = prev.curveType; + seg.ptStart = _points.Count; + if (prev.curveType == GPathPoint.CurveType.Straight) + { + seg.ptCount = 2; + _points.Add(prev.pos); + _points.Add(current.pos); + } + else if (prev.curveType == GPathPoint.CurveType.Bezier) + { + seg.ptCount = 3; + _points.Add(prev.pos); + _points.Add(current.pos); + _points.Add(prev.control1); + } + else if (prev.curveType == GPathPoint.CurveType.CubicBezier) + { + seg.ptCount = 4; + _points.Add(prev.pos); + _points.Add(current.pos); + _points.Add(prev.control1); + _points.Add(prev.control2); + } + seg.length = Vector3.Distance(prev.pos, current.pos); + _fullLength += seg.length; + _segments.Add(seg); + } + + if (current.curveType != GPathPoint.CurveType.CRSpline) + { + if (splinePoints.Count > 0) + { + splinePoints.Add(current.pos); + CreateSplineSegment(); + } + } + else + splinePoints.Add(current.pos); + + prev = current; + } + + if (splinePoints.Count > 1) + CreateSplineSegment(); + } + + void CreateSplineSegment() + { + int cnt = splinePoints.Count; + splinePoints.Insert(0, splinePoints[0]); + splinePoints.Add(splinePoints[cnt]); + splinePoints.Add(splinePoints[cnt]); + cnt += 3; + + Segment seg = new Segment(); + seg.type = GPathPoint.CurveType.CRSpline; + seg.ptStart = _points.Count; + seg.ptCount = cnt; + _points.AddRange(splinePoints); + + seg.length = 0; + for (int i = 1; i < cnt; i++) + seg.length += Vector3.Distance(splinePoints[i - 1], splinePoints[i]); + _fullLength += seg.length; + _segments.Add(seg); + splinePoints.Clear(); + } + + /// + /// + /// + public void Clear() + { + _segments.Clear(); + _points.Clear(); + } + + /// + /// + /// + /// + /// + public Vector3 GetPointAt(float t) + { + t = Mathf.Clamp01(t); + int cnt = _segments.Count; + if (cnt == 0) + return Vector3.zero; + + Segment seg; + if (t == 1) + { + seg = _segments[cnt - 1]; + + if (seg.type == GPathPoint.CurveType.Straight) + return Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + return onBezierCurve(seg.ptStart, seg.ptCount, t); + else + return onCRSplineCurve(seg.ptStart, seg.ptCount, t); + } + + float len = t * _fullLength; + Vector3 pt = new Vector3(); + for (int i = 0; i < cnt; i++) + { + seg = _segments[i]; + + len -= seg.length; + if (len < 0) + { + t = 1 + len / seg.length; + + if (seg.type == GPathPoint.CurveType.Straight) + pt = Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + pt = onBezierCurve(seg.ptStart, seg.ptCount, t); + else + pt = onCRSplineCurve(seg.ptStart, seg.ptCount, t); + + break; + } + } + + return pt; + } + + /// + /// + /// + public int segmentCount + { + get { return _segments.Count; } + } + + /// + /// + /// + /// + /// + public float GetSegmentLength(int segmentIndex) + { + return _segments[segmentIndex].length; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void GetPointsInSegment(int segmentIndex, float t0, float t1, List points, List ts = null, float pointDensity = 0.1f) + { + if (points == null) + points = new List(); + + if (ts != null) + ts.Add(t0); + Segment seg = _segments[segmentIndex]; + if (seg.type == GPathPoint.CurveType.Straight) + { + points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t0)); + points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t1)); + } + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + { + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t0)); + int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); + for (int j = 0; j <= SmoothAmount; j++) + { + float t = (float)j / SmoothAmount; + if (t > t0 && t < t1) + { + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t)); + if (ts != null) + ts.Add(t); + } + } + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t1)); + } + else + { + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t0)); + int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); + for (int j = 0; j <= SmoothAmount; j++) + { + float t = (float)j / SmoothAmount; + if (t > t0 && t < t1) + { + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t)); + if (ts != null) + ts.Add(t); + } + } + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t1)); + } + + if (ts != null) + ts.Add(t1); + } + + /// + /// + /// + /// + public void GetAllPoints(List points, float pointDensity = 0.1f) + { + int cnt = _segments.Count; + for (int i = 0; i < cnt; i++) + GetPointsInSegment(i, 0, 1, points, null, pointDensity); + } + + /// + /// Catmull rom spline implementation + /// by Stéphane Drouot, laei - http://games.laei.org + /// + /// Actual translation of math gebrish to C# credit is due to + /// Boon Cotter - http://www.booncotter.com/waypoints-catmull-rom-splines/ + /// + /// This takes a list of vector3 (or an array) and gives a function called .onCurve(t) + /// returning a value on a Catmull-Rom spline for 0 <= t <= 1 + /// + Vector3 onCRSplineCurve(int ptStart, int ptCount, float t) + { + int adjustedIndex = Mathf.FloorToInt(t * (ptCount - 4)) + ptStart; //Since the equation works with 4 points, we adjust the starting point depending on t to return a point on the specific segment + + Vector3 result = new Vector3(); + + Vector3 p0 = _points[adjustedIndex]; + Vector3 p1 = _points[adjustedIndex + 1]; + Vector3 p2 = _points[adjustedIndex + 2]; + Vector3 p3 = _points[adjustedIndex + 3]; + + float adjustedT = (t == 1f) ? 1f : Mathf.Repeat(t * (ptCount - 4), 1f); // Then we adjust t to be that value on that new piece of segment... for t == 1f don't use repeat (that would return 0f); + + float t0 = ((-adjustedT + 2f) * adjustedT - 1f) * adjustedT * 0.5f; + float t1 = (((3f * adjustedT - 5f) * adjustedT) * adjustedT + 2f) * 0.5f; + float t2 = ((-3f * adjustedT + 4f) * adjustedT + 1f) * adjustedT * 0.5f; + float t3 = ((adjustedT - 1f) * adjustedT * adjustedT) * 0.5f; + + result.x = p0.x * t0 + p1.x * t1 + p2.x * t2 + p3.x * t3; + result.y = p0.y * t0 + p1.y * t1 + p2.y * t2 + p3.y * t3; + result.z = p0.z * t0 + p1.z * t1 + p2.z * t2 + p3.z * t3; + + return result; + } + + Vector3 onBezierCurve(int ptStart, int ptCount, float t) + { + float t2 = 1f - t; + Vector3 p0 = _points[ptStart]; + Vector3 p1 = _points[ptStart + 1]; + Vector3 cp0 = _points[ptStart + 2]; + + if (ptCount == 4) + { + Vector3 cp1 = _points[ptStart + 3]; + return t2 * t2 * t2 * p0 + 3f * t2 * t2 * t * cp0 + 3f * t2 * t * t * cp1 + t * t * t * p1; + } + else + return t2 * t2 * p0 + 2f * t2 * t * cp0 + t * t * p1; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs.meta new file mode 100644 index 0000000..e45c2af --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GPath.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3755f976b6dd17c408731fa87b3cb006 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs new file mode 100644 index 0000000..207f864 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs @@ -0,0 +1,189 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class GTween + { + /// + /// + /// + public static bool catchCallbackExceptions = false; + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(float startValue, float endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector2 startValue, Vector2 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector3 startValue, Vector3 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector4 startValue, Vector4 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Color startValue, Color endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener ToDouble(double startValue, double endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + public static GTweener DelayedCall(float delay) + { + return TweenManager.CreateTween().SetDelay(delay); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener Shake(Vector3 startValue, float amplitude, float duration) + { + return TweenManager.CreateTween()._Shake(startValue, amplitude, duration); + } + + /// + /// + /// + /// + /// + public static bool IsTweening(object target) + { + return TweenManager.IsTweening(target, TweenPropType.None); + } + + /// + /// + /// + /// + /// + /// + public static bool IsTweening(object target, TweenPropType propType) + { + return TweenManager.IsTweening(target, propType); + } + + /// + /// + /// + /// + public static void Kill(object target) + { + TweenManager.KillTweens(target, TweenPropType.None, false); + } + + /// + /// + /// + /// + /// + public static void Kill(object target, bool complete) + { + TweenManager.KillTweens(target, TweenPropType.None, complete); + } + + /// + /// + /// + /// + /// + /// + public static void Kill(object target, TweenPropType propType, bool complete) + { + TweenManager.KillTweens(target, propType, complete); + } + + /// + /// + /// + /// + /// + public static GTweener GetTween(object target) + { + return TweenManager.GetTween(target, TweenPropType.None); + } + + /// + /// + /// + /// + /// + /// + public static GTweener GetTween(object target, TweenPropType propType) + { + return TweenManager.GetTween(target, propType); + } + + /// + /// + /// + public static void Clean() + { + TweenManager.Clean(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs.meta new file mode 100644 index 0000000..b9fd5cb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTween.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 613566965c56f6e4e9a95936b8128f90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs new file mode 100644 index 0000000..e3bf740 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs @@ -0,0 +1,891 @@ +using System; +using UnityEngine; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public delegate void GTweenCallback(); + + /// + /// + /// + /// + public delegate void GTweenCallback1(GTweener tweener); + + /// + /// + /// + public interface ITweenListener + { + /// + /// + /// + /// + void OnTweenStart(GTweener tweener); + + /// + /// + /// + /// + void OnTweenUpdate(GTweener tweener); + + /// + /// + /// + /// + void OnTweenComplete(GTweener tweener); + } + + /// + /// + /// + public class GTweener + { + /// + /// [Y 修改] + /// + #region 自定义参数 + public int rt_Id = 0; + public string rt_Info = string.Empty; + public float rt_Value = 0.0f; + public object rt_Param = null; + public Action rt_Func = null; + + public GTweener rt_GTweener = null; + public DG.Tweening.Tweener rt_Tweener = null; + public GObject rt_GObject = null; + public GComponent rt_GComponent = null; + public UnityEngine.Object rt_UObject = null; + #endregion + + internal object _target; + internal TweenPropType _propType; + internal bool _killed; + internal bool _paused; + + float _delay; + float _duration; + float _breakpoint; + EaseType _easeType; + float _easeOvershootOrAmplitude; + float _easePeriod; + int _repeat; + bool _yoyo; + float _timeScale; + bool _ignoreEngineTimeScale; + bool _snapping; + object _userData; + GPath _path; + CustomEase _customEase; + + GTweenCallback _onUpdate; + GTweenCallback _onStart; + GTweenCallback _onComplete; + GTweenCallback1 _onUpdate1; + GTweenCallback1 _onStart1; + GTweenCallback1 _onComplete1; + ITweenListener _listener; + + TweenValue _startValue; + TweenValue _endValue; + TweenValue _value; + TweenValue _deltaValue; + int _valueSize; + + bool _started; + int _ended; + float _elapsedTime; + float _normalizedTime; + int _smoothStart; + + public GTweener() + { + _startValue = new TweenValue(); + _endValue = new TweenValue(); + _value = new TweenValue(); + _deltaValue = new TweenValue(); + } + + /// + /// + /// + /// + /// + public GTweener SetDelay(float value) + { + _delay = value; + return this; + } + + /// + /// + /// + public float delay + { + get { return _delay; } + } + + /// + /// + /// + /// + /// + public GTweener SetDuration(float value) + { + _duration = value; + return this; + } + + /// + /// + /// + public float duration + { + get { return _duration; } + } + + /// + /// + /// + /// + /// + public GTweener SetBreakpoint(float value) + { + _breakpoint = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEase(EaseType value) + { + _easeType = value; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetEase(EaseType value, CustomEase customEase) + { + _easeType = value; + _customEase = customEase; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEasePeriod(float value) + { + _easePeriod = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEaseOvershootOrAmplitude(float value) + { + _easeOvershootOrAmplitude = value; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetRepeat(int times, bool yoyo = false) + { + _repeat = times; + _yoyo = yoyo; + return this; + } + + /// + /// + /// + public int repeat + { + get { return _repeat; } + } + + /// + /// + /// + /// + /// + public GTweener SetTimeScale(float value) + { + _timeScale = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetIgnoreEngineTimeScale(bool value) + { + _ignoreEngineTimeScale = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetSnapping(bool value) + { + _snapping = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetPath(GPath value) + { + _path = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetTarget(object value) + { + _target = value; + _propType = TweenPropType.None; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetTarget(object value, TweenPropType propType) + { + _target = value; + _propType = propType; + return this; + } + + /// + /// + /// + public object target + { + get { return _target; } + } + + /// + /// + /// + /// + /// + public GTweener SetUserData(object value) + { + _userData = value; + return this; + } + + /// + /// + /// + public object userData + { + get { return _userData; } + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnUpdate(GTweenCallback callback) + { + _onUpdate = callback; + return this; + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnStart(GTweenCallback callback) + { + _onStart = callback; + return this; + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnComplete(GTweenCallback callback) + { + _onComplete = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnUpdate(GTweenCallback1 callback) + { + _onUpdate1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnStart(GTweenCallback1 callback) + { + _onStart1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnComplete(GTweenCallback1 callback) + { + _onComplete1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetListener(ITweenListener value) + { + _listener = value; + return this; + } + + /// + /// + /// + public TweenValue startValue + { + get { return _startValue; } + } + + /// + /// + /// + public TweenValue endValue + { + get { return _endValue; } + } + + /// + /// + /// + public TweenValue value + { + get { return _value; } + } + + /// + /// + /// + public TweenValue deltaValue + { + get { return _deltaValue; } + } + + /// + /// + /// + public float normalizedTime + { + get { return _normalizedTime; } + } + + /// + /// + /// + public bool completed + { + get { return _ended != 0; } + } + + /// + /// + /// + public bool allCompleted + { + get { return _ended == 1; } + } + + /// + /// + /// + /// + /// + public GTweener SetPaused(bool paused) + { + _paused = paused; + if (_paused) + _smoothStart = 0; + return this; + } + + /// + /// + /// + /// + public void Seek(float time) + { + if (_killed) + return; + + _elapsedTime = time; + if (_elapsedTime < _delay) + { + if (_started) + _elapsedTime = _delay; + else + return; + } + + Update(); + } + + /// + /// + /// + /// + public void Kill(bool complete = false) + { + if (_killed) + return; + + if (complete) + { + if (_ended == 0) + { + if (_breakpoint >= 0) + _elapsedTime = _delay + _breakpoint; + else if (_repeat >= 0) + _elapsedTime = _delay + _duration * (_repeat + 1); + else + _elapsedTime = _delay + _duration * 2; + Update(); + } + + CallCompleteCallback(); + } + + _killed = true; + } + + internal GTweener _To(float start, float end, float duration) + { + _valueSize = 1; + _startValue.x = start; + _endValue.x = end; + _value.x = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector2 start, Vector2 end, float duration) + { + _valueSize = 2; + _startValue.vec2 = start; + _endValue.vec2 = end; + _value.vec2 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector3 start, Vector3 end, float duration) + { + _valueSize = 3; + _startValue.vec3 = start; + _endValue.vec3 = end; + _value.vec3 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector4 start, Vector4 end, float duration) + { + _valueSize = 4; + _startValue.vec4 = start; + _endValue.vec4 = end; + _value.vec4 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Color start, Color end, float duration) + { + _valueSize = 4; + _startValue.color = start; + _endValue.color = end; + _value.color = start; + _duration = duration; + return this; + } + + internal GTweener _To(double start, double end, float duration) + { + _valueSize = 5; + _startValue.d = start; + _endValue.d = end; + _value.d = start; + _duration = duration; + return this; + } + + internal GTweener _Shake(Vector3 start, float amplitude, float duration) + { + _valueSize = 6; + _startValue.vec3 = start; + _startValue.w = amplitude; + _duration = duration; + _easeType = EaseType.Linear; + return this; + } + + internal void _Init() + { + _delay = 0; + _duration = 0; + _breakpoint = -1; + _easeType = EaseType.QuadOut; + _timeScale = 1; + _ignoreEngineTimeScale = false; + _easePeriod = 0; + _easeOvershootOrAmplitude = 1.70158f; + _snapping = false; + _repeat = 0; + _yoyo = false; + _valueSize = 0; + _started = false; + _paused = false; + _killed = false; + _elapsedTime = 0; + _normalizedTime = 0; + _ended = 0; + _path = null; + _customEase = null; + _smoothStart = Time.frameCount == 1 ? 3 : 1;//刚启动时会有多帧的超时 + + ///[Y 修改] + #region 自定义扩展 + rt_Id = 0; + rt_Info = string.Empty; + rt_Value = 0.0f; + rt_Param = null; + rt_Func = null; + + rt_GTweener = null; + rt_Tweener = null; + rt_GObject = null; + rt_GComponent = null; + rt_UObject = null; + #endregion + } + + internal void _Reset() + { + _target = null; + _listener = null; + _userData = null; + _onStart = _onUpdate = _onComplete = null; + _onStart1 = _onUpdate1 = _onComplete1 = null; + } + + internal void _Update() + { + if (_ended != 0) //Maybe completed by seek + { + CallCompleteCallback(); + _killed = true; + return; + } + + float dt; + if (_smoothStart > 0) + { + _smoothStart--; + dt = Mathf.Clamp(Time.unscaledDeltaTime, 0, Application.targetFrameRate > 0 ? (1.0f / Application.targetFrameRate) : 0.016f); + if (!_ignoreEngineTimeScale) + dt *= Time.timeScale; + } + else if (_ignoreEngineTimeScale) + dt = Time.unscaledDeltaTime; + else + dt = Time.deltaTime; + if (_timeScale != 1) + dt *= _timeScale; + if (dt == 0) + return; + + _elapsedTime += dt; + Update(); + + if (_ended != 0) + { + if (!_killed) + { + CallCompleteCallback(); + _killed = true; + } + } + } + + void Update() + { + _ended = 0; + + if (_valueSize == 0) //DelayedCall + { + if (_elapsedTime >= _delay + _duration) + _ended = 1; + + return; + } + + if (!_started) + { + if (_elapsedTime < _delay) + return; + + _started = true; + CallStartCallback(); + if (_killed) + return; + } + + bool reversed = false; + float tt = _elapsedTime - _delay; + if (_breakpoint >= 0 && tt >= _breakpoint) + { + tt = _breakpoint; + _ended = 2; + } + + if (_repeat != 0) + { + int round = Mathf.FloorToInt(tt / _duration); + tt -= _duration * round; + if (_yoyo) + reversed = round % 2 == 1; + + if (_repeat > 0 && _repeat - round < 0) + { + if (_yoyo) + reversed = _repeat % 2 == 1; + tt = _duration; + _ended = 1; + } + } + else if (tt >= _duration) + { + tt = _duration; + _ended = 1; + } + + _normalizedTime = EaseManager.Evaluate(_easeType, reversed ? (_duration - tt) : tt, _duration, + _easeOvershootOrAmplitude, _easePeriod, _customEase); + + _value.SetZero(); + _deltaValue.SetZero(); + + if (_valueSize == 5) + { + double d = _startValue.d + (_endValue.d - _startValue.d) * _normalizedTime; + if (_snapping) + d = Math.Round(d); + _deltaValue.d = d - _value.d; + _value.d = d; + _value.x = (float)d; + } + else if (_valueSize == 6) + { + if (_ended == 0) + { + Vector3 r = UnityEngine.Random.insideUnitSphere; + r.x = r.x > 0 ? 1 : -1; + r.y = r.y > 0 ? 1 : -1; + r.z = r.z > 0 ? 1 : -1; + r *= _startValue.w * (1 - _normalizedTime); + + _deltaValue.vec3 = r; + _value.vec3 = _startValue.vec3 + r; + } + else + _value.vec3 = _startValue.vec3; + } + else if (_path != null) + { + Vector3 vec3 = _path.GetPointAt(_normalizedTime); + if (_snapping) + { + vec3.x = Mathf.Round(vec3.x); + vec3.y = Mathf.Round(vec3.y); + vec3.z = Mathf.Round(vec3.z); + } + _deltaValue.vec3 = vec3 - _value.vec3; + _value.vec3 = vec3; + } + else + { + for (int i = 0; i < _valueSize; i++) + { + float n1 = _startValue[i]; + float n2 = _endValue[i]; + float f = n1 + (n2 - n1) * _normalizedTime; + if (_snapping) + f = Mathf.Round(f); + _deltaValue[i] = f - _value[i]; + _value[i] = f; + } + _value.d = _value.x; + } + + if (_target != null && _propType != TweenPropType.None) + TweenPropTypeUtils.SetProps(_target, _propType, _value); + + CallUpdateCallback(); + } + + void CallStartCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onStart1 != null) + _onStart1(this); + if (_onStart != null) + _onStart(); + if (_listener != null) + _listener.OnTweenStart(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in start callback > " + e.Message); + } + } + else + { + if (_onStart1 != null) + _onStart1(this); + if (_onStart != null) + _onStart(); + if (_listener != null) + _listener.OnTweenStart(this); + } + } + + void CallUpdateCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onUpdate1 != null) + _onUpdate1(this); + if (_onUpdate != null) + _onUpdate(); + if (_listener != null) + _listener.OnTweenUpdate(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in update callback > " + e.Message); + } + } + else + { + if (_onUpdate1 != null) + _onUpdate1(this); + if (_onUpdate != null) + _onUpdate(); + if (_listener != null) + _listener.OnTweenUpdate(this); + } + } + + void CallCompleteCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onComplete1 != null) + _onComplete1(this); + if (_onComplete != null) + _onComplete(); + if (_listener != null) + _listener.OnTweenComplete(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in complete callback > " + e.Message); + } + } + else + { + if (_onComplete1 != null) + _onComplete1(this); + if (_onComplete != null) + _onComplete(); + if (_listener != null) + _listener.OnTweenComplete(this); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs.meta new file mode 100644 index 0000000..61bd140 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/GTweener.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48e1b5ac4a90a5649962a3e75fd666c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs new file mode 100644 index 0000000..b54b64e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs @@ -0,0 +1,180 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + internal static class TweenManager + { + static GTweener[] _activeTweens = new GTweener[30]; + static List _tweenerPool = new List(30); + static int _totalActiveTweens = 0; + static bool _inited = false; + + internal static GTweener CreateTween() + { + if (!_inited) + Init(); + + GTweener tweener; + int cnt = _tweenerPool.Count; + if (cnt > 0) + { + tweener = _tweenerPool[cnt - 1]; + _tweenerPool.RemoveAt(cnt - 1); + } + else + tweener = new GTweener(); + tweener._Init(); + _activeTweens[_totalActiveTweens++] = tweener; + + if (_totalActiveTweens == _activeTweens.Length) + { + GTweener[] newArray = new GTweener[_activeTweens.Length + Mathf.CeilToInt(_activeTweens.Length * 0.5f)]; + _activeTweens.CopyTo(newArray, 0); + _activeTweens = newArray; + } + + return tweener; + } + + internal static bool IsTweening(object target, TweenPropType propType) + { + if (target == null) + return false; + + bool anyType = propType == TweenPropType.None; + for (int i = 0; i < _totalActiveTweens; i++) + { + GTweener tweener = _activeTweens[i]; + if (tweener != null && tweener.target == target && !tweener._killed + && (anyType || tweener._propType == propType)) + return true; + } + + return false; + } + + internal static bool KillTweens(object target, TweenPropType propType, bool completed) + { + if (target == null) + return false; + + bool flag = false; + int cnt = _totalActiveTweens; + bool anyType = propType == TweenPropType.None; + for (int i = 0; i < cnt; i++) + { + GTweener tweener = _activeTweens[i]; + if (tweener != null && tweener.target == target && !tweener._killed + && (anyType || tweener._propType == propType)) + { + tweener.Kill(completed); + flag = true; + } + } + + return flag; + } + + internal static GTweener GetTween(object target, TweenPropType propType) + { + if (target == null) + return null; + + int cnt = _totalActiveTweens; + bool anyType = propType == TweenPropType.None; + for (int i = 0; i < cnt; i++) + { + GTweener tweener = _activeTweens[i]; + if (tweener != null && tweener.target == target && !tweener._killed + && (anyType || tweener._propType == propType)) + { + return tweener; + } + } + + return null; + } + + internal static void Update() + { + int cnt = _totalActiveTweens; + int freePosStart = -1; + for (int i = 0; i < cnt; i++) + { + GTweener tweener = _activeTweens[i]; + if (tweener == null) + { + if (freePosStart == -1) + freePosStart = i; + } + else if (tweener._killed) + { + tweener._Reset(); + _tweenerPool.Add(tweener); + _activeTweens[i] = null; + + if (freePosStart == -1) + freePosStart = i; + } + else + { + if ((tweener._target is GObject) && ((GObject)tweener._target)._disposed) + tweener._killed = true; + else if (!tweener._paused) + tweener._Update(); + + if (freePosStart != -1) + { + _activeTweens[freePosStart] = tweener; + _activeTweens[i] = null; + freePosStart++; + } + } + } + + if (freePosStart >= 0) + { + if (_totalActiveTweens != cnt) //new tweens added + { + int j = cnt; + cnt = _totalActiveTweens - cnt; + for (int i = 0; i < cnt; i++) + { + _activeTweens[freePosStart++] = _activeTweens[j]; + _activeTweens[j] = null; + j++; + } + } + _totalActiveTweens = freePosStart; + } + } + + internal static void Clean() + { + _tweenerPool.Clear(); + } + + static void Init() + { + _inited = true; + if (Application.isPlaying) + { + GameObject gameObject = new GameObject("[FairyGUI.TweenManager]"); + gameObject.hideFlags = HideFlags.HideInHierarchy; + gameObject.SetActive(true); + Object.DontDestroyOnLoad(gameObject); + + gameObject.AddComponent(); + } + } + + class TweenEngine : MonoBehaviour + { + void Update() + { + TweenManager.Update(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs.meta new file mode 100644 index 0000000..6bb36b8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3048174c9aaf2e840953e3cab497a426 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs new file mode 100644 index 0000000..ed9464b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs @@ -0,0 +1,103 @@ +namespace FairyGUI +{ + /// + /// + /// + public enum TweenPropType + { + None, + X, + Y, + Z, + XY, + Position, + Width, + Height, + Size, + ScaleX, + ScaleY, + Scale, + Rotation, + RotationX, + RotationY, + Alpha, + Progress + } + + internal class TweenPropTypeUtils + { + internal static void SetProps(object target, TweenPropType propType, TweenValue value) + { + GObject g = target as GObject; + if (g == null) + return; + + switch (propType) + { + case TweenPropType.X: + g.x = value.x; + break; + + case TweenPropType.Y: + g.y = value.x; + break; + + case TweenPropType.Z: + g.z = value.x; + break; + + case TweenPropType.XY: + g.xy = value.vec2; + break; + + case TweenPropType.Position: + g.position = value.vec3; + break; + + case TweenPropType.Width: + g.width = value.x; + break; + + case TweenPropType.Height: + g.height = value.x; + break; + + case TweenPropType.Size: + g.size = value.vec2; + break; + + case TweenPropType.ScaleX: + g.scaleX = value.x; + break; + + case TweenPropType.ScaleY: + g.scaleY = value.x; + break; + + case TweenPropType.Scale: + g.scale = value.vec2; + break; + + case TweenPropType.Rotation: + g.rotation = value.x; + break; + + case TweenPropType.RotationX: + g.rotationX = value.x; + break; + + case TweenPropType.RotationY: + g.rotationY = value.x; + break; + + case TweenPropType.Alpha: + g.alpha = value.x; + break; + + case TweenPropType.Progress: + g.asProgress.Update(value.d); + break; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs.meta new file mode 100644 index 0000000..9b242e3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenPropType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7000822d8123b4344b21dcfb230f8938 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs new file mode 100644 index 0000000..38d6da4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs @@ -0,0 +1,151 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class TweenValue + { + /// + /// + /// + public float x; + + /// + /// + /// + public float y; + + /// + /// + /// + public float z; + + /// + /// + /// + public float w; + + /// + /// + /// + public double d; + + public TweenValue() + { + } + + /// + /// + /// + public Vector2 vec2 + { + get { return new Vector2(x, y); } + set + { + x = value.x; + y = value.y; + } + } + + /// + /// + /// + public Vector3 vec3 + { + get { return new Vector3(x, y, z); } + set + { + x = value.x; + y = value.y; + z = value.z; + } + } + + /// + /// + /// + public Vector4 vec4 + { + get { return new Vector4(x, y, z, w); } + set + { + x = value.x; + y = value.y; + z = value.z; + w = value.w; + } + } + + /// + /// + /// + public Color color + { + get { return new Color(x, y, z, w); } + set + { + x = value.r; + y = value.g; + z = value.b; + w = value.a; + } + } + + /// + /// + /// + /// + /// + public float this[int index] + { + get + { + switch (index) + { + case 0: + return x; + case 1: + return y; + case 2: + return z; + case 3: + return w; + default: + throw new System.Exception("Index out of bounds: " + index); + } + } + + set + { + switch (index) + { + case 0: + x = value; + break; + case 1: + y = value; + break; + case 2: + z = value; + break; + case 3: + w = value; + break; + default: + throw new System.Exception("Index out of bounds: " + index); + } + } + } + + /// + /// + /// + public void SetZero() + { + x = y = z = w = 0; + d = 0; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs.meta new file mode 100644 index 0000000..b54d05b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Tween/TweenValue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97e8a1ca496b4d34cad5f2420a9f8809 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI.meta new file mode 100644 index 0000000..f8cba9b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 929603a3379395146b898542bc37d31b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action.meta new file mode 100644 index 0000000..ce484c7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 76c9ac9d39933da4e833eddb1a96581a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs new file mode 100644 index 0000000..8316158 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs @@ -0,0 +1,52 @@ +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class ChangePageAction : ControllerAction + { + public string objectId; + public string controllerName; + public string targetPage; + + public ChangePageAction() + { + } + + override protected void Enter(Controller controller) + { + if (string.IsNullOrEmpty(controllerName)) + return; + + GComponent gcom; + if (!string.IsNullOrEmpty(objectId)) + gcom = controller.parent.GetChildById(objectId) as GComponent; + else + gcom = controller.parent; + if (gcom != null) + { + Controller cc = gcom.GetController(controllerName); + if (cc != null && cc != controller && !cc.changing) + { + if (this.targetPage == "~1") + { + if (controller.selectedIndex < cc.pageCount) + cc.selectedIndex = controller.selectedIndex; + } + else if (this.targetPage == "~2") + cc.selectedPage = controller.selectedPage; + else + cc.selectedPageId = this.targetPage; + } + } + } + + override public void Setup(ByteBuffer buffer) + { + base.Setup(buffer); + + objectId = buffer.ReadS(); + controllerName = buffer.ReadS(); + targetPage = buffer.ReadS(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs.meta new file mode 100644 index 0000000..4ab8020 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ChangePageAction.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 625a0a9a670984b47a4b170a801c850e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs new file mode 100644 index 0000000..1deb08f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs @@ -0,0 +1,68 @@ +using System; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class ControllerAction + { + public enum ActionType + { + PlayTransition, + ChangePage + } + + public string[] fromPage; + public string[] toPage; + + public static ControllerAction CreateAction(ActionType type) + { + switch (type) + { + case ActionType.PlayTransition: + return new PlayTransitionAction(); + + case ActionType.ChangePage: + return new ChangePageAction(); + } + return null; + } + + public ControllerAction() + { + } + + public void Run(Controller controller, string prevPage, string curPage) + { + if ((fromPage == null || fromPage.Length == 0 || Array.IndexOf(fromPage, prevPage) != -1) + && (toPage == null || toPage.Length == 0 || Array.IndexOf(toPage, curPage) != -1)) + Enter(controller); + else + Leave(controller); + } + + virtual protected void Enter(Controller controller) + { + + } + + virtual protected void Leave(Controller controller) + { + + } + + virtual public void Setup(ByteBuffer buffer) + { + int cnt; + + cnt = buffer.ReadShort(); + fromPage = new string[cnt]; + for (int i = 0; i < cnt; i++) + fromPage[i] = buffer.ReadS(); + + cnt = buffer.ReadShort(); + toPage = new string[cnt]; + for (int i = 0; i < cnt; i++) + toPage[i] = buffer.ReadS(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs.meta new file mode 100644 index 0000000..38ab0db --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/ControllerAction.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6fb1eb3d57827b4bb09eddfa5c76137 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs new file mode 100644 index 0000000..0226976 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs @@ -0,0 +1,52 @@ +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class PlayTransitionAction : ControllerAction + { + public string transitionName; + public int playTimes; + public float delay; + public bool stopOnExit; + + private Transition _currentTransition; + + public PlayTransitionAction() + { + playTimes = 1; + delay = 0; + } + + override protected void Enter(Controller controller) + { + Transition trans = controller.parent.GetTransition(transitionName); + if (trans != null) + { + if (_currentTransition != null && _currentTransition.playing) + trans.ChangePlayTimes(playTimes); + else + trans.Play(playTimes, delay, null); + _currentTransition = trans; + } + } + + override protected void Leave(Controller controller) + { + if (stopOnExit && _currentTransition != null) + { + _currentTransition.Stop(); + _currentTransition = null; + } + } + + override public void Setup(ByteBuffer buffer) + { + base.Setup(buffer); + + transitionName = buffer.ReadS(); + playTimes = buffer.ReadInt(); + delay = buffer.ReadFloat(); + stopOnExit = buffer.ReadBool(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs.meta new file mode 100644 index 0000000..2c6f43f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Action/PlayTransitionAction.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eac7f8de0d09f17439fb3c8e4a06090e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs new file mode 100644 index 0000000..a080583 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs @@ -0,0 +1,189 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class AsyncCreationHelper + { + public static void CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) + { + Timers.inst.StartCoroutine(_CreateObject(item, callback)); + } + + static IEnumerator _CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) + { + Stats.LatestObjectCreation = 0; + Stats.LatestGraphicsCreation = 0; + + float frameTime = UIConfig.frameTimeForAsyncUIConstruction; + + List itemList = new List(); + DisplayListItem di = new DisplayListItem(item, ObjectType.Component); + di.childCount = CollectComponentChildren(item, itemList); + itemList.Add(di); + + int cnt = itemList.Count; + List objectPool = new List(cnt); + GObject obj; + float t = Time.realtimeSinceStartup; + bool alreadyNextFrame = false; + + for (int i = 0; i < cnt; i++) + { + di = itemList[i]; + if (di.packageItem != null) + { + obj = UIObjectFactory.NewObject(di.packageItem); + objectPool.Add(obj); + + UIPackage._constructing++; + if (di.packageItem.type == PackageItemType.Component) + { + int poolStart = objectPool.Count - di.childCount - 1; + + ((GComponent)obj).ConstructFromResource(objectPool, poolStart); + + objectPool.RemoveRange(poolStart, di.childCount); + } + else + { + obj.ConstructFromResource(); + } + UIPackage._constructing--; + } + else + { + obj = UIObjectFactory.NewObject(di.type); + objectPool.Add(obj); + + if (di.type == ObjectType.List && di.listItemCount > 0) + { + int poolStart = objectPool.Count - di.listItemCount - 1; + for (int k = 0; k < di.listItemCount; k++) //把他们都放到pool里,这样GList在创建时就不需要创建对象了 + ((GList)obj).itemPool.ReturnObject(objectPool[k + poolStart]); + objectPool.RemoveRange(poolStart, di.listItemCount); + } + } + + if ((i % 5 == 0) && Time.realtimeSinceStartup - t >= frameTime) + { + yield return null; + t = Time.realtimeSinceStartup; + alreadyNextFrame = true; + } + } + + if (!alreadyNextFrame) //强制至至少下一帧才调用callback,避免调用者逻辑出错 + yield return null; + + callback(objectPool[0]); + } + + /// + /// 收集创建目标对象所需的所有类型信息 + /// + /// + /// + static int CollectComponentChildren(PackageItem item, List list) + { + ByteBuffer buffer = item.rawData; + buffer.Seek(0, 2); + + int dcnt = buffer.ReadShort(); + DisplayListItem di; + PackageItem pi; + for (int i = 0; i < dcnt; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + ObjectType type = (ObjectType)buffer.ReadByte(); + string src = buffer.ReadS(); + string pkgId = buffer.ReadS(); + + buffer.position = curPos; + + if (src != null) + { + UIPackage pkg; + if (pkgId != null) + pkg = UIPackage.GetById(pkgId); + else + pkg = item.owner; + + pi = pkg != null ? pkg.GetItem(src) : null; + di = new DisplayListItem(pi, type); + + if (pi != null && pi.type == PackageItemType.Component) + di.childCount = CollectComponentChildren(pi, list); + } + else + { + di = new DisplayListItem(null, type); + if (type == ObjectType.List) //list + di.listItemCount = CollectListChildren(buffer, list); + } + + list.Add(di); + buffer.position = curPos + dataLen; + } + + return dcnt; + } + + static int CollectListChildren(ByteBuffer buffer, List list) + { + buffer.Seek(buffer.position, 8); + + string defaultItem = buffer.ReadS(); + int listItemCount = 0; + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadShort(); + nextPos += buffer.position; + + string url = buffer.ReadS(); + if (url == null) + url = defaultItem; + if (!string.IsNullOrEmpty(url)) + { + PackageItem pi = UIPackage.GetItemByURL(url); + if (pi != null) + { + DisplayListItem di = new DisplayListItem(pi, pi.objectType); + if (pi.type == PackageItemType.Component) + di.childCount = CollectComponentChildren(pi, list); + + list.Add(di); + listItemCount++; + } + } + buffer.position = nextPos; + } + + return listItemCount; + } + + /// + /// + /// + class DisplayListItem + { + public PackageItem packageItem; + public ObjectType type; + public int childCount; + public int listItemCount; + + public DisplayListItem(PackageItem pi, ObjectType type) + { + this.packageItem = pi; + this.type = type; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs.meta new file mode 100644 index 0000000..808c891 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/AsyncCreationHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99d38995f0d185d4eb694a7728219c01 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs new file mode 100644 index 0000000..032b073 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs @@ -0,0 +1,440 @@ +using System.Collections.Generic; +using FairyGUI.Utils; +using System; + +namespace FairyGUI +{ + /// + /// Controller class. + /// 控制器类。控制器的创建和设计需通过编辑器完成,不建议使用代码创建。 + /// 最常用的方法是通过selectedIndex获得或改变控制器的活动页面。如果要获得控制器页面改变的通知,使用onChanged事件。 + /// + public class Controller : EventDispatcher + { + /// + /// Name of the controller + /// 控制器名称。 + /// + public string name; + + internal GComponent parent; + internal bool autoRadioGroupDepth; + internal bool changing; + + int _selectedIndex; + int _previousIndex; + List _pageIds; + List _pageNames; + List _actions; + + EventListener _onChanged; + + static uint _nextPageId; + + public Controller() + { + _pageIds = new List(); + _pageNames = new List(); + _selectedIndex = -1; + _previousIndex = -1; + } + + public void Dispose() + { + RemoveEventListeners(); + } + + + /// + /// When controller page changed. + /// 当控制器活动页面改变时,此事件被触发。 + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Current page index. + /// 获得或设置当前活动页面索引。 + /// + public int selectedIndex + { + get + { + return _selectedIndex; + } + set + { + if (_selectedIndex != value) + { + if (value > _pageIds.Count - 1) + throw new IndexOutOfRangeException("" + value); + + changing = true; + + _previousIndex = _selectedIndex; + _selectedIndex = value; + parent.ApplyController(this); + + DispatchEvent("onChanged", null); + + changing = false; + } + } + } + + /// + /// Set current page index, no onChanged event. + /// 通过索引设置当前活动页面,和selectedIndex的区别在于,这个方法不会触发onChanged事件。 + /// + /// Page index + public void SetSelectedIndex(int value) + { + if (_selectedIndex != value) + { + if (value > _pageIds.Count - 1) + throw new IndexOutOfRangeException("" + value); + + changing = true; + _previousIndex = _selectedIndex; + _selectedIndex = value; + parent.ApplyController(this); + changing = false; + } + } + + /// + /// Set current page by name, no onChanged event. + /// 通过页面名称设置当前活动页面,和selectedPage的区别在于,这个方法不会触发onChanged事件。 + /// + /// Page name + public void SetSelectedPage(string value) + { + int i = _pageNames.IndexOf(value); + if (i == -1) + i = 0; + this.SetSelectedIndex(i); + } + + /// + /// Current page name. + /// 获得当前活动页面名称 + /// + public string selectedPage + { + get + { + if (_selectedIndex == -1) + return null; + else + return _pageNames[_selectedIndex]; + } + set + { + int i = _pageNames.IndexOf(value); + if (i == -1) + i = 0; + this.selectedIndex = i; + } + } + + [Obsolete("Use previousIndex")] + public int previsousIndex + { + get { return _previousIndex; } + } + + /// + /// Previouse page index. + /// 获得上次活动页面索引 + /// + public int previousIndex + { + get { return _previousIndex; } + } + + /// + /// Previous page name. + /// 获得上次活动页面名称。 + /// + public string previousPage + { + get + { + if (_previousIndex == -1) + return null; + else + return _pageNames[_previousIndex]; + } + } + + /// + /// Page count of this controller. + /// 获得页面数量。 + /// + public int pageCount + { + get { return _pageIds.Count; } + } + + /// + /// Get page name by an index. + /// 通过页面索引获得页面名称。 + /// + /// Page index + /// Page Name + public string GetPageName(int index) + { + return _pageNames[index]; + } + + /// + /// Get page id by an index. + /// 通过页面索引获得页面id。 + /// + /// Page index + /// Page Id + public string GetPageId(int index) + { + return _pageIds[index]; + } + + /// + /// Get page id by name + /// + /// + /// + public string GetPageIdByName(string aName) + { + int i = _pageNames.IndexOf(aName); + if (i != -1) + return _pageIds[i]; + else + return null; + } + + /// + /// Add a new page to this controller. + /// + /// Page name + public void AddPage(string name) + { + if (name == null) + name = string.Empty; + + AddPageAt(name, _pageIds.Count); + } + + /// + /// Add a new page to this controller at a certain index. + /// + /// Page name + /// Insert position + public void AddPageAt(string name, int index) + { + string nid = "_" + (_nextPageId++); + if (index == _pageIds.Count) + { + _pageIds.Add(nid); + _pageNames.Add(name); + } + else + { + _pageIds.Insert(index, nid); + _pageNames.Insert(index, name); + } + } + + /// + /// Remove a page. + /// + /// Page name + public void RemovePage(string name) + { + int i = _pageNames.IndexOf(name); + if (i != -1) + { + _pageIds.RemoveAt(i); + _pageNames.RemoveAt(i); + if (_selectedIndex >= _pageIds.Count) + this.selectedIndex = _selectedIndex - 1; + else + parent.ApplyController(this); + } + } + + /// + /// Removes a page at a certain index. + /// + /// + public void RemovePageAt(int index) + { + _pageIds.RemoveAt(index); + _pageNames.RemoveAt(index); + if (_selectedIndex >= _pageIds.Count) + this.selectedIndex = _selectedIndex - 1; + else + parent.ApplyController(this); + } + + /// + /// Remove all pages. + /// + public void ClearPages() + { + _pageIds.Clear(); + _pageNames.Clear(); + if (_selectedIndex != -1) + this.selectedIndex = -1; + else + parent.ApplyController(this); + } + + /// + /// Check if the controller has a page. + /// + /// Page name. + /// + public bool HasPage(string aName) + { + return _pageNames.IndexOf(aName) != -1; + } + + internal int GetPageIndexById(string aId) + { + return _pageIds.IndexOf(aId); + } + + internal string GetPageNameById(string aId) + { + int i = _pageIds.IndexOf(aId); + if (i != -1) + return _pageNames[i]; + else + return null; + } + + internal string selectedPageId + { + get + { + if (_selectedIndex == -1) + return string.Empty; + else + return _pageIds[_selectedIndex]; + } + set + { + int i = _pageIds.IndexOf(value); + if (i != -1) + this.selectedIndex = i; + } + } + + internal string oppositePageId + { + set + { + int i = _pageIds.IndexOf(value); + if (i > 0) + this.selectedIndex = 0; + else if (_pageIds.Count > 1) + this.selectedIndex = 1; + } + } + + internal string previousPageId + { + get + { + if (_previousIndex == -1) + return null; + else + return _pageIds[_previousIndex]; + } + } + + public void RunActions() + { + if (_actions != null) + { + int cnt = _actions.Count; + for (int i = 0; i < cnt; i++) + { + _actions[i].Run(this, previousPageId, selectedPageId); + } + } + } + + public void Setup(ByteBuffer buffer) + { + int beginPos = buffer.position; + buffer.Seek(beginPos, 0); + + name = buffer.ReadS(); + autoRadioGroupDepth = buffer.ReadBool(); + + buffer.Seek(beginPos, 1); + + int cnt = buffer.ReadShort(); + _pageIds.Capacity = cnt; + _pageNames.Capacity = cnt; + for (int i = 0; i < cnt; i++) + { + _pageIds.Add(buffer.ReadS()); + _pageNames.Add(buffer.ReadS()); + } + + int homePageIndex = 0; + if (buffer.version >= 2) + { + int homePageType = buffer.ReadByte(); + switch (homePageType) + { + case 1: + homePageIndex = buffer.ReadShort(); + break; + + case 2: + homePageIndex = _pageNames.IndexOf(UIPackage.branch); + if (homePageIndex == -1) + homePageIndex = 0; + break; + + case 3: + homePageIndex = _pageNames.IndexOf(UIPackage.GetVar(buffer.ReadS())); + if (homePageIndex == -1) + homePageIndex = 0; + break; + } + } + + buffer.Seek(beginPos, 2); + + cnt = buffer.ReadShort(); + if (cnt > 0) + { + if (_actions == null) + _actions = new List(cnt); + + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + ControllerAction action = ControllerAction.CreateAction((ControllerAction.ActionType)buffer.ReadByte()); + action.Setup(buffer); + _actions.Add(action); + + buffer.position = nextPos; + } + } + + if (parent != null && _pageIds.Count > 0) + _selectedIndex = homePageIndex; + else + _selectedIndex = -1; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs.meta new file mode 100644 index 0000000..263c47d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Controller.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a032426f9564db4a95c1c5a513bcd12 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs new file mode 100644 index 0000000..2a6175b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs @@ -0,0 +1,139 @@ +namespace FairyGUI +{ + /// + /// Helper for drag and drop. + /// 这是一个提供特殊拖放功能的功能类。与GObject.draggable不同,拖动开始后,他使用一个替代的图标作为拖动对象。 + /// 当玩家释放鼠标/手指,目标组件会发出一个onDrop事件。 + /// + public class DragDropManager + { + private GLoader _agent; + private object _sourceData; + private GObject _source; + + private static DragDropManager _inst; + public static DragDropManager inst + { + get + { + if (_inst == null) + _inst = new DragDropManager(); + return _inst; + } + } + + public DragDropManager() + { + _agent = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); + _agent.gameObjectName = "DragDropAgent"; + _agent.SetHome(GRoot.inst); + _agent.touchable = false;//important + _agent.draggable = true; + _agent.SetSize(100, 100); + _agent.SetPivot(0.5f, 0.5f, true); + _agent.align = AlignType.Center; + _agent.verticalAlign = VertAlignType.Middle; + _agent.sortingOrder = int.MaxValue; + _agent.onDragEnd.Add(__dragEnd); + } + + /// + /// Loader object for real dragging. + /// 用于实际拖动的Loader对象。你可以根据实际情况设置loader的大小,对齐等。 + /// + public GLoader dragAgent + { + get { return _agent; } + } + + /// + /// Is dragging? + /// 返回当前是否正在拖动。 + /// + public bool dragging + { + get { return _agent.parent != null; } + } + + /// + /// Start dragging. + /// 开始拖动。 + /// + /// Source object. This is the object which initiated the dragging. + /// Icon to be used as the dragging sign. + /// Custom data. You can get it in the onDrop event data. + /// Copy the touchId from InputEvent to here, if has one. + public void StartDrag(GObject source, string icon, object sourceData, int touchPointID = -1) + { + if (_agent.parent != null) + return; + + _sourceData = sourceData; + _source = source; + _agent.url = icon; + GRoot.inst.AddChild(_agent); + _agent.xy = GRoot.inst.GlobalToLocal(Stage.inst.GetTouchPosition(touchPointID)); + _agent.StartDrag(touchPointID); + } + + /// + /// [Y 修改] + /// Start dragging. + /// 开始拖动。 + /// + /// Source object. This is the object which initiated the dragging. + /// Icon to be used as the dragging sign. + /// Custom data. You can get it in the onDrop event data. + /// Copy the touchId from InputEvent to here, if has one. + public void StartDrag(GObject source, NTexture texture, object sourceData, int touchPointID = -1) + { + if (_agent.parent != null) + return; + + _sourceData = sourceData; + _agent.texture = texture; + GRoot.inst.AddChild(_agent); + _agent.xy = GRoot.inst.GlobalToLocal(Stage.inst.GetTouchPosition(touchPointID)); + _agent.StartDrag(touchPointID); + } + + /// + /// Cancel dragging. + /// 取消拖动。 + /// + public void Cancel() + { + if (_agent.parent != null) + { + _agent.StopDrag(); + GRoot.inst.RemoveChild(_agent); + _sourceData = null; + } + } + + private void __dragEnd(EventContext evt) + { + if (_agent.parent == null) //cancelled + return; + + GRoot.inst.RemoveChild(_agent); + + object sourceData = _sourceData; + GObject source = _source; + _sourceData = null; + _source = null; + + GObject obj = GRoot.inst.touchTarget; + while (obj != null) + { + if (obj.hasEventListeners("onDrop")) + { + obj.RequestFocus(); + obj.DispatchEvent("onDrop", sourceData, source); + return; + } + obj = obj.parent; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs.meta new file mode 100644 index 0000000..9d2c351 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/DragDropManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb013a6e64663c34694529d92a620777 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs new file mode 100644 index 0000000..5bbcbca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs @@ -0,0 +1,128 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public interface EMRenderTarget + { + int EM_sortingOrder { get; } + + void EM_BeforeUpdate(); + void EM_Update(UpdateContext context); + void EM_Reload(); + } + + /// + /// 这是一个在编辑状态下渲染UI的功能类。EM=Edit Mode + /// + public class EMRenderSupport + { + /// + /// + /// + public static bool orderChanged; + + static UpdateContext _updateContext; + static List _targets = new List(); + + /// + /// + /// + public static bool packageListReady { get; private set; } + + /// + /// + /// + public static bool hasTarget + { + get { return _targets.Count > 0; } + } + + /// + /// + /// + /// + public static void Add(EMRenderTarget value) + { + if (!_targets.Contains(value)) + _targets.Add(value); + orderChanged = true; + } + + /// + /// + /// + /// + public static void Remove(EMRenderTarget value) + { + _targets.Remove(value); + } + + /// + /// 由StageCamera调用 + /// + public static void Update() + { + if (Application.isPlaying) + return; + + if (_updateContext == null) + _updateContext = new UpdateContext(); + + if (orderChanged) + { + _targets.Sort(CompareDepth); + orderChanged = false; + } + + int cnt = _targets.Count; + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_BeforeUpdate(); + } + + if (packageListReady) + { + _updateContext.Begin(); + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_Update(_updateContext); + } + _updateContext.End(); + } + } + + /// + /// 当发生二进制重载时,或用户点击刷新菜单 + /// + public static void Reload() + { + if (Application.isPlaying) + return; + + UIConfig.ClearResourceRefs(); + UIConfig[] configs = GameObject.FindObjectsOfType(); + foreach (UIConfig config in configs) + config.Load(); + + packageListReady = true; + + int cnt = _targets.Count; + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_Reload(); + } + } + + static int CompareDepth(EMRenderTarget c1, EMRenderTarget c2) + { + return c1.EM_sortingOrder - c2.EM_sortingOrder; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs.meta new file mode 100644 index 0000000..2ac3129 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/EMRenderSupport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0ea7d5d9d5c232d4f9a312870329cbd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs new file mode 100644 index 0000000..8a7f3a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs @@ -0,0 +1,304 @@ +namespace FairyGUI +{ + public enum PackageItemType + { + Image, + MovieClip, + Sound, + Component, + Atlas, + Font, + Swf, + Misc, + Unknown, + Spine, + DragoneBones + } + + public enum ObjectType + { + Image, + MovieClip, + Swf, + Graph, + Loader, + Group, + Text, + RichText, + InputText, + Component, + List, + Label, + Button, + ComboBox, + ProgressBar, + Slider, + ScrollBar, + Tree, + Loader3D + } + + public enum AlignType + { + Left, + Center, + Right + } + + public enum VertAlignType + { + Top, + Middle, + Bottom + } + + public enum OverflowType + { + Visible, + Hidden, + Scroll + } + + public enum FillType + { + None, + Scale, + ScaleMatchHeight, + ScaleMatchWidth, + ScaleFree, + ScaleNoBorder + } + + public enum AutoSizeType + { + None, + Both, + Height, + Shrink, + Ellipsis + } + + public enum ScrollType + { + Horizontal, + Vertical, + Both + } + + public enum ScrollBarDisplayType + { + Default, + Visible, + Auto, + Hidden + } + + public enum RelationType + { + Left_Left, + Left_Center, + Left_Right, + Center_Center, + Right_Left, + Right_Center, + Right_Right, + + Top_Top, + Top_Middle, + Top_Bottom, + Middle_Middle, + Bottom_Top, + Bottom_Middle, + Bottom_Bottom, + + Width, + Height, + + LeftExt_Left, + LeftExt_Right, + RightExt_Left, + RightExt_Right, + TopExt_Top, + TopExt_Bottom, + BottomExt_Top, + BottomExt_Bottom, + + Size + } + + public enum ListLayoutType + { + SingleColumn, + SingleRow, + FlowHorizontal, + FlowVertical, + Pagination + } + + public enum ListSelectionMode + { + Single, + Multiple, + Multiple_SingleClick, + None + } + + public enum ProgressTitleType + { + Percent, + ValueAndMax, + Value, + Max + } + + public enum ButtonMode + { + Common, + Check, + Radio + } + + public enum TransitionActionType + { + XY, + Size, + Scale, + Pivot, + Alpha, + Rotation, + Color, + Animation, + Visible, + Sound, + Transition, + Shake, + ColorFilter, + Skew, + Text, + Icon, + Unknown + } + + public enum GroupLayoutType + { + None, + Horizontal, + Vertical + } + + public enum ChildrenRenderOrder + { + Ascent, + Descent, + Arch, + } + + public enum PopupDirection + { + Auto, + Up, + Down + } + + /// + /// + /// + public enum FlipType + { + None, + Horizontal, + Vertical, + Both + } + + /// + /// + /// + public enum FillMethod + { + None = 0, + + /// + /// The Image will be filled Horizontally + /// + Horizontal = 1, + + /// + /// The Image will be filled Vertically. + /// + Vertical = 2, + + /// + /// The Image will be filled Radially with the radial center in one of the corners. + /// + Radial90 = 3, + + /// + /// The Image will be filled Radially with the radial center in one of the edges. + /// + Radial180 = 4, + + /// + /// The Image will be filled Radially with the radial center at the center. + /// + Radial360 = 5, + } + + /// + /// + /// + public enum OriginHorizontal + { + Left, + Right, + } + + /// + /// + /// + public enum OriginVertical + { + Top, + Bottom + } + + /// + /// + /// + public enum Origin90 + { + TopLeft, + TopRight, + BottomLeft, + BottomRight + } + + /// + /// + /// + public enum Origin180 + { + Top, + Bottom, + Left, + Right + } + + /// + /// + /// + public enum Origin360 + { + Top, + Bottom, + Left, + Right + } + + public enum FocusRule + { + NotFocusable, + Focusable, + NavigationBase + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs.meta new file mode 100644 index 0000000..e5cdaa1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/FieldTypes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1d03a824e0fdd8a48a0ad6173b4593e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs new file mode 100644 index 0000000..3fbd802 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs @@ -0,0 +1,695 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GButton class. + /// + public class GButton : GComponent, IColorGear + { + //[Y 修改] + protected Controller _iconController; + + /// + /// [Y 修改] + /// 是否关闭点击音效 + /// + public bool isCloseClickSound = false; + + /// + /// [Y 修改] + /// 是否关闭点击动效 + /// + public bool isCloseClickAnim = false; + + /// + /// Play sound when button is clicked. + /// + public NAudioClip sound; + + /// + /// Volume of the click sound. (0-1) + /// + public float soundVolumeScale; + + /// + /// For radio or checkbox. if false, the button will not change selected status on click. Default is true. + /// 如果为true,对于单选和多选按钮,当玩家点击时,按钮会自动切换状态。设置为false,则不会。默认为true。 + /// + public bool changeStateOnClick; + + /// + /// Show a popup on click. + /// 可以为按钮设置一个关联的组件,当按钮被点击时,此组件被自动弹出。 + /// + public GObject linkedPopup; + + protected GObject _titleObject; + protected GObject _iconObject; + protected Controller _relatedController; + protected string _relatedPageId; + + ButtonMode _mode; + bool _selected; + string _title; + string _icon; + string _selectedTitle; + string _selectedIcon; + Controller _buttonController; + int _downEffect; + float _downEffectValue; + bool _downScaled; + + bool _down; + bool _over; + + EventListener _onChanged; + + public const string UP = "up"; + public const string DOWN = "down"; + public const string OVER = "over"; + public const string SELECTED_OVER = "selectedOver"; + public const string DISABLED = "disabled"; + public const string SELECTED_DISABLED = "selectedDisabled"; + + public GButton() + { + sound = UIConfig.buttonSound; + soundVolumeScale = UIConfig.buttonSoundVolumeScale; + changeStateOnClick = true; + _downEffectValue = 0.8f; + _title = string.Empty; + } + + /// + /// [Y 修改] + /// 设置按下动画特效值 + /// + public void SetClickDownEffect(float value, int effectType = 2) + { + _downEffectValue = value; + _downEffect = effectType; + } + + /// + /// [Y 修改] + /// 播放点击声效 + /// + private void PlayClickSound() + { + if (isCloseClickSound) return; + + PlaySound(); + } + + //[Y 修改] + public void PlaySound() + { + if (sound != null && sound.nativeClip != null) + { + Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); + } + } + + /// + /// Dispatched when the button status was changed. + /// 如果为单选或多选按钮,当按钮的选中状态发生改变时,此事件触发。 + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Icon of the button. + /// + override public string icon + { + get { return _icon; } + set + { + _icon = value; + value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = value; + + //[Y 修改] + if (_iconController != null) _iconController.selectedIndex = value == null ? 1 : 0; + + UpdateGear(7); + } + } + + /// + /// Title of the button + /// + public string title + { + get { return _title; } + set + { + _title = value; + if (_titleObject != null) + _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// Icon value on selected status. + /// + public string selectedIcon + { + get { return _selectedIcon; } + set + { + _selectedIcon = value; + value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = value; + } + } + + /// + /// Title value on selected status. + /// + public string selectedTitle + { + get { return _selectedTitle; } + set + { + _selectedTitle = value; + if (_titleObject != null) + _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; + } + } + + /// + /// Title color. + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + tf.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public Color color + { + get { return this.titleColor; } + set { this.titleColor = value; } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// If the button is in selected status. + /// + public bool selected + { + get { return _selected; } + + set + { + if (_mode == ButtonMode.Common) + return; + + if (_selected != value) + { + _selected = value; + SetCurrentState(); + if (_selectedTitle != null && _titleObject != null) + _titleObject.text = _selected ? _selectedTitle : _title; + if (_selectedIcon != null) + { + string str = _selected ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = str; + } + + if (_relatedController != null + && parent != null + && !parent._buildingDisplayList) + { + if (_selected) + { + _relatedController.selectedPageId = _relatedPageId; + if (_relatedController.autoRadioGroupDepth) + parent.AdjustRadioGroupDepth(this, _relatedController); + } + else if (_mode == ButtonMode.Check && _relatedController.selectedPageId == _relatedPageId) + _relatedController.oppositePageId = _relatedPageId; + } + } + } + } + + /// + /// Button mode. + /// + /// + public ButtonMode mode + { + get { return _mode; } + set + { + if (_mode != value) + { + if (value == ButtonMode.Common) + this.selected = false; + _mode = value; + } + } + } + + /// + /// A controller is connected to this button, the activate page of this controller will change while the button status changed. + /// 对应编辑器中的单选控制器。 + /// + public Controller relatedController + { + get { return _relatedController; } + set + { + if (value != _relatedController) + { + _relatedController = value; + _relatedPageId = null; + } + } + } + + /// + /// + /// + public string relatedPageId + { + get { return _relatedPageId; } + set { _relatedPageId = value; } + } + + /// + /// Simulates a click on this button. + /// 模拟点击这个按钮。 + /// + /// If the down effect will simulate too. + public void FireClick(bool downEffect, bool clickCall = false) + { + if (downEffect && _mode == ButtonMode.Common) + { + SetState(OVER); + + Timers.inst.Add(0.1f, 1, (object param) => { SetState(DOWN); }); + Timers.inst.Add(0.2f, 1, + (object param) => + { + SetState(UP); + if (clickCall) + { + onClick.Call(); + } + } + ); + } + else + { + if (clickCall) + { + onClick.Call(); + } + } + + __click(); + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + protected void SetState(string val) + { + if (_buttonController != null) + _buttonController.selectedPage = val; + + if (_downEffect == 1) + { + int cnt = this.numChildren; + if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) + { + Color color = new Color(_downEffectValue, _downEffectValue, _downEffectValue); + for (int i = 0; i < cnt; i++) + { + GObject obj = this.GetChildAt(i); + if ((obj is IColorGear) && !(obj is GTextField)) + ((IColorGear)obj).color = color; + } + } + else + { + for (int i = 0; i < cnt; i++) + { + GObject obj = this.GetChildAt(i); + if ((obj is IColorGear) && !(obj is GTextField)) + ((IColorGear)obj).color = Color.white; + } + } + } + else if (_downEffect == 2) + { + if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) + { + if (!_downScaled) + { + // [Y 修改] + if (isCloseClickAnim) return; + + _downScaled = true; + SetScale(this.scaleX * _downEffectValue, this.scaleY * _downEffectValue); + } + } + else + { + if (_downScaled) + { + // [Y 修改] + if (isCloseClickAnim) return; + + _downScaled = false; + SetScale(this.scaleX / _downEffectValue, this.scaleY / _downEffectValue); + } + } + } + } + + protected void SetCurrentState() + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + { + if (_selected) + SetState(SELECTED_DISABLED); + else + SetState(DISABLED); + } + else + { + if (_selected) + SetState(_over ? SELECTED_OVER : DOWN); + else + SetState(_over ? OVER : UP); + } + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_relatedController == c) + this.selected = _relatedPageId == c.selectedPageId; + } + + override protected void HandleGrayedChanged() + { + if (_buttonController != null && _buttonController.HasPage(DISABLED)) + { + if (this.grayed) + { + if (_selected) + SetState(SELECTED_DISABLED); + else + SetState(DISABLED); + } + else + { + if (_selected) + SetState(DOWN); + else + SetState(UP); + } + } + else + base.HandleGrayedChanged(); + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + //[Y 修改] + _iconController = GetController("cont_icon"); + + buffer.Seek(0, 6); + + _mode = (ButtonMode)buffer.ReadByte(); + string str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + soundVolumeScale = buffer.ReadFloat(); + _downEffect = buffer.ReadByte(); + _downEffectValue = buffer.ReadFloat(); + if (_downEffect == 2) + SetPivot(0.5f, 0.5f, this.pivotAsAnchor); + + _buttonController = GetController("button"); + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + if (_titleObject != null) + _title = _titleObject.text; + if (_iconObject != null) + _icon = _iconObject.icon; + + if (_mode == ButtonMode.Common) + SetState(UP); + + displayObject.onRollOver.Add(__rollover); + displayObject.onRollOut.Add(__rollout); + displayObject.onTouchBegin.Add(__touchBegin); + displayObject.onTouchEnd.Add(__touchEnd); + displayObject.onRemovedFromStage.Add(__removedFromStage); + displayObject.onClick.Add(__click); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + + str = buffer.ReadS(); + if (str != null) + this.title = str; + str = buffer.ReadS(); + if (str != null) + this.selectedTitle = str; + str = buffer.ReadS(); + if (str != null) + this.icon = str; + str = buffer.ReadS(); + if (str != null) + this.selectedIcon = str; + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv != 0) + this.titleFontSize = iv; + iv = buffer.ReadShort(); + if (iv >= 0) + _relatedController = parent.GetControllerAt(iv); + _relatedPageId = buffer.ReadS(); + + str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + if (buffer.ReadBool()) + soundVolumeScale = buffer.ReadFloat(); + + this.selected = buffer.ReadBool(); + } + + private void __rollover() + { + if (_buttonController == null || !_buttonController.HasPage(OVER)) + return; + + _over = true; + if (_down) + return; + + if (this.grayed && _buttonController.HasPage(DISABLED)) + return; + + SetState(_selected ? SELECTED_OVER : OVER); + } + + private void __rollout() + { + if (_buttonController == null || !_buttonController.HasPage(OVER)) + return; + + _over = false; + if (_down) + return; + + if (this.grayed && _buttonController.HasPage(DISABLED)) + return; + + SetState(_selected ? DOWN : UP); + } + + private void __touchBegin(EventContext context) + { + if (context.inputEvent.button != 0) + return; + + _down = true; + context.CaptureTouch(); + + if (_mode == ButtonMode.Common) + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + SetState(SELECTED_DISABLED); + else + { + // [Y 修改] + PlayClickSound(); + + SetState(DOWN); + } + } + + if (linkedPopup != null) + { + if (linkedPopup is Window) + ((Window)linkedPopup).ToggleStatus(); + else + this.root.TogglePopup(linkedPopup, this); + } + } + + private void __touchEnd() + { + if (_down) + { + _down = false; + if (_mode == ButtonMode.Common) + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + SetState(DISABLED); + else if (_over) + SetState(OVER); + else + SetState(UP); + } + else + { + if (!_over + && _buttonController != null + && (_buttonController.selectedPage == OVER || _buttonController.selectedPage == SELECTED_OVER)) + { + SetCurrentState(); + } + } + } + } + + private void __removedFromStage() + { + if (_over) + __rollout(); + } + + private void __click() + { + // [Y 修改] + //if (sound != null && sound.nativeClip != null) + // Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); + + if (_mode == ButtonMode.Check) + { + if (changeStateOnClick) + { + this.selected = !_selected; + DispatchEvent("onChanged", null); + } + } + else if (_mode == ButtonMode.Radio) + { + if (changeStateOnClick && !_selected) + { + this.selected = true; + DispatchEvent("onChanged", null); + } + } + else + { + if (_relatedController != null) + _relatedController.selectedPageId = _relatedPageId; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs.meta new file mode 100644 index 0000000..9ee0040 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GButton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e5e996dd06bc77458af09a2465efb6d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs new file mode 100644 index 0000000..33c81bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs @@ -0,0 +1,628 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GComboBox class. + /// + public class GComboBox : GComponent + { + /// + /// Visible item count of the drop down list. + /// + public int visibleItemCount; + + /// + /// + /// + public GComponent dropdown; + + /// + /// Play sound when button is clicked. + /// + public NAudioClip sound; + + /// + /// Volume of the click sound. (0-1) + /// + public float soundVolumeScale; + + protected GObject _titleObject; + protected GObject _iconObject; + protected GList _list; + + protected List _items; + protected List _icons; + protected List _values; + protected PopupDirection _popupDirection; + protected Controller _selectionController; + + bool _itemsUpdated; + int _selectedIndex; + Controller _buttonController; + + bool _down; + bool _over; + + EventListener _onChanged; + + public GComboBox() + { + visibleItemCount = UIConfig.defaultComboBoxVisibleItemCount; + _itemsUpdated = true; + _selectedIndex = -1; + _items = new List(); + _values = new List(); + _popupDirection = PopupDirection.Auto; + soundVolumeScale = 1; + } + + /// + /// Dispatched when selection was changed. + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Icon of the combobox. + /// + override public string icon + { + get + { + if (_iconObject != null) + return _iconObject.icon; + else + return null; + } + + set + { + if (_iconObject != null) + _iconObject.icon = value; + UpdateGear(7); + } + } + + /// + /// Title of the combobox. + /// + public string title + { + get + { + if (_titleObject != null) + return _titleObject.text; + else + return null; + } + set + { + if (_titleObject != null) + _titleObject.text = value; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// Text color + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + tf.color = value; + } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// Items to build up drop down list. + /// + public string[] items + { + get + { + return _items.ToArray(); + } + set + { + _items.Clear(); + if (value != null) + _items.AddRange(value); + ApplyListChange(); + } + } + + /// + /// + /// + public string[] icons + { + get { return _icons != null ? _icons.ToArray() : null; } + set + { + this.iconList.Clear(); + if (value != null) + _icons.AddRange(value); + ApplyListChange(); + } + } + + /// + /// Values, should be same size of the items. + /// + public string[] values + { + get { return _values.ToArray(); } + set + { + _values.Clear(); + if (value != null) + _values.AddRange(value); + } + } + + /// + /// + /// + public List itemList + { + get { return _items; } + } + + /// + /// + /// + public List valueList + { + get { return _values; } + } + + /// + /// + /// + public List iconList + { + get { return _icons ?? (_icons = new List()); } + } + + /// + /// Call this method after you made changes on itemList or iconList + /// + public void ApplyListChange() + { + if (_items.Count > 0) + { + if (_selectedIndex >= _items.Count) + _selectedIndex = _items.Count - 1; + else if (_selectedIndex == -1) + _selectedIndex = 0; + + this.text = _items[_selectedIndex]; + if (_icons != null && _selectedIndex < _icons.Count) + this.icon = _icons[_selectedIndex]; + } + else + { + this.text = string.Empty; + if (_icons != null) + this.icon = null; + _selectedIndex = -1; + } + + _itemsUpdated = true; + } + + /// + /// Selected index. + /// + public int selectedIndex + { + get + { + return _selectedIndex; + } + set + { + if (_selectedIndex == value) + return; + + _selectedIndex = value; + if (_selectedIndex >= 0 && _selectedIndex < _items.Count) + { + this.text = (string)_items[_selectedIndex]; + if (_icons != null && _selectedIndex < _icons.Count) + this.icon = _icons[_selectedIndex]; + } + else + { + this.text = string.Empty; + if (_icons != null) + this.icon = null; + } + + UpdateSelectionController(); + } + } + + /// + /// + /// + public Controller selectionController + { + get { return _selectionController; } + set { _selectionController = value; } + } + + /// + /// Selected value. + /// + public string value + { + get + { + if (_selectedIndex >= 0 && _selectedIndex < _values.Count) + return _values[_selectedIndex]; + else + return null; + } + set + { + int index = _values.IndexOf(value); + if (index == -1 && value == null) + index = _values.IndexOf(string.Empty); + if (index == -1) + index = 0; + this.selectedIndex = index; + } + } + + /// + /// + /// + public PopupDirection popupDirection + { + get { return _popupDirection; } + set { _popupDirection = value; } + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + protected void SetState(string value) + { + if (_buttonController != null) + _buttonController.selectedPage = value; + } + + protected void SetCurrentState() + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(GButton.DISABLED)) + SetState(GButton.DISABLED); + else if (dropdown != null && dropdown.parent != null) + SetState(GButton.DOWN); + else + SetState(_over ? GButton.OVER : GButton.UP); + } + + override protected void HandleGrayedChanged() + { + if (_buttonController != null && _buttonController.HasPage(GButton.DISABLED)) + { + if (this.grayed) + SetState(GButton.DISABLED); + else + SetState(GButton.UP); + } + else + base.HandleGrayedChanged(); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_selectionController == c) + this.selectedIndex = c.selectedIndex; + } + + void UpdateSelectionController() + { + if (_selectionController != null && !_selectionController.changing + && _selectedIndex < _selectionController.pageCount) + { + Controller c = _selectionController; + _selectionController = null; + c.selectedIndex = _selectedIndex; + _selectionController = c; + } + } + + public override void Dispose() + { + if (dropdown != null) + { + dropdown.Dispose(); + dropdown = null; + } + _selectionController = null; + + base.Dispose(); + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _buttonController = GetController("button"); + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + + string str = buffer.ReadS(); + if (str != null) + { + dropdown = UIPackage.CreateObjectFromURL(str) as GComponent; + if (dropdown == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should be a component."); + return; + } + + _list = dropdown.GetChild("list") as GList; + if (_list == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + ": should container a list component named list."); + return; + } + _list.onClickItem.Add(__clickItem); + + _list.AddRelation(dropdown, RelationType.Width); + _list.RemoveRelation(dropdown, RelationType.Height); + + dropdown.AddRelation(_list, RelationType.Height); + dropdown.RemoveRelation(_list, RelationType.Width); + + dropdown.SetHome(this); + } + + displayObject.onRollOver.Add(__rollover); + displayObject.onRollOut.Add(__rollout); + displayObject.onTouchBegin.Add(__touchBegin); + displayObject.onTouchEnd.Add(__touchEnd); + displayObject.onClick.Add(__click); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + _items.Add(buffer.ReadS()); + _values.Add(buffer.ReadS()); + str = buffer.ReadS(); + if (str != null) + { + if (_icons == null) + _icons = new List(); + _icons.Add(str); + } + + buffer.position = nextPos; + } + + str = buffer.ReadS(); + if (str != null) + { + this.text = str; + _selectedIndex = _items.IndexOf(str); + } + else if (_items.Count > 0) + { + _selectedIndex = 0; + this.text = _items[0]; + } + else + _selectedIndex = -1; + + str = buffer.ReadS(); + if (str != null) + this.icon = str; + + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv > 0) + visibleItemCount = iv; + _popupDirection = (PopupDirection)buffer.ReadByte(); + + iv = buffer.ReadShort(); + if (iv >= 0) + _selectionController = parent.GetControllerAt(iv); + + if (buffer.version >= 5) + { + str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + soundVolumeScale = buffer.ReadFloat(); + } + } + + public void UpdateDropdownList() + { + if (_itemsUpdated) + { + _itemsUpdated = false; + RenderDropdownList(); + _list.ResizeToFit(visibleItemCount); + } + } + + protected void ShowDropdown() + { + UpdateDropdownList(); + if (_list.selectionMode == ListSelectionMode.Single) + _list.selectedIndex = -1; + dropdown.width = this.width; + _list.EnsureBoundsCorrect(); //avoid flicker + + this.root.TogglePopup(dropdown, this, _popupDirection); + if (dropdown.parent != null) + { + dropdown.displayObject.onRemovedFromStage.Add(__popupWinClosed); + SetState(GButton.DOWN); + } + } + + virtual protected void RenderDropdownList() + { + _list.RemoveChildrenToPool(); + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + GObject item = _list.AddItemFromPool(); + item.text = _items[i]; + item.icon = (_icons != null && i < _icons.Count) ? _icons[i] : null; + item.name = i < _values.Count ? _values[i] : string.Empty; + } + } + + private void __popupWinClosed(object obj) + { + dropdown.displayObject.onRemovedFromStage.Remove(__popupWinClosed); + SetCurrentState(); + + RequestFocus(); + } + + private void __clickItem(EventContext context) + { + if (dropdown.parent is GRoot) + ((GRoot)dropdown.parent).HidePopup(dropdown); + _selectedIndex = int.MinValue; + this.selectedIndex = _list.GetChildIndex((GObject)context.data); + + DispatchEvent("onChanged", null); + } + + private void __rollover() + { + _over = true; + if (_down || dropdown != null && dropdown.parent != null) + return; + + SetCurrentState(); + } + + private void __rollout() + { + _over = false; + if (_down || dropdown != null && dropdown.parent != null) + return; + + SetCurrentState(); + } + + private void __touchBegin(EventContext context) + { + if (context.initiator is InputTextField) + return; + + _down = true; + + if (dropdown != null) + ShowDropdown(); + + context.CaptureTouch(); + } + + private void __touchEnd(EventContext context) + { + if (_down) + { + _down = false; + if (dropdown != null && dropdown.parent != null) + SetCurrentState(); + } + } + + private void __click() + { + if (sound != null && sound.nativeClip != null) + Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs.meta new file mode 100644 index 0000000..112bc4b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComboBox.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 65b819211c4a7ec4eb1cf17cda579377 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs new file mode 100644 index 0000000..091c420 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs @@ -0,0 +1,1768 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// Component + /// + public class GComponent : GObject + { + /// + /// Root container. + /// + public Container rootContainer { get; private set; } + + /// + /// Content container. If the component is not clipped, then container==rootContainer. + /// + public Container container { get; protected set; } + + /// + /// ScrollPane of the component. If the component is not scrollable, the value is null. + /// + public ScrollPane scrollPane { get; private set; } + + internal List _children; + internal List _controllers; + internal List _transitions; + internal bool _buildingDisplayList; + + protected Margin _margin; + protected bool _trackBounds; + protected bool _boundsChanged; + protected ChildrenRenderOrder _childrenRenderOrder; + protected int _apexIndex; + internal Vector2 _alignOffset; + + Vector2 _clipSoftness; + int _sortingChildCount; + Action _buildDelegate; + Controller _applyingController; + + EventListener _onDrop; + + public GComponent() + { + _children = new List(); + _controllers = new List(); + _transitions = new List(); + _margin = new Margin(); + _buildDelegate = BuildNativeDisplayList; + } + + override protected void CreateDisplayObject() + { + rootContainer = new Container("GComponent"); + rootContainer.gOwner = this; + rootContainer.onUpdate += OnUpdate; + container = rootContainer; + + displayObject = rootContainer; + } + + override public void Dispose() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + { + Transition trans = _transitions[i]; + trans.Dispose(); + } + + cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller c = _controllers[i]; + c.Dispose(); + } + + if (scrollPane != null) + scrollPane.Dispose(); + + base.Dispose(); //Dispose native tree first, avoid DisplayObject.RemoveFromParent call + + cnt = _children.Count; + for (int i = cnt - 1; i >= 0; --i) + { + GObject obj = _children[i]; + obj.InternalSetParent(null); //Avoid GObject.RemoveParent call + obj.Dispose(); + } + +#if FAIRYGUI_TOLUA + if (_peerTable != null) + { + _peerTable.Dispose(); + _peerTable = null; + } +#endif + +#if FAIRYGUI_PUERTS + if (__onDispose != null) + __onDispose(); + __onConstruct = null; + __onDispose = null; +#endif + } + + /// + /// Dispatched when an object was dragged and dropped to this component. + /// + public EventListener onDrop + { + get { return _onDrop ?? (_onDrop = new EventListener(this, "onDrop")); } + } + + /// + /// Draw call optimization switch. + /// + public bool fairyBatching + { + get { return rootContainer.fairyBatching; } + set { rootContainer.fairyBatching = value; } + } + + /// + /// + /// + /// + public void InvalidateBatchingState(bool childChanged) + { + if (childChanged) + container.InvalidateBatchingState(childChanged); + else + rootContainer.InvalidateBatchingState(); + } + + /// + /// If true, mouse/touch events cannot pass through the empty area of the component. Default is true. + /// + public bool opaque + { + get { return rootContainer.opaque; } + set { rootContainer.opaque = value; } + } + + /// + /// + /// + /// + public Margin margin + { + get { return _margin; } + set + { + _margin = value; + if (rootContainer.clipRect != null && + scrollPane == null) //如果scrollPane不为空,则HandleSizeChanged里面的处理会促使ScrollPane处理 + container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); + HandleSizeChanged(); + } + } + + /// + /// + /// + public ChildrenRenderOrder childrenRenderOrder + { + get { return _childrenRenderOrder; } + set + { + if (_childrenRenderOrder != value) + { + _childrenRenderOrder = value; + BuildNativeDisplayList(); + } + } + } + + /// + /// + /// + public int apexIndex + { + get { return _apexIndex; } + set + { + if (_apexIndex != value) + { + _apexIndex = value; + + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + BuildNativeDisplayList(); + } + } + } + + /// + /// If true, children can be navigated by TAB from first to last, and repeat + /// + public bool tabStopChildren + { + get { return rootContainer.tabStopChildren; } + set { rootContainer.tabStopChildren = value; } + } + + /// + /// Add a child to the component. It will be at the frontmost position. + /// + /// A child object + /// GObject + public GObject AddChild(GObject child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// Adds a child to the component at a certain index. + /// + /// A child object + /// Index + /// GObject + virtual public GObject AddChildAt(GObject child, int index) + { + if (index >= 0 && index <= _children.Count) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + child.RemoveFromParent(); + child.InternalSetParent(this); + + int cnt = _children.Count; + if (child.sortingOrder != 0) + { + _sortingChildCount++; + index = GetInsertPosForSortingChild(child); + } + else if (_sortingChildCount > 0) + { + if (index > (cnt - _sortingChildCount)) + index = cnt - _sortingChildCount; + } + + if (index == cnt) + _children.Add(child); + else + _children.Insert(index, child); + + ChildStateChanged(child); + SetBoundsChangedFlag(); + } + + return child; + } + else + { + throw new Exception("Invalid child index: " + index + ">" + _children.Count); + } + } + + int GetInsertPosForSortingChild(GObject target) + { + int cnt = _children.Count; + int i; + for (i = 0; i < cnt; i++) + { + GObject child = _children[i]; + if (child == target) + continue; + + if (target.sortingOrder < child.sortingOrder) + break; + } + + return i; + } + + /// + /// Removes a child from the component. If the object is not a child, nothing happens. + /// + /// A child object + /// GObject + public GObject RemoveChild(GObject child) + { + return RemoveChild(child, false); + } + + /// + /// Removes a child from the component. If the object is not a child, nothing happens. + /// + /// A child object + /// If true, the child will be disposed right away. + /// GObject + public GObject RemoveChild(GObject child, bool dispose) + { + int childIndex = _children.IndexOf(child); + if (childIndex != -1) + { + RemoveChildAt(childIndex, dispose); + } + + return child; + } + + /// + /// Removes a child at a certain index. Children above the child will move down. + /// + /// Index + /// GObject + public GObject RemoveChildAt(int index) + { + return RemoveChildAt(index, false); + } + + /// + /// Removes a child at a certain index. Children above the child will move down. + /// + /// Index + /// If true, the child will be disposed right away. + /// GObject + virtual public GObject RemoveChildAt(int index, bool dispose) + { + if (index >= 0 && index < numChildren) + { + GObject child = _children[index]; + + child.InternalSetParent(null); + + if (child.sortingOrder != 0) + _sortingChildCount--; + + _children.RemoveAt(index); + child.group = null; + if (child.inContainer) + { + container.RemoveChild(child.displayObject); + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + + if (dispose) + child.Dispose(); + + SetBoundsChangedFlag(); + return child; + } + else + throw new Exception("Invalid child index: " + index + ">" + numChildren); + } + + /// + /// Remove all children. + /// + public void RemoveChildren() + { + RemoveChildren(0, -1, false); + } + + /// + /// Removes a range of children from the container (endIndex included). + /// + /// Begin index. + /// End index.(Included). + /// If true, the child will be disposed right away. + public void RemoveChildren(int beginIndex, int endIndex, bool dispose) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex, dispose); + } + + /// + /// Returns a child object at a certain index. If index out of bounds, exception raised. + /// + /// Index + /// A child object. + public GObject GetChildAt(int index) + { + if (index >= 0 && index < numChildren) + return _children[index]; + else + throw new Exception("Invalid child index: " + index + ">" + numChildren); + } + + /// + /// Returns a child object with a certain name. + /// + /// Name + /// A child object. Null if not found. + public GObject GetChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].name == name) + return _children[i]; + } + + return null; + } + + public GObject GetChildByPath(string path) + { + string[] arr = path.Split('.'); + int cnt = arr.Length; + GComponent gcom = this; + GObject obj = null; + for (int i = 0; i < cnt; ++i) + { + obj = gcom.GetChild(arr[i]); + if (obj == null) + break; + + if (i != cnt - 1) + { + if (!(obj is GComponent)) + { + obj = null; + break; + } + else + gcom = (GComponent)obj; + } + } + + return obj; + } + + /// + /// Returns a visible child object with a certain name. + /// + /// Name + /// A child object. Null if not found. + public GObject GetVisibleChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (child.internalVisible && child.internalVisible2 && child.name == name) + return child; + } + + return null; + } + + /// + /// Returns a child object belong to a group with a certain name. + /// + /// A group object + /// Name + /// A child object. Null if not found. + public GObject GetChildInGroup(GGroup group, string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (child.group == group && child.name == name) + return child; + } + + return null; + } + + internal GObject GetChildById(string id) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].id == id) + return _children[i]; + } + + return null; + } + + /// + /// Returns a copy of all children with an array. + /// + /// An array contains all children + public GObject[] GetChildren() + { + return _children.ToArray(); + } + + /// + /// [Y 修改] + /// + public int GetChildrenCount() + { + return _children.Count; + } + + /// + /// Returns the index of a child within the container, or "-1" if it is not found. + /// + /// A child object + /// Index of the child. -1 If not found. + public int GetChildIndex(GObject child) + { + return _children.IndexOf(child); + } + + /// + /// Moves a child to a certain index. Children at and after the replaced position move up. + /// + /// A Child + /// Index + public void SetChildIndex(GObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new ArgumentException("Not a child of this container"); + + if (child.sortingOrder != 0) //no effect + return; + + if (_sortingChildCount > 0) + { + int cnt = _children.Count; + if (index > (cnt - _sortingChildCount - 1)) + index = cnt - _sortingChildCount - 1; + } + + _SetChildIndex(child, oldIndex, index); + } + + /// + /// Moves a child to a certain position which is in front of the child previously at given index. + /// 与SetChildIndex不同的是,如果child原来在index的前面,那么child插入的位置是index-1,即保证排在原来占据index的对象的前面。 + /// + /// + /// + public int SetChildIndexBefore(GObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new ArgumentException("Not a child of this container"); + + if (child.sortingOrder != 0) //no effect + return oldIndex; + + int cnt = _children.Count; + if (_sortingChildCount > 0) + { + if (index > (cnt - _sortingChildCount - 1)) + index = cnt - _sortingChildCount - 1; + } + + if (oldIndex < index) + return _SetChildIndex(child, oldIndex, index - 1); + else + return _SetChildIndex(child, oldIndex, index); + } + + int _SetChildIndex(GObject child, int oldIndex, int index) + { + int cnt = _children.Count; + if (index > cnt) + index = cnt; + + if (oldIndex == index) + return oldIndex; + + _children.RemoveAt(oldIndex); + if (index >= cnt) + _children.Add(child); + else + _children.Insert(index, child); + + if (child.inContainer) + { + int displayIndex = 0; + if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) + { + for (int i = 0; i < index; i++) + { + GObject g = _children[i]; + if (g.inContainer) + displayIndex++; + } + + container.SetChildIndex(child.displayObject, displayIndex); + } + else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) + { + for (int i = cnt - 1; i > index; i--) + { + GObject g = _children[i]; + if (g.inContainer) + displayIndex++; + } + + container.SetChildIndex(child.displayObject, displayIndex); + } + else + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + + SetBoundsChangedFlag(); + } + + return index; + } + + /// + /// Swaps the indexes of two children. + /// + /// A child object + /// A child object + public void SwapChildren(GObject child1, GObject child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// Swaps the indexes of two children. + /// + /// index of first child + /// index of second child + public void SwapChildrenAt(int index1, int index2) + { + GObject child1 = _children[index1]; + GObject child2 = _children[index2]; + + SetChildIndex(child1, index2); + SetChildIndex(child2, index1); + } + + /// + /// The number of children of this component. + /// + public int numChildren + { + get { return _children.Count; } + } + + /// + /// + /// + /// + /// + public bool IsAncestorOf(GObject obj) + { + if (obj == null) + return false; + + GComponent p = obj.parent; + while (p != null) + { + if (p == this) + return true; + + p = p.parent; + } + + return false; + } + + + /// + /// + /// + /// + public void ChangeChildrenOrder(IList objs) + { + int cnt = objs.Count; + for (int i = 0; i < cnt; i++) + { + GObject obj = objs[i]; + if (obj.parent != this) + throw new Exception("Not a child of this container"); + + _children[i] = obj; + } + + BuildNativeDisplayList(); + SetBoundsChangedFlag(); + } + + /// + /// Adds a controller to the container. + /// + /// Controller object + public void AddController(Controller controller) + { + _controllers.Add(controller); + controller.parent = this; + ApplyController(controller); + } + + /// + /// Returns a controller object at a certain index. + /// + /// Index + /// Controller object. + public Controller GetControllerAt(int index) + { + return _controllers[index]; + } + + /// + /// Returns a controller object with a certain name. + /// + /// Name + /// Controller object. Null if not found. + public Controller GetController(string name) + { + int cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller c = _controllers[i]; + if (c.name == name) + return c; + } + + return null; + } + + /// + /// Removes a controller from the container. + /// + /// Controller object. + public void RemoveController(Controller c) + { + int index = _controllers.IndexOf(c); + if (index == -1) + throw new Exception("controller not exists: " + c.name); + + c.parent = null; + _controllers.RemoveAt(index); + + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + child.HandleControllerChanged(c); + } + } + + /// + /// Returns controller list. + /// + /// Controller list + public List Controllers + { + get { return _controllers; } + } + + /// + /// Returns a transition object at a certain index. + /// + /// Index + /// transition object. + public Transition GetTransitionAt(int index) + { + return _transitions[index]; + } + + /// + /// Returns a transition object at a certain name. + /// + /// Name + /// Transition Object + public Transition GetTransition(string name) + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + { + Transition trans = _transitions[i]; + if (trans.name == name) + return trans; + } + + return null; + } + + /// + /// Returns transition list. + /// + /// Transition list + public List Transitions + { + get { return _transitions; } + } + + internal void ChildStateChanged(GObject child) + { + if (_buildingDisplayList) + return; + + int cnt = _children.Count; + + if (child is GGroup) + { + for (int i = 0; i < cnt; ++i) + { + GObject g = _children[i]; + if (g.group == child) + ChildStateChanged(g); + } + + return; + } + + if (child.displayObject == null) + return; + + if (child.internalVisible) + { + if (child.displayObject.parent == null) + { + if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) + { + int index = 0; + for (int i = 0; i < cnt; i++) + { + GObject g = _children[i]; + if (g == child) + break; + + if (g.displayObject != null && g.displayObject.parent != null) + index++; + } + + container.AddChildAt(child.displayObject, index); + } + else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) + { + int index = 0; + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = _children[i]; + if (g == child) + break; + + if (g.displayObject != null && g.displayObject.parent != null) + index++; + } + + container.AddChildAt(child.displayObject, index); + } + else + { + container.AddChild(child.displayObject); + + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + } + else + { + if (child.displayObject.parent != null) + { + container.RemoveChild(child.displayObject); + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + } + } + + void BuildNativeDisplayList() + { + if (displayObject == null || displayObject.isDisposed) + return; + + int cnt = _children.Count; + if (cnt == 0) + return; + + switch (_childrenRenderOrder) + { + case ChildrenRenderOrder.Ascent: + { + for (int i = 0; i < cnt; i++) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + case ChildrenRenderOrder.Descent: + { + for (int i = cnt - 1; i >= 0; i--) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + + case ChildrenRenderOrder.Arch: + { + int apex = Mathf.Clamp(_apexIndex, 0, cnt); + for (int i = 0; i < apex; i++) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + + for (int i = cnt - 1; i >= apex; i--) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + } + } + + internal void ApplyController(Controller c) + { + _applyingController = c; + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + child.HandleControllerChanged(c); + } + + _applyingController = null; + + c.RunActions(); + } + + void ApplyAllControllers() + { + int cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller controller = _controllers[i]; + ApplyController(controller); + } + } + + internal void AdjustRadioGroupDepth(GObject obj, Controller c) + { + int cnt = _children.Count; + int i; + GObject child; + int myIndex = -1, maxIndex = -1; + for (i = 0; i < cnt; i++) + { + child = _children[i]; + if (child == obj) + { + myIndex = i; + } + else if ((child is GButton) + && ((GButton)child).relatedController == c) + { + if (i > maxIndex) + maxIndex = i; + } + } + + if (myIndex < maxIndex) + { + if (_applyingController != null) + _children[maxIndex].HandleControllerChanged(_applyingController); + this.SwapChildrenAt(myIndex, maxIndex); + } + } + + /// + /// If clipping softness is set, clipped containers will have soft border effect. + /// + public Vector2 clipSoftness + { + get { return _clipSoftness; } + set + { + _clipSoftness = value; + if (scrollPane != null) + scrollPane.UpdateClipSoft(); + else if (_clipSoftness.x > 0 || _clipSoftness.y > 0) + rootContainer.clipSoftness = new Vector4(value.x, value.y, value.x, value.y); + else + rootContainer.clipSoftness = null; + } + } + + /// + /// The mask of the component. + /// + public DisplayObject mask + { + get { return container.mask; } + set + { + container.mask = value; + if (value != null && value.parent != container) + container.AddChild(value); + } + } + + /// + /// [Y 修改] + /// 用户组件自定义数据 + /// + private string _baseUserData; + + /// + /// [Y 修改] + /// 用户组件自定义数据 + /// + public string baseUserData + { + get + { + if (_baseUserData == null) + { + ByteBuffer buffer = packageItem.rawData; + buffer.Seek(0, 4); + _baseUserData = buffer.ReadS(); + } + + return _baseUserData; + } + } + + /// + /// + /// + public bool reversedMask + { + get { return container.reversedMask; } + set { container.reversedMask = value; } + } + + /// + /// Test if a child is in view. + /// + /// A child object + /// True if in view + public bool IsChildInView(GObject child) + { + if (scrollPane != null) + { + return scrollPane.IsChildInView(child); + } + else if (rootContainer.clipRect != null) + { + return child.x + child.width >= 0 && child.x <= this.width + && child.y + child.height >= 0 && child.y <= this.height; + } + else + return true; + } + + virtual public int GetFirstChildInView() + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (IsChildInView(child)) + return i; + } + + return -1; + } + + protected void SetupScroll(ByteBuffer buffer) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + scrollPane = new ScrollPane(this); + scrollPane.Setup(buffer); + } + + protected void SetupOverflow(OverflowType overflow) + { + if (overflow == OverflowType.Hidden) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + UpdateClipRect(); + container.SetXY(_margin.left, _margin.top); + } + else if (_margin.left != 0 || _margin.top != 0) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + container.SetXY(_margin.left, _margin.top); + } + } + + void UpdateClipRect() + { + if (scrollPane == null) + { + float w = this.width - (_margin.left + _margin.right); + float h = this.height - (_margin.top + _margin.bottom); + rootContainer.clipRect = new Rect(_margin.left, _margin.top, w, h); + } + else + rootContainer.clipRect = new Rect(0, 0, this.width, this.height); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (scrollPane != null) + scrollPane.OnOwnerSizeChanged(); + if (rootContainer.clipRect != null) + UpdateClipRect(); + } + + override protected void HandleGrayedChanged() + { + Controller cc = GetController("grayed"); + if (cc != null) + cc.selectedIndex = this.grayed ? 1 : 0; + else + base.HandleGrayedChanged(); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (scrollPane != null) + scrollPane.HandleControllerChanged(c); + } + + /// + /// Notify the component the bounds should recaculate. + /// + public void SetBoundsChangedFlag() + { + if (scrollPane == null && !_trackBounds) + return; + + _boundsChanged = true; + } + + /// + /// Make sure the bounds of the component is correct. + /// Bounds of the component is not updated on every changed. For example, you add a new child to the list, children in the list will be rearranged in next frame. + /// If you want to access the correct child position immediatelly, call this function first. + /// + public void EnsureBoundsCorrect() + { + if (_boundsChanged) + UpdateBounds(); + } + + virtual protected void UpdateBounds() + { + float ax, ay, aw, ah; + if (_children.Count > 0) + { + ax = int.MaxValue; + ay = int.MaxValue; + float ar = int.MinValue, ab = int.MinValue; + float tmp; + + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + tmp = child.x; + if (tmp < ax) + ax = tmp; + tmp = child.y; + if (tmp < ay) + ay = tmp; + tmp = child.x + child.actualWidth; + if (tmp > ar) + ar = tmp; + tmp = child.y + child.actualHeight; + if (tmp > ab) + ab = tmp; + } + + aw = ar - ax; + ah = ab - ay; + } + else + { + ax = 0; + ay = 0; + aw = 0; + ah = 0; + } + + SetBounds(ax, ay, aw, ah); + } + + protected void SetBounds(float ax, float ay, float aw, float ah) + { + _boundsChanged = false; + if (scrollPane != null) + scrollPane.SetContentSize(Mathf.RoundToInt(ax + aw), Mathf.RoundToInt(ay + ah)); + } + + /// + /// Viwe port width of the container. + /// + public float viewWidth + { + get + { + if (scrollPane != null) + return scrollPane.viewWidth; + else + return this.width - _margin.left - _margin.right; + } + + set + { + if (scrollPane != null) + scrollPane.viewWidth = value; + else + this.width = value + _margin.left + _margin.right; + } + } + + /// + /// View port height of the container. + /// + public float viewHeight + { + get + { + if (scrollPane != null) + return scrollPane.viewHeight; + else + return this.height - _margin.top - _margin.bottom; + } + + set + { + if (scrollPane != null) + scrollPane.viewHeight = value; + else + this.height = value + _margin.top + _margin.bottom; + } + } + + public void GetSnappingPosition(ref float xValue, ref float yValue) + { + GetSnappingPositionWithDir(ref xValue, ref yValue, 0, 0); + } + + protected bool ShouldSnapToNext(float dir, float delta, float size) + { + return dir < 0 && delta > UIConfig.defaultScrollSnappingThreshold * size + || dir > 0 && delta > (1 - UIConfig.defaultScrollSnappingThreshold) * size + || dir == 0 && delta > size / 2; + } + + /** + * dir正数表示右移或者下移,负数表示左移或者上移 + */ + virtual public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) + { + int cnt = _children.Count; + if (cnt == 0) + return; + + EnsureBoundsCorrect(); + + GObject obj = null; + + int i = 0; + if (yValue != 0) + { + for (; i < cnt; i++) + { + obj = _children[i]; + if (yValue < obj.y) + { + if (i == 0) + { + yValue = 0; + break; + } + else + { + GObject prev = _children[i - 1]; + if (ShouldSnapToNext(yDir, yValue - prev.y, prev.height)) + yValue = obj.y; + else + yValue = prev.y; + break; + } + } + } + + if (i == cnt) + yValue = obj.y; + } + + if (xValue != 0) + { + if (i > 0) + i--; + for (; i < cnt; i++) + { + obj = _children[i]; + if (xValue < obj.x) + { + if (i == 0) + { + xValue = 0; + break; + } + else + { + GObject prev = _children[i - 1]; + if (ShouldSnapToNext(xDir, xValue - prev.x, prev.width)) + xValue = obj.x; + else + xValue = prev.x; + break; + } + } + } + + if (i == cnt) + { + xValue = obj.x; + } + } + } + + internal void ChildSortingOrderChanged(GObject child, int oldValue, int newValue) + { + if (newValue == 0) + { + _sortingChildCount--; + SetChildIndex(child, _children.Count); + } + else + { + if (oldValue == 0) + _sortingChildCount++; + + int oldIndex = _children.IndexOf(child); + int index = GetInsertPosForSortingChild(child); + if (oldIndex < index) + _SetChildIndex(child, oldIndex, index - 1); + else + _SetChildIndex(child, oldIndex, index); + } + } + + /// + /// 每帧调用的一个回调。如果你要override,请记住以下两点: + /// 1、记得调用base.onUpdate; + /// 2、不要在方法里进行任何会更改显示列表的操作,例如AddChild、RemoveChild、visible等。 + /// + protected virtual void OnUpdate() + { + if (_boundsChanged) + { + UpdateBounds(); + } + } + + override public void ConstructFromResource() + { + ConstructFromResource(null, 0); + } + + internal void ConstructFromResource(List objectPool, int poolIndex) + { + this.gameObjectName = packageItem.name; + PackageItem contentItem = packageItem.getBranch(); + + // [Y 修改] + if (Stage.inst.currLang != null) + { + if (!contentItem.translated) + { + TranslationHelper.TranslateComponent(contentItem); + contentItem.translated = true; + } + } + + + ByteBuffer buffer = contentItem.rawData; + buffer.Seek(0, 0); + + underConstruct = true; + + sourceWidth = buffer.ReadInt(); + sourceHeight = buffer.ReadInt(); + initWidth = sourceWidth; + initHeight = sourceHeight; + + SetSize(sourceWidth, sourceHeight); + + if (buffer.ReadBool()) + { + minWidth = buffer.ReadInt(); + maxWidth = buffer.ReadInt(); + minHeight = buffer.ReadInt(); + maxHeight = buffer.ReadInt(); + } + + if (buffer.ReadBool()) + { + float f1 = buffer.ReadFloat(); + float f2 = buffer.ReadFloat(); + SetPivot(f1, f2, buffer.ReadBool()); + } + + if (buffer.ReadBool()) + { + _margin.top = buffer.ReadInt(); + _margin.bottom = buffer.ReadInt(); + _margin.left = buffer.ReadInt(); + _margin.right = buffer.ReadInt(); + } + + OverflowType overflow = (OverflowType)buffer.ReadByte(); + if (overflow == OverflowType.Scroll) + { + int savedPos = buffer.position; + buffer.Seek(0, 7); + SetupScroll(buffer); + buffer.position = savedPos; + } + else + SetupOverflow(overflow); + + if (buffer.ReadBool()) + { + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + this.clipSoftness = new Vector2(i1, i2); + } + + _buildingDisplayList = true; + + buffer.Seek(0, 1); + + int controllerCount = buffer.ReadShort(); + for (int i = 0; i < controllerCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + Controller controller = new Controller(); + _controllers.Add(controller); + controller.parent = this; + controller.Setup(buffer); + + buffer.position = nextPos; + } + + buffer.Seek(0, 2); + + GObject child; + int childCount = buffer.ReadShort(); + for (int i = 0; i < childCount; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + if (objectPool != null) + child = objectPool[poolIndex + i]; + else + { + buffer.Seek(curPos, 0); + + ObjectType type = (ObjectType)buffer.ReadByte(); + string src = buffer.ReadS(); + string pkgId = buffer.ReadS(); + + PackageItem pi = null; + if (src != null) + { + UIPackage pkg; + if (pkgId != null) + pkg = UIPackage.GetById(pkgId); + else + pkg = contentItem.owner; + + pi = pkg != null ? pkg.GetItem(src) : null; + } + + if (pi != null) + { + child = UIObjectFactory.NewObject(pi); + child.ConstructFromResource(); + } + else + child = UIObjectFactory.NewObject(type); + } + + child.underConstruct = true; + child.Setup_BeforeAdd(buffer, curPos); + child.InternalSetParent(this); + _children.Add(child); + + buffer.position = curPos + dataLen; + } + + buffer.Seek(0, 3); + this.relations.Setup(buffer, true); + + buffer.Seek(0, 2); + buffer.Skip(2); + + for (int i = 0; i < childCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + buffer.Seek(buffer.position, 3); + _children[i].relations.Setup(buffer, false); + + buffer.position = nextPos; + } + + buffer.Seek(0, 2); + buffer.Skip(2); + + for (int i = 0; i < childCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + child = _children[i]; + child.Setup_AfterAdd(buffer, buffer.position); + child.underConstruct = false; + if (child.displayObject != null) + child.displayObject.cachedTransform.SetParent(this.displayObject.cachedTransform, false); + + buffer.position = nextPos; + } + + buffer.Seek(0, 4); + + buffer.Skip(2); //customData + this.opaque = buffer.ReadBool(); + int maskId = buffer.ReadShort(); + if (maskId != -1) + { + container.mask = GetChildAt(maskId).displayObject; + if (buffer.ReadBool()) + container.reversedMask = true; + } + + { + string hitTestId = buffer.ReadS(); + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + if (hitTestId != null) + { + PackageItem pi = contentItem.owner.GetItem(hitTestId); + if (pi != null && pi.pixelHitTestData != null) + rootContainer.hitArea = + new PixelHitTest(pi.pixelHitTestData, i1, i2, sourceWidth, sourceHeight); + } + else if (i1 != 0 && i2 != -1) + { + rootContainer.hitArea = new ShapeHitTest(this.GetChildAt(i2).displayObject); + } + } + if (buffer.version >= 5) + { + string str = buffer.ReadS(); + if (!string.IsNullOrEmpty(str)) + this.onAddedToStage.Add(() => __playSound(str, 1)); + + string str2 = buffer.ReadS(); + if (!string.IsNullOrEmpty(str2)) + this.onRemovedFromStage.Add(() => __playSound(str2, 1)); + } + + buffer.Seek(0, 5); + int transitionCount = buffer.ReadShort(); + for (int i = 0; i < transitionCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + Transition trans = new Transition(this); + trans.Setup(buffer); + _transitions.Add(trans); + + buffer.position = nextPos; + } + + if (_transitions.Count > 0) + { + this.onAddedToStage.Add(__addedToStage); + this.onRemovedFromStage.Add(__removedFromStage); + } + + ApplyAllControllers(); + _buildingDisplayList = false; + underConstruct = false; + BuildNativeDisplayList(); + SetBoundsChangedFlag(); + + if (contentItem.objectType != ObjectType.Component) + ConstructExtension(buffer); + ConstructFromXML(null); +#if FAIRYGUI_TOLUA + CallLua("ctor"); +#endif +#if FAIRYGUI_PUERTS + if (__onConstruct != null) + __onConstruct(); +#endif + } + + virtual protected void ConstructExtension(ByteBuffer buffer) + { + } + + /// + /// Method for extensions to override + /// + /// + virtual public void ConstructFromXML(XML xml) + { + } + + public override void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 4); + + int pageController = buffer.ReadShort(); + if (pageController != -1 && scrollPane != null && scrollPane.pageMode) + scrollPane.pageController = parent.GetControllerAt(pageController); + + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + Controller cc = GetController(buffer.ReadS()); + string pageId = buffer.ReadS(); + if (cc != null) + cc.selectedPageId = pageId; + } + + if (buffer.version >= 2) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + string value = buffer.ReadS(); + GObject obj = this.GetChildByPath(target); + if (obj != null) + { + if (propertyId == 0) + obj.text = value; + else if (propertyId == 1) + obj.icon = value; + } + } + } + } + + void __playSound(string soundRes, float volumeScale) + { + NAudioClip sound = UIPackage.GetItemAssetByURL(soundRes) as NAudioClip; + if (sound != null && sound.nativeClip != null) + Stage.inst.PlayOneShotSound(sound.nativeClip, volumeScale); + } + + void __addedToStage() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + _transitions[i].OnOwnerAddedToStage(); + } + + void __removedFromStage() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + _transitions[i].OnOwnerRemovedFromStage(); + } + +#if FAIRYGUI_TOLUA + internal LuaTable _peerTable; + + public void SetLuaPeer(LuaTable peerTable) + { + _peerTable = peerTable; + } + + [NoToLua] + public bool CallLua(string funcName) + { + if (_peerTable != null) + { + LuaFunction ctor = _peerTable.GetLuaFunction(funcName); + if (ctor != null) + { + try + { + ctor.Call(this); + } + catch (Exception err) + { + Debug.LogError(err); + } + + ctor.Dispose(); + return true; + } + } + + return false; + } +#endif + +#if FAIRYGUI_PUERTS + public Action __onConstruct; + public Action __onDispose; +#endif + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs.meta new file mode 100644 index 0000000..54ea769 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GComponent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a21ec486dca945f459590f80e1e6f699 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs new file mode 100644 index 0000000..430bdca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs @@ -0,0 +1,274 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GGraph class. + /// 对应编辑器里的图形对象。图形有两个用途,一是用来显示简单的图形,例如矩形等;二是作为一个占位的用途, + /// 可以将本对象替换为其他对象,或者在它的前后添加其他对象,相当于一个位置和深度的占位;还可以直接将内容设置 + /// 为原生对象。 + /// + public class GGraph : GObject, IColorGear + { + Shape _shape; + + public GGraph() + { + } + + override protected void CreateDisplayObject() + { + _shape = new Shape(); + _shape.gOwner = this; + displayObject = _shape; + } + + /// + /// Replace this object to another object in the display list. + /// 在显示列表中,将指定对象取代这个图形对象。这个图形对象相当于一个占位的用途。 + /// + /// Target object. + public void ReplaceMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + target.name = this.name; + target.alpha = this.alpha; + target.rotation = this.rotation; + target.visible = this.visible; + target.touchable = this.touchable; + target.grayed = this.grayed; + target.SetXY(this.x, this.y); + target.SetSize(this.width, this.height); + + int index = parent.GetChildIndex(this); + parent.AddChildAt(target, index); + target.relations.CopyFrom(this.relations); + + parent.RemoveChild(this, true); + } + + /// + /// Add another object before this object. + /// 在显示列表中,将另一个对象插入到这个对象的前面。 + /// + /// Target object. + public void AddBeforeMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + int index = parent.GetChildIndex(this); + parent.AddChildAt(target, index); + } + + /// + /// Add another object after this object. + /// 在显示列表中,将另一个对象插入到这个对象的后面。 + /// + /// Target object. + public void AddAfterMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + int index = parent.GetChildIndex(this); + index++; + parent.AddChildAt(target, index); + } + + /// + /// 设置内容为一个原生对象。这个图形对象相当于一个占位的用途。 + /// + /// 原生对象 + public void SetNativeObject(DisplayObject obj) + { + if (displayObject == obj) + return; + + if (_shape != null) + { + if (_shape.parent != null) + _shape.parent.RemoveChild(displayObject, true); + else + _shape.Dispose(); + _shape.gOwner = null; + _shape = null; + } + + displayObject = obj; + + if (displayObject != null) + { + displayObject.alpha = this.alpha; + displayObject.rotation = this.rotation; + displayObject.visible = this.visible; + displayObject.touchable = this.touchable; + displayObject.gOwner = this; + } + + if (parent != null) + parent.ChildStateChanged(this); + HandlePositionChanged(); + } + + /// + /// + /// + public Color color + { + get + { + if (_shape != null) + return _shape.color; + else + return Color.clear; + } + set + { + if (_shape != null && _shape.color != value) + { + _shape.color = value; + UpdateGear(4); + } + } + } + + /// + /// Get the shape object. It can be used for drawing. + /// 获取图形的原生对象,可用于绘制图形。 + /// + public Shape shape + { + get { return _shape; } + } + + /// + /// Draw a rectangle. + /// 画矩形。 + /// + /// Width + /// Height + /// Line size + /// Line color + /// Fill color + public void DrawRect(float aWidth, float aHeight, int lineSize, Color lineColor, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawRect(lineSize, lineColor, fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawRoundRect(float aWidth, float aHeight, Color fillColor, float[] corner) + { + this.SetSize(aWidth, aHeight); + this.shape.DrawRoundRect(0, Color.white, fillColor, corner[0], corner[1], corner[2], corner[3]); + } + + /// + /// + /// + /// + /// + /// + public void DrawEllipse(float aWidth, float aHeight, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawEllipse(fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawPolygon(points, fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor, float lineSize, Color lineColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawPolygon(points, fillColor, lineSize, lineColor); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + int type = buffer.ReadByte(); + if (type != 0) + { + int lineSize = buffer.ReadInt(); + Color lineColor = buffer.ReadColor(); + Color fillColor = buffer.ReadColor(); + bool roundedRect = buffer.ReadBool(); + Vector4 cornerRadius = new Vector4(); + if (roundedRect) + { + for (int i = 0; i < 4; i++) + cornerRadius[i] = buffer.ReadFloat(); + } + + if (type == 1) + { + if (roundedRect) + _shape.DrawRoundRect(lineSize, lineColor, fillColor, cornerRadius.x, cornerRadius.y, cornerRadius.z, cornerRadius.w); + else + _shape.DrawRect(lineSize, lineColor, fillColor); + } + else if (type == 2) + _shape.DrawEllipse(lineSize, fillColor, lineColor, fillColor, 0, 360); + else if (type == 3) + { + int cnt = buffer.ReadShort() / 2; + Vector2[] points = new Vector2[cnt]; + for (int i = 0; i < cnt; i++) + points[i].Set(buffer.ReadFloat(), buffer.ReadFloat()); + + _shape.DrawPolygon(points, fillColor, lineSize, lineColor); + } + else if (type == 4) + { + int sides = buffer.ReadShort(); + float startAngle = buffer.ReadFloat(); + int cnt = buffer.ReadShort(); + float[] distances = null; + if (cnt > 0) + { + distances = new float[cnt]; + for (int i = 0; i < cnt; i++) + distances[i] = buffer.ReadFloat(); + } + + _shape.DrawRegularPolygon(sides, lineSize, fillColor, lineColor, fillColor, startAngle, distances); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs.meta new file mode 100644 index 0000000..a94e52e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 913b7964e87194d4182c1ad388d94f19 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs new file mode 100644 index 0000000..d3d5d34 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs @@ -0,0 +1,538 @@ +using System; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// GGroup class. + /// 组对象,对应编辑器里的高级组。 + /// + public class GGroup : GObject + { + GroupLayoutType _layout; + int _lineGap; + int _columnGap; + + bool _excludeInvisibles; + bool _autoSizeDisabled; + int _mainGridIndex; + int _mainGridMinSize; + + bool _percentReady; + bool _boundsChanged; + int _mainChildIndex; + float _totalSize; + int _numChildren; + internal int _updating; + + Action _refreshDelegate; + + public GGroup() + { + _mainGridIndex = -1; + _mainChildIndex = -1; + _mainGridMinSize = 50; + _refreshDelegate = EnsureBoundsCorrect; + } + + /// + /// Group layout type. + /// + public GroupLayoutType layout + { + get { return _layout; } + set + { + if (_layout != value) + { + _layout = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int lineGap + { + get { return _lineGap; } + set + { + if (_lineGap != value) + { + _lineGap = value; + SetBoundsChangedFlag(true); + } + } + } + + /// + /// + /// + public int columnGap + { + get { return _columnGap; } + set + { + if (_columnGap != value) + { + _columnGap = value; + SetBoundsChangedFlag(true); + } + } + } + + /// + /// + /// + public bool excludeInvisibles + { + get { return _excludeInvisibles; } + set + { + if (_excludeInvisibles != value) + { + _excludeInvisibles = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public bool autoSizeDisabled + { + get { return _autoSizeDisabled; } + set + { + if (_autoSizeDisabled != value) + { + _autoSizeDisabled = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int mainGridMinSize + { + get { return _mainGridMinSize; } + set + { + if (_mainGridMinSize != value) + { + _mainGridMinSize = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int mainGridIndex + { + get { return _mainGridIndex; } + set + { + if (_mainGridIndex != value) + { + _mainGridIndex = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// Update group bounds. + /// 更新组的包围. + /// + public void SetBoundsChangedFlag(bool positionChangedOnly = false) + { + if (_updating == 0 && parent != null) + { + if (!positionChangedOnly) + _percentReady = false; + + if (!_boundsChanged) + { + _boundsChanged = true; + + if (_layout != GroupLayoutType.None) + { + UpdateContext.OnBegin -= _refreshDelegate; + UpdateContext.OnBegin += _refreshDelegate; + } + } + } + } + + public void EnsureBoundsCorrect() + { + if (parent == null || !_boundsChanged) + return; + + UpdateContext.OnBegin -= _refreshDelegate; + _boundsChanged = false; + + if (_autoSizeDisabled) + ResizeChildren(0, 0); + else + { + HandleLayout(); + UpdateBounds(); + } + } + + void UpdateBounds() + { + int cnt = parent.numChildren; + int i; + GObject child; + float ax = int.MaxValue, ay = int.MaxValue; + float ar = int.MinValue, ab = int.MinValue; + float tmp; + bool empty = true; + bool skipInvisibles = _layout != GroupLayoutType.None && _excludeInvisibles; + + for (i = 0; i < cnt; i++) + { + child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (skipInvisibles && !child.internalVisible3) + continue; + + tmp = child.xMin; + if (tmp < ax) + ax = tmp; + tmp = child.yMin; + if (tmp < ay) + ay = tmp; + tmp = child.xMin + child.width; + if (tmp > ar) + ar = tmp; + tmp = child.yMin + child.height; + if (tmp > ab) + ab = tmp; + + empty = false; + } + + float w; + float h; + if (!empty) + { + _updating |= 1; + SetXY(ax, ay); + _updating &= 2; + + w = ar - ax; + h = ab - ay; + } + else + w = h = 0; + + if ((_updating & 2) == 0) + { + _updating |= 2; + SetSize(w, h); + _updating &= 1; + } + else + { + _updating &= 1; + ResizeChildren(_width - w, _height - h); + } + } + + void HandleLayout() + { + _updating |= 1; + + if (_layout == GroupLayoutType.Horizontal) + { + float curX = this.x; + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + if (_excludeInvisibles && !child.internalVisible3) + continue; + + child.xMin = curX; + if (child.width != 0) + curX += child.width + _columnGap; + } + } + else if (_layout == GroupLayoutType.Vertical) + { + float curY = this.y; + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + if (_excludeInvisibles && !child.internalVisible3) + continue; + + child.yMin = curY; + if (child.height != 0) + curY += child.height + _lineGap; + } + } + + _updating &= 2; + } + + internal void MoveChildren(float dx, float dy) + { + if ((_updating & 1) != 0 || parent == null) + return; + + _updating |= 1; + + int cnt = parent.numChildren; + int i; + GObject child; + for (i = 0; i < cnt; i++) + { + child = parent.GetChildAt(i); + if (child.group == this) + { + child.SetXY(child.x + dx, child.y + dy); + } + } + + _updating &= 2; + } + + internal void ResizeChildren(float dw, float dh) + { + if (_layout == GroupLayoutType.None || (_updating & 2) != 0 || parent == null) + return; + + _updating |= 2; + + if (_boundsChanged) + { + _boundsChanged = false; + if (!_autoSizeDisabled) + { + UpdateBounds(); + return; + } + } + + int cnt = parent.numChildren; + + if (!_percentReady) + { + _percentReady = true; + _numChildren = 0; + _totalSize = 0; + _mainChildIndex = -1; + + int j = 0; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (!_excludeInvisibles || child.internalVisible3) + { + if (j == _mainGridIndex) + _mainChildIndex = i; + + _numChildren++; + + if (_layout == GroupLayoutType.Horizontal) + _totalSize += child.width; + else + _totalSize += child.height; + } + + j++; + } + + if (_mainChildIndex != -1) + { + if (_layout == GroupLayoutType.Horizontal) + { + GObject child = parent.GetChildAt(_mainChildIndex); + _totalSize += _mainGridMinSize - child.width; + child._sizePercentInGroup = _mainGridMinSize / _totalSize; + } + else + { + GObject child = parent.GetChildAt(_mainChildIndex); + _totalSize += _mainGridMinSize - child.height; + child._sizePercentInGroup = _mainGridMinSize / _totalSize; + } + } + + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (i == _mainChildIndex) + continue; + + if (_totalSize > 0) + child._sizePercentInGroup = (_layout == GroupLayoutType.Horizontal ? child.width : child.height) / _totalSize; + else + child._sizePercentInGroup = 0; + } + } + + float remainSize = 0; + float remainPercent = 1; + bool priorHandled = false; + + if (_layout == GroupLayoutType.Horizontal) + { + remainSize = this.width - (_numChildren - 1) * _columnGap; + if (_mainChildIndex != -1 && remainSize >= _totalSize) + { + GObject child = parent.GetChildAt(_mainChildIndex); + child.SetSize(remainSize - (_totalSize - _mainGridMinSize), child._rawHeight + dh, true); + remainSize -= child.width; + remainPercent -= child._sizePercentInGroup; + priorHandled = true; + } + + float curX = this.x; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (_excludeInvisibles && !child.internalVisible3) + { + child.SetSize(child._rawWidth, child._rawHeight + dh, true); + continue; + } + + if (!priorHandled || i != _mainChildIndex) + { + child.SetSize(Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), child._rawHeight + dh, true); + remainPercent -= child._sizePercentInGroup; + remainSize -= child.width; + } + + child.xMin = curX; + if (child.width != 0) + curX += child.width + _columnGap; + } + } + else + { + remainSize = this.height - (_numChildren - 1) * _lineGap; + if (_mainChildIndex != -1 && remainSize >= _totalSize) + { + GObject child = parent.GetChildAt(_mainChildIndex); + child.SetSize(child._rawWidth + dw, remainSize - (_totalSize - _mainGridMinSize), true); + remainSize -= child.height; + remainPercent -= child._sizePercentInGroup; + priorHandled = true; + } + + float curY = this.y; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (_excludeInvisibles && !child.internalVisible3) + { + child.SetSize(child._rawWidth + dw, child._rawHeight, true); + continue; + } + + if (!priorHandled || i != _mainChildIndex) + { + child.SetSize(child._rawWidth + dw, Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), true); + remainPercent -= child._sizePercentInGroup; + remainSize -= child.height; + } + + child.yMin = curY; + if (child.height != 0) + curY += child.height + _lineGap; + } + } + + _updating &= 1; + } + + override protected void HandleAlphaChanged() + { + base.HandleAlphaChanged(); + + if (this.underConstruct || parent == null) + return; + + int cnt = parent.numChildren; + float a = this.alpha; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group == this) + child.alpha = a; + } + } + + override internal protected void HandleVisibleChanged() + { + if (parent == null) + return; + + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group == this) + child.HandleVisibleChanged(); + } + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _layout = (GroupLayoutType)buffer.ReadByte(); + _lineGap = buffer.ReadInt(); + _columnGap = buffer.ReadInt(); + if (buffer.version >= 2) + { + _excludeInvisibles = buffer.ReadBool(); + _autoSizeDisabled = buffer.ReadBool(); + _mainGridIndex = buffer.ReadShort(); + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!this.visible) + HandleVisibleChanged(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs.meta new file mode 100644 index 0000000..307b9aa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GGroup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b8aac7740f89ffc409bfb6cd30d58fec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs new file mode 100644 index 0000000..f9ac898 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs @@ -0,0 +1,170 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GImage class. + /// + public class GImage : GObject, IColorGear + { + Image _content; + + public GImage() + { + } + + override protected void CreateDisplayObject() + { + _content = new Image(); + _content.gOwner = this; + displayObject = _content; + } + + /// + /// Color of the image. + /// + public Color color + { + get { return _content.color; } + set + { + _content.color = value; + UpdateGear(4); + } + } + + /// + /// Flip type. + /// + /// + public FlipType flip + { + get { return _content.graphics.flip; } + set { _content.graphics.flip = value; } + } + + /// + /// Fill method. + /// + /// + public FillMethod fillMethod + { + get { return _content.fillMethod; } + set { _content.fillMethod = value; } + } + + /// + /// Fill origin. + /// + /// + /// + /// + /// + /// + public int fillOrigin + { + get { return _content.fillOrigin; } + set { _content.fillOrigin = value; } + } + + /// + /// Fill clockwise if true. + /// + public bool fillClockwise + { + get { return _content.fillClockwise; } + set { _content.fillClockwise = value; } + } + + /// + /// Fill amount. (0~1) + /// + public float fillAmount + { + get { return _content.fillAmount; } + set { _content.fillAmount = value; } + } + + /// + /// Set texture directly. The image wont own the texture. + /// + public NTexture texture + { + get { return _content.texture; } + set + { + if (value != null) + { + sourceWidth = value.width; + sourceHeight = value.height; + } + else + { + sourceWidth = 0; + sourceHeight = 0; + } + initWidth = sourceWidth; + initHeight = sourceHeight; + _content.texture = value; + } + } + + /// + /// Set material. + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// Set shader. + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + override public void ConstructFromResource() + { + this.gameObjectName = packageItem.name; + + PackageItem contentItem = packageItem.getBranch(); + sourceWidth = contentItem.width; + sourceHeight = contentItem.height; + initWidth = sourceWidth; + initHeight = sourceHeight; + + contentItem = contentItem.getHighResolution(); + contentItem.Load(); + _content.scale9Grid = contentItem.scale9Grid; + _content.scaleByTile = contentItem.scaleByTile; + _content.tileGridIndice = contentItem.tileGridIndice; + _content.texture = contentItem.texture; + _content.textureScale = new Vector2(contentItem.width / (float)sourceWidth, contentItem.height / (float)sourceHeight); + + SetSize(sourceWidth, sourceHeight); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.graphics.flip = (FlipType)buffer.ReadByte(); + _content.fillMethod = (FillMethod)buffer.ReadByte(); + if (_content.fillMethod != FillMethod.None) + { + _content.fillOrigin = buffer.ReadByte(); + _content.fillClockwise = buffer.ReadBool(); + _content.fillAmount = buffer.ReadFloat(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs.meta new file mode 100644 index 0000000..a8d12df --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GImage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 106156ac7c8773640af01f14fd396393 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs new file mode 100644 index 0000000..333cd3e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs @@ -0,0 +1,235 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GLabel class. + /// + public class GLabel : GComponent, IColorGear + { + protected GObject _titleObject; + protected GObject _iconObject; + + public GLabel() + { + } + + /// + /// Icon of the label. + /// + override public string icon + { + get + { + if (_iconObject != null) + return _iconObject.icon; + else + return null; + } + + set + { + if (_iconObject != null) + _iconObject.icon = value; + UpdateGear(7); + } + } + + /// + /// Title of the label. + /// + public string title + { + get + { + if (_titleObject != null) + return _titleObject.text; + else + return null; + } + set + { + if (_titleObject != null) + _titleObject.text = value; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// If title is input text. + /// + public bool editable + { + get + { + if (_titleObject is GTextInput) + return _titleObject.asTextInput.editable; + else + return false; + } + + set + { + if (_titleObject is GTextInput) + _titleObject.asTextInput.editable = value; + } + } + + /// + /// Title color of the label + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + tf.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// + /// + public Color color + { + get { return this.titleColor; } + set { this.titleColor = value; } + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + str = buffer.ReadS(); + if (str != null) + this.title = str; + str = buffer.ReadS(); + if (str != null) + this.icon = str; + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv != 0) + this.titleFontSize = iv; + + if (buffer.ReadBool()) + { + GTextInput input = GetTextField() as GTextInput; + if (input != null) + { + str = buffer.ReadS(); + if (str != null) + input.promptText = str; + + str = buffer.ReadS(); + if (str != null) + input.restrict = str; + + iv = buffer.ReadInt(); + if (iv != 0) + input.maxLength = iv; + iv = buffer.ReadInt(); + if (iv != 0) + input.keyboardType = iv; + if (buffer.ReadBool()) + input.displayAsPassword = true; + } + else + buffer.Skip(13); + } + + if (buffer.version >= 5) + { + string sound = buffer.ReadS(); + if (!string.IsNullOrEmpty(sound)) + { + float volumeScale = buffer.ReadFloat(); + displayObject.onClick.Add(() => + { + NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; + if (audioClip != null && audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); + }); + } + else + buffer.Skip(4); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs.meta new file mode 100644 index 0000000..e400470 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLabel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd9c62cc282bb9b4fa9e794317eedd30 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs new file mode 100644 index 0000000..f875963 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs @@ -0,0 +1,3151 @@ +using System; +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Callback function when an item is needed to update its look. + /// + /// Item index. + /// Item object. + public delegate void ListItemRenderer(int index, GObject item); + + /// + /// + /// + /// + /// + public delegate string ListItemProvider(int index); + + /// + /// GList class. + /// + public class GList : GComponent + { + /// + /// 如果true,当item不可见时自动折叠,否则依然占位 + /// + public bool foldInvisibleItems = false; + + /// + /// List selection mode + /// + /// + public ListSelectionMode selectionMode; + + /// + /// Callback function when an item is needed to update its look. + /// + public ListItemRenderer itemRenderer; + + /// + /// Callback funtion to return item resource url. + /// + public ListItemProvider itemProvider; + + /// + /// + /// + public bool scrollItemToViewOnClick; + + string _defaultItem; + ListLayoutType _layout; + int _lineCount; + int _columnCount; + int _lineGap; + int _columnGap; + AlignType _align; + VertAlignType _verticalAlign; + bool _autoResizeItem; + Controller _selectionController; + + GObjectPool _pool; + int _lastSelectedIndex; + + EventListener _onClickItem; + EventListener _onRightClickItem; + + //Virtual List support + bool _virtual; + bool _loop; + int _numItems; + int _realNumItems; + int _firstIndex; //the top left index + int _curLineItemCount; //item count in one line + int _curLineItemCount2; //只用在页面模式,表示垂直方向的项目数 + Vector2 _itemSize; + int _virtualListChanged; //1-content changed, 2-size changed + uint itemInfoVer; //用来标志item是否在本次处理中已经被重用了 + + int _miscFlags; //1-event locked, 2-focus events registered + + class ItemInfo + { + public Vector2 size; + public GObject obj; + public uint updateFlag; + public bool selected; + } + List _virtualItems; + + EventCallback1 _itemClickDelegate; + + public GList() + : base() + { + _trackBounds = true; + this.opaque = true; + scrollItemToViewOnClick = true; + + container = new Container(); + rootContainer.AddChild(container); + rootContainer.gameObject.name = "GList"; + + _pool = new GObjectPool(container.cachedTransform); + + _itemClickDelegate = __clickItem; + } + + public override void Dispose() + { + _pool.Clear(); + if (_virtualListChanged != 0) + Timers.inst.Remove(this.RefreshVirtualList); + + _selectionController = null; + scrollItemToViewOnClick = false; + itemRenderer = null; + itemProvider = null; + + base.Dispose(); + } + + /// + /// [Y 修改] + /// + public void ClearPool() + { + if (_pool != null) + { + _pool.Clear(); + } + } + + /// + /// Dispatched when a list item being clicked. + /// + public EventListener onClickItem + { + get { return _onClickItem ?? (_onClickItem = new EventListener(this, "onClickItem")); } + } + + /// + /// Dispatched when a list item being clicked with right button. + /// + public EventListener onRightClickItem + { + get { return _onRightClickItem ?? (_onRightClickItem = new EventListener(this, "onRightClickItem")); } + } + + /// + /// Resource url of the default item. + /// + public string defaultItem + { + get { return _defaultItem; } + set + { + _defaultItem = UIPackage.NormalizeURL(value); + } + } + + /// + /// List layout type. + /// + public ListLayoutType layout + { + get { return _layout; } + set + { + if (_layout != value) + { + _layout = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public int lineCount + { + get { return _lineCount; } + set + { + if (_lineCount != value) + { + _lineCount = value; + if (_layout == ListLayoutType.FlowVertical || _layout == ListLayoutType.Pagination) + { + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + } + + /// + /// + /// + public int columnCount + { + get { return _columnCount; } + set + { + if (_columnCount != value) + { + _columnCount = value; + if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + } + + /// + /// + /// + public int lineGap + { + get { return _lineGap; } + set + { + if (_lineGap != value) + { + _lineGap = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public int columnGap + { + get { return _columnGap; } + set + { + if (_columnGap != value) + { + _columnGap = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public AlignType align + { + get { return _align; } + set + { + if (_align != value) + { + _align = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + /// + /// If the item will resize itself to fit the list width/height. + /// + public bool autoResizeItem + { + get { return _autoResizeItem; } + set + { + if (_autoResizeItem != value) + { + _autoResizeItem = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + /// + public Vector2 defaultItemSize + { + get { return _itemSize; } + set + { + _itemSize = value; + if (_virtual) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.scrollPane.scrollStep = _itemSize.y; + else + this.scrollPane.scrollStep = _itemSize.x; + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public GObjectPool itemPool + { + get { return _pool; } + } + + /// + /// + /// + /// + /// + public GObject GetFromPool(string url) + { + if (string.IsNullOrEmpty(url)) + url = _defaultItem; + + GObject ret = _pool.GetObject(url); + if (ret != null) + ret.visible = true; + return ret; + } + + void ReturnToPool(GObject obj) + { + _pool.ReturnObject(obj); + } + + /// + /// Add a item to list, same as GetFromPool+AddChild + /// + /// Item object + public GObject AddItemFromPool() + { + GObject obj = GetFromPool(null); + + return AddChild(obj); + } + + /// + /// Add a item to list, same as GetFromPool+AddChild + /// + /// Item resource url + /// Item object + public GObject AddItemFromPool(string url) + { + GObject obj = GetFromPool(url); + + return AddChild(obj); + } + + /// + /// + /// + /// + /// + /// + override public GObject AddChildAt(GObject child, int index) + { + base.AddChildAt(child, index); + if (child is GButton) + { + GButton button = (GButton)child; + button.selected = false; + button.changeStateOnClick = false; + } + + child.onClick.Add(_itemClickDelegate); + child.onRightClick.Add(_itemClickDelegate); + + return child; + } + + /// + /// + /// + /// + /// + /// + override public GObject RemoveChildAt(int index, bool dispose) + { + GObject child = base.RemoveChildAt(index, dispose); + child.onClick.Remove(_itemClickDelegate); + child.onRightClick.Remove(_itemClickDelegate); + + return child; + } + + /// + /// + /// + /// + public void RemoveChildToPoolAt(int index) + { + GObject child = base.RemoveChildAt(index); + ReturnToPool(child); + } + + /// + /// + /// + /// + public void RemoveChildToPool(GObject child) + { + base.RemoveChild(child); + ReturnToPool(child); + } + + /// + /// + /// + public void RemoveChildrenToPool() + { + RemoveChildrenToPool(0, -1); + } + + /// + /// + /// + /// + /// + public void RemoveChildrenToPool(int beginIndex, int endIndex) + { + if (endIndex < 0 || endIndex >= _children.Count) + endIndex = _children.Count - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildToPoolAt(beginIndex); + } + + /// + /// + /// + public int selectedIndex + { + get + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && ((GButton)ii.obj).selected + || ii.obj == null && ii.selected) + { + if (_loop) + return i % _numItems; + else + return i; + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + return i; + } + } + return -1; + } + + set + { + if (value >= 0 && value < this.numItems) + { + if (selectionMode != ListSelectionMode.Single) + ClearSelection(); + AddSelection(value, false); + } + else + ClearSelection(); + } + } + + /// + /// + /// + public Controller selectionController + { + get { return _selectionController; } + set { _selectionController = value; } + } + + /// + /// + /// + /// + public List GetSelection() + { + return GetSelection(null); + } + + /// + /// + /// + /// + public List GetSelection(List result) + { + if (result == null) + result = new List(); + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && ((GButton)ii.obj).selected + || ii.obj == null && ii.selected) + { + int j = i; + if (_loop) + { + j = i % _numItems; + if (result.Contains(j)) + continue; + } + result.Add(j); + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + result.Add(i); + } + } + return result; + } + + /// + /// + /// + /// + /// + public void AddSelection(int index, bool scrollItToView) + { + if (selectionMode == ListSelectionMode.None) + return; + + CheckVirtualList(); + + if (selectionMode == ListSelectionMode.Single) + ClearSelection(); + + if (scrollItToView) + ScrollToView(index); + + _lastSelectedIndex = index; + GButton obj = null; + if (_virtual) + { + ItemInfo ii = _virtualItems[index]; + if (ii.obj != null) + obj = ii.obj.asButton; + ii.selected = true; + } + else + obj = GetChildAt(index).asButton; + + if (obj != null && !obj.selected) + { + obj.selected = true; + UpdateSelectionController(index); + } + } + + /// + /// + /// + /// + public void RemoveSelection(int index) + { + if (selectionMode == ListSelectionMode.None) + return; + + GButton obj = null; + if (_virtual) + { + ItemInfo ii = _virtualItems[index]; + if (ii.obj != null) + obj = ii.obj.asButton; + ii.selected = false; + } + else + obj = GetChildAt(index).asButton; + + if (obj != null) + obj.selected = false; + } + + /// + /// + /// + public void ClearSelection() + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton)) + ((GButton)ii.obj).selected = false; + ii.selected = false; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null) + obj.selected = false; + } + } + } + + void ClearSelectionExcept(GObject g) + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.obj != g) + { + if ((ii.obj is GButton)) + ((GButton)ii.obj).selected = false; + ii.selected = false; + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj != g) + obj.selected = false; + } + } + } + + /// + /// + /// + public void SelectAll() + { + CheckVirtualList(); + + int last = -1; + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && !((GButton)ii.obj).selected) + { + ((GButton)ii.obj).selected = true; + last = i; + } + ii.selected = true; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && !obj.selected) + { + obj.selected = true; + last = i; + } + } + } + + if (last != -1) + UpdateSelectionController(last); + } + + /// + /// + /// + public void SelectNone() + { + ClearSelection(); + } + + /// + /// + /// + public void SelectReverse() + { + CheckVirtualList(); + + int last = -1; + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton)) + { + ((GButton)ii.obj).selected = !((GButton)ii.obj).selected; + if (((GButton)ii.obj).selected) + last = i; + } + ii.selected = !ii.selected; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null) + { + obj.selected = !obj.selected; + if (obj.selected) + last = i; + } + } + } + + if (last != -1) + UpdateSelectionController(last); + } + + /// + /// + /// + /// + public void EnableSelectionFocusEvents(bool enabled) + { + if (((_miscFlags & 2) != 0) == enabled) + return; + + if (enabled) + { + _miscFlags |= 2; + this.tabStopChildren = true; + onFocusIn.Add(NotifySelection); + onFocusOut.Add(NotifySelection); + } + else + { + _miscFlags &= 0xFD; + onFocusIn.Remove(NotifySelection); + onFocusOut.Remove(NotifySelection); + } + } + + void NotifySelection(EventContext context) + { + string eventType = context.type == "onFocusIn" ? "onListFocusIn" : "onListFocusOut"; + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + obj.DispatchEvent(eventType); + } + } + + /// + /// + /// + public void EnableArrowKeyNavigation(bool enabled) + { + if (enabled) + { + this.tabStopChildren = true; + onKeyDown.Add(__keydown); + } + else + { + this.tabStopChildren = false; + onKeyDown.Remove(__keydown); + } + } + + void __keydown(EventContext context) + { + int index = -1; + switch (context.inputEvent.keyCode) + { + case KeyCode.LeftArrow: + index = HandleArrowKey(7); + break; + + case KeyCode.RightArrow: + index = HandleArrowKey(3); + break; + + case KeyCode.UpArrow: + index = HandleArrowKey(1); + break; + + case KeyCode.DownArrow: + index = HandleArrowKey(5); + break; + } + + if (index != -1) + { + index = ItemIndexToChildIndex(index); + if (index != -1) + DispatchItemEvent(GetChildAt(index), context); + + context.StopPropagation(); + } + } + + /// + /// + /// + /// + public int HandleArrowKey(int dir) + { + int curIndex = this.selectedIndex; + if (curIndex == -1) + return -1; + + int index = curIndex; + switch (dir) + { + case 1://up + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) + { + index--; + } + else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + if (_virtual) + { + index -= _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int i; + for (i = index - 1; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + current = obj; + break; + } + k++; + } + for (; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + index = i + k + 1; + break; + } + } + } + } + break; + + case 3://right + if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + index++; + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_virtual) + { + index += _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int cnt = _children.Count; + int i; + for (i = index + 1; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + current = obj; + break; + } + k++; + } + for (; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + index = i - k - 1; + break; + } + } + } + } + break; + + case 5://down + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) + { + index++; + } + else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + if (_virtual) + { + index += _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int cnt = _children.Count; + int i; + for (i = index + 1; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + current = obj; + break; + } + k++; + } + for (; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + index = i - k - 1; + break; + } + } + } + } + break; + + case 7://left + if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + index--; + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_virtual) + { + index -= _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int i; + for (i = index - 1; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + current = obj; + break; + } + k++; + } + for (; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + index = i + k + 1; + break; + } + } + } + } + break; + } + + if (index != curIndex && index >= 0 && index < this.numItems) + { + ClearSelection(); + AddSelection(index, true); + return index; + } + else + return -1; + } + + void __clickItem(EventContext context) + { + GObject item = context.sender as GObject; + if ((item is GButton) && selectionMode != ListSelectionMode.None) + SetSelectionOnEvent(item, context.inputEvent); + + if (scrollPane != null && scrollItemToViewOnClick) + scrollPane.ScrollToView(item, true); + + DispatchItemEvent(item, context); + } + + virtual protected void DispatchItemEvent(GObject item, EventContext context) + { + if (context.type == item.onRightClick.type) + DispatchEvent("onRightClickItem", item); + else + DispatchEvent("onClickItem", item); + } + + void SetSelectionOnEvent(GObject item, InputEvent evt) + { + bool dontChangeLastIndex = false; + GButton button = (GButton)item; + int index = ChildIndexToItemIndex(GetChildIndex(item)); + + if (selectionMode == ListSelectionMode.Single) + { + if (!button.selected) + { + ClearSelectionExcept(button); + button.selected = true; + } + } + else + { + if (evt.shift) + { + if (!button.selected) + { + if (_lastSelectedIndex != -1) + { + int min = Math.Min(_lastSelectedIndex, index); + int max = Math.Max(_lastSelectedIndex, index); + max = Math.Min(max, this.numItems - 1); + if (_virtual) + { + for (int i = min; i <= max; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.obj is GButton) + ((GButton)ii.obj).selected = true; + ii.selected = true; + } + } + else + { + for (int i = min; i <= max; i++) + { + GButton obj = GetChildAt(i).asButton; + if (obj != null && !obj.selected) + obj.selected = true; + } + } + + dontChangeLastIndex = true; + } + else + { + button.selected = true; + } + } + } + else if (evt.ctrl || evt.ctrlOrCmd || selectionMode == ListSelectionMode.Multiple_SingleClick) + { + button.selected = !button.selected; + } + else + { + if (!button.selected) + { + ClearSelectionExcept(button); + button.selected = true; + } + else if (evt.button == 0) + ClearSelectionExcept(button); + } + } + + if (!dontChangeLastIndex) + _lastSelectedIndex = index; + + if (button.selected) + UpdateSelectionController(index); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + public void ResizeToFit() + { + ResizeToFit(int.MaxValue, 0); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + /// Item count + public void ResizeToFit(int itemCount) + { + ResizeToFit(itemCount, 0); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + /// >Item count + /// If the result size if smaller than minSize, then use minSize. + public void ResizeToFit(int itemCount, int minSize) + { + EnsureBoundsCorrect(); + + int curCount = this.numItems; + if (itemCount > curCount) + itemCount = curCount; + + if (_virtual) + { + int lineCount = Mathf.CeilToInt((float)itemCount / _curLineItemCount); + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = lineCount * _itemSize.y + Math.Max(0, lineCount - 1) * _lineGap; + else + this.viewWidth = lineCount * _itemSize.x + Math.Max(0, lineCount - 1) * _columnGap; + } + else if (itemCount == 0) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = minSize; + else + this.viewWidth = minSize; + } + else + { + int i = itemCount - 1; + GObject obj = null; + while (i >= 0) + { + obj = this.GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + break; + i--; + } + if (i < 0) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = minSize; + else + this.viewWidth = minSize; + } + else + { + float size; + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + size = obj.y + obj.height; + if (size < minSize) + size = minSize; + this.viewHeight = size; + } + else + { + size = obj.x + obj.width; + if (size < minSize) + size = minSize; + this.viewWidth = size; + } + } + } + } + + /// + /// + /// + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_selectionController == c) + this.selectedIndex = c.selectedIndex; + } + + void UpdateSelectionController(int index) + { + if (_selectionController != null && !_selectionController.changing + && index < _selectionController.pageCount) + { + Controller c = _selectionController; + _selectionController = null; + c.selectedIndex = index; + _selectionController = c; + } + } + + /// + /// [Y 修改] + /// 控制动画缓动时间 + /// + private float m_animTweenTime = 0f; + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + public void ScrollToView(int index) + { + // [Y 修改] + m_animTweenTime = 0f; + ScrollToView(index, false); + } + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + /// True to scroll smoothly, othewise immdediately. + public void ScrollToView(int index, bool ani) + { + // [Y 修改] + m_animTweenTime = 0f; + ScrollToView(index, ani, false); + } + + /// + /// [Y 修改] + /// 控制动画缓动时间 + /// + public void ScrollToView_UseAnim(int index, bool ani, float animTweenTime) + { + if (ani) + { + m_animTweenTime = animTweenTime; + } + ScrollToView(index, ani, false); + } + /// + /// [Y 修改] + /// 设置动画缓动时间 + /// + private void SetAnimTweenTime(ScrollPane curSorollPane, bool ani) + { + if (ani) + { + curSorollPane.SetAnimTweenTime(m_animTweenTime); + } + } + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + /// True to scroll smoothly, othewise immdediately. + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(int index, bool ani, bool setFirst) + { + if (_virtual) + { + if (_numItems == 0) + return; + + CheckVirtualList(); + + if (index >= _virtualItems.Count) + throw new Exception("Invalid child index: " + index + ">" + _virtualItems.Count); + + if (_loop) + index = Mathf.FloorToInt((float)_firstIndex / _numItems) * _numItems + index; + + Rect rect; + ItemInfo ii = _virtualItems[index]; + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + float pos = 0; + for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) + pos += _virtualItems[i].size.y + _lineGap; + rect = new Rect(0, pos, _itemSize.x, ii.size.y); + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + float pos = 0; + for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) + pos += _virtualItems[i].size.x + _columnGap; + rect = new Rect(pos, 0, ii.size.x, _itemSize.y); + } + else + { + int page = index / (_curLineItemCount * _curLineItemCount2); + rect = new Rect(page * viewWidth + (index % _curLineItemCount) * (ii.size.x + _columnGap), + (index / _curLineItemCount) % _curLineItemCount2 * (ii.size.y + _lineGap), + ii.size.x, ii.size.y); + } + + setFirst = true;//因为在可变item大小的情况下,只有设置在最顶端,位置才不会因为高度变化而改变,所以只能支持setFirst=true + // [Y 修改] + if (this.scrollPane != null) + { + SetAnimTweenTime(scrollPane, ani); + scrollPane.ScrollToView(rect, ani, setFirst); + } + else if (parent != null && parent.scrollPane != null) + { + SetAnimTweenTime(parent.scrollPane, ani); + parent.scrollPane.ScrollToView(this.TransformRect(rect, parent), ani, setFirst); + } + } + else + { + // [Y 修改] + GObject obj = GetChildAt(index); + if (this.scrollPane != null) + { + SetAnimTweenTime(scrollPane, ani); + scrollPane.ScrollToView(obj, ani, setFirst); + } + else if (parent != null && parent.scrollPane != null) + { + SetAnimTweenTime(parent.scrollPane, ani); + parent.scrollPane.ScrollToView(obj, ani, setFirst); + } + } + } + + /// + /// 获取当前点击哪个item + /// + public GObject touchItem + { + get + { + //find out which item is under finger + //逐层往上知道查到点击了那个item + GObject obj = GRoot.inst.touchTarget; + GObject p = obj.parent; + while (p != null) + { + if (p == this) + return obj; + + obj = p; + p = p.parent; + } + + return null; + } + } + + /// + /// Get first child in view. + /// + /// + public override int GetFirstChildInView() + { + return ChildIndexToItemIndex(base.GetFirstChildInView()); + } + + public int ChildIndexToItemIndex(int index) + { + if (!_virtual) + return index; + + if (_layout == ListLayoutType.Pagination) + { + for (int i = _firstIndex; i < _realNumItems; i++) + { + if (_virtualItems[i].obj != null) + { + index--; + if (index < 0) + return i; + } + } + + return index; + } + else + { + index += _firstIndex; + if (_loop && _numItems > 0) + index = index % _numItems; + + return index; + } + } + + public int ItemIndexToChildIndex(int index) + { + if (!_virtual) + return index; + + if (_layout == ListLayoutType.Pagination) + { + return GetChildIndex(_virtualItems[index].obj); + } + else + { + if (_loop && _numItems > 0) + { + int j = _firstIndex % _numItems; + if (index >= j) + index = index - j; + else + index = _numItems - j + index; + } + else + index -= _firstIndex; + + return index; + } + } + + + /// + /// Set the list to be virtual list. + /// 设置列表为虚拟列表模式。在虚拟列表模式下,列表不会为每一条列表数据创建一个实体对象,而是根据视口大小创建最小量的显示对象,然后通过itemRenderer指定的回调函数设置列表数据。 + /// 在虚拟模式下,你不能通过AddChild、RemoveChild等方式管理列表,只能通过设置numItems设置列表数据的长度。 + /// 如果要刷新列表,可以通过重新设置numItems,或者调用RefreshVirtualList完成。 + /// ‘单行’或者‘单列’的列表布局可支持不等高的列表项目。 + /// 除了‘页面’的列表布局,其他布局均支持使用不同资源构建列表项目,你可以在itemProvider里返回。如果不提供,默认使用defaultItem。 + /// + public void SetVirtual() + { + SetVirtual(false); + } + + public bool isVirtual + { + get { return _virtual; } + } + + /// + /// Set the list to be virtual list, and has loop behavior. + /// + public void SetVirtualAndLoop() + { + SetVirtual(true); + } + + void SetVirtual(bool loop) + { + if (!_virtual) + { + if (this.scrollPane == null) + Debug.LogError("FairyGUI: Virtual list must be scrollable!"); + + if (loop) + { + if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.FlowVertical) + Debug.LogError("FairyGUI: Loop list is not supported for FlowHorizontal or FlowVertical layout!"); + + this.scrollPane.bouncebackEffect = false; + } + + _virtual = true; + _loop = loop; + _virtualItems = new List(); + RemoveChildrenToPool(); + + if (_itemSize.x == 0 || _itemSize.y == 0) + { + GObject obj = GetFromPool(null); + if (obj == null) + { + Debug.LogError("FairyGUI: Virtual List must have a default list item resource."); + _itemSize = new Vector2(100, 100); + } + else + { + _itemSize = obj.size; + _itemSize.x = Mathf.CeilToInt(_itemSize.x); + _itemSize.y = Mathf.CeilToInt(_itemSize.y); + ReturnToPool(obj); + } + } + + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + this.scrollPane.scrollStep = _itemSize.y; + if (_loop) + this.scrollPane._loop = 2; + } + else + { + this.scrollPane.scrollStep = _itemSize.x; + if (_loop) + this.scrollPane._loop = 1; + } + + this.scrollPane.onScroll.AddCapture(__scrolled); + SetVirtualListChangedFlag(true); + } + } + + + /// + /// [Y 修改] + /// 累积更新列表的次数 + /// + public int amassUpdateListNum = 0; + /// + /// Set the list item count. + /// If the list is not virtual, specified number of items will be created. + /// If the list is virtual, only items in view will be created. + /// + public int numItems + { + get + { + if (_virtual) + return _numItems; + else + return _children.Count; + } + set + { + if (_virtual) + { + if (itemRenderer == null) + throw new Exception("FairyGUI: Set itemRenderer first!"); + + _numItems = value; + if (_loop) + _realNumItems = _numItems * 6;//设置6倍数量,用于循环滚动 + else + _realNumItems = _numItems; + + //_virtualItems的设计是只增不减的 + int oldCount = _virtualItems.Count; + if (_realNumItems > oldCount) + { + for (int i = oldCount; i < _realNumItems; i++) + { + ItemInfo ii = new ItemInfo(); + ii.size = _itemSize; + + _virtualItems.Add(ii); + } + } + else + { + for (int i = _realNumItems; i < oldCount; i++) + _virtualItems[i].selected = false; + } + + if (_virtualListChanged != 0) + Timers.inst.Remove(this.RefreshVirtualList); + //立即刷新 + this.RefreshVirtualList(null); + } + else + { + // [Y 修改] + amassUpdateListNum++; + int currAmassUpdateListNum = amassUpdateListNum; + + int cnt = _children.Count; + if (value > cnt) + { + for (int i = cnt; i < value; i++) + { + if (itemProvider == null) + AddItemFromPool(); + else + AddItemFromPool(itemProvider(i)); + } + } + else + { + RemoveChildrenToPool(value, cnt); + } + + if (itemRenderer != null) + { + for (int i = 0; i < value; i++) + { + // [Y 修改] 只更新最近一次的列表刷新 + // [Y 修改] 提前判断下标安全 + if (currAmassUpdateListNum == amassUpdateListNum) + { + if (i >= 0 && i < numChildren) + { + itemRenderer(i, GetChildAt(i)); + } + else + { + Debug.LogError("[FGUI-GList]Error Update GList invalid index: " + i); + } + } + } + } + } + } + } + + public void RefreshVirtualList() + { + if (!_virtual) + throw new Exception("FairyGUI: not virtual list"); + + SetVirtualListChangedFlag(false); + } + + void CheckVirtualList() + { + if (_virtualListChanged != 0) + { + this.RefreshVirtualList(null); + Timers.inst.Remove(this.RefreshVirtualList); + } + } + + void SetVirtualListChangedFlag(bool layoutChanged) + { + if (layoutChanged) + _virtualListChanged = 2; + else if (_virtualListChanged == 0) + _virtualListChanged = 1; + + Timers.inst.CallLater(RefreshVirtualList); + } + + void RefreshVirtualList(object param) + { + bool layoutChanged = _virtualListChanged == 2; + _virtualListChanged = 0; + _miscFlags |= 1; + + if (layoutChanged) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.SingleRow) + _curLineItemCount = 1; + else if (_layout == ListLayoutType.FlowHorizontal) + { + if (_columnCount > 0) + _curLineItemCount = _columnCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_lineCount > 0) + _curLineItemCount = _lineCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + } + else //pagination + { + if (_columnCount > 0) + _curLineItemCount = _columnCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + + if (_lineCount > 0) + _curLineItemCount2 = _lineCount; + else + { + _curLineItemCount2 = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); + if (_curLineItemCount2 <= 0) + _curLineItemCount2 = 1; + } + } + } + + float ch = 0, cw = 0; + if (_realNumItems > 0) + { + int len = Mathf.CeilToInt((float)_realNumItems / _curLineItemCount) * _curLineItemCount; + int len2 = Math.Min(_curLineItemCount, _realNumItems); + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + for (int i = 0; i < len; i += _curLineItemCount) + ch += _virtualItems[i].size.y + _lineGap; + if (ch > 0) + ch -= _lineGap; + + if (_autoResizeItem) + cw = scrollPane.viewWidth; + else + { + for (int i = 0; i < len2; i++) + cw += _virtualItems[i].size.x + _columnGap; + if (cw > 0) + cw -= _columnGap; + } + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + for (int i = 0; i < len; i += _curLineItemCount) + cw += _virtualItems[i].size.x + _columnGap; + if (cw > 0) + cw -= _columnGap; + + if (_autoResizeItem) + ch = this.scrollPane.viewHeight; + else + { + for (int i = 0; i < len2; i++) + ch += _virtualItems[i].size.y + _lineGap; + if (ch > 0) + ch -= _lineGap; + } + } + else + { + int pageCount = Mathf.CeilToInt((float)len / (_curLineItemCount * _curLineItemCount2)); + cw = pageCount * viewWidth; + ch = viewHeight; + } + } + + HandleAlign(cw, ch); + this.scrollPane.SetContentSize(cw, ch); + + _miscFlags &= 0xFE; + + HandleScroll(true); + } + + void __scrolled(EventContext context) + { + HandleScroll(false); + } + + int GetIndexOnPos1(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + if (numChildren > 0 && !forceUpdate) + { + float pos2 = this.GetChildAt(0).y; + if (pos2 + (_lineGap > 0 ? 0 : -_lineGap) > pos) + { + for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) + { + pos2 -= (_virtualItems[i].size.y + _lineGap); + if (pos2 <= pos) + { + pos = pos2; + return i; + } + } + + pos = 0; + return 0; + } + else + { + float testGap = _lineGap > 0 ? _lineGap : 0; + for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.y; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _lineGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + else + { + float pos2 = 0; + float testGap = _lineGap > 0 ? _lineGap : 0; + for (int i = 0; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.y; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _lineGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + + int GetIndexOnPos2(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + if (numChildren > 0 && !forceUpdate) + { + float pos2 = this.GetChildAt(0).x; + if (pos2 + (_columnGap > 0 ? 0 : -_columnGap) > pos) + { + for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) + { + pos2 -= (_virtualItems[i].size.x + _columnGap); + if (pos2 <= pos) + { + pos = pos2; + return i; + } + } + + pos = 0; + return 0; + } + else + { + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + else + { + float pos2 = 0; + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = 0; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + + int GetIndexOnPos3(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + float viewWidth = this.viewWidth; + int page = Mathf.FloorToInt(pos / viewWidth); + int startIndex = page * (_curLineItemCount * _curLineItemCount2); + float pos2 = page * viewWidth; + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = 0; i < _curLineItemCount; i++) + { + float pos3 = pos2 + _virtualItems[startIndex + i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return startIndex + i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return startIndex + _curLineItemCount - 1; + } + + void HandleScroll(bool forceUpdate) + { + if ((_miscFlags & 1) != 0) + return; + + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + int enterCounter = 0; + while (HandleScroll1(forceUpdate)) + { + //可能会因为ITEM资源改变导致ITEM大小发生改变,所有出现最后一页填不满的情况,这时要反复尝试填满。 + enterCounter++; + forceUpdate = false; + if (enterCounter > 20) + { + Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); + break; + } + } + + HandleArchOrder1(); + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + int enterCounter = 0; + while (HandleScroll2(forceUpdate)) + { + enterCounter++; + forceUpdate = false; + if (enterCounter > 20) + { + Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); + break; + } + } + + HandleArchOrder2(); + } + else + { + HandleScroll3(forceUpdate); + } + + _boundsChanged = false; + } + + bool HandleScroll1(bool forceUpdate) + { + float pos = scrollPane.scrollingPosY; + float max = pos + scrollPane.viewHeight; + bool end = max == scrollPane.contentHeight;//这个标志表示当前需要滚动到最末,无论内容变化大小 + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos1(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return false; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + int curIndex = newFirstIndex; + bool forward = oldFirstIndex > newFirstIndex; + int childCount = this.numChildren; + int lastIndex = oldFirstIndex + childCount - 1; + int reuseIndex = forward ? lastIndex : oldFirstIndex; + float curX = 0, curY = pos; + bool needRender; + float deltaSize = 0; + float firstItemDeltaSize = 0; + string url = _defaultItem; + int partSize = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); + + itemInfoVer++; + while (curIndex < _realNumItems && (end || curY < max)) + { + ItemInfo ii = _virtualItems[curIndex]; + + if (ii.obj == null || forceUpdate) + { + if (itemProvider != null) + { + url = itemProvider(curIndex % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + if (ii.obj != null && ii.obj.resourceURL != url) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + if (ii.obj == null) + { + //搜索最适合的重用item,保证每次刷新需要新建或者重新render的item最少 + if (forward) + { + for (int j = reuseIndex; j >= oldFirstIndex; j--) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex--; + break; + } + } + } + else + { + for (int j = reuseIndex; j <= lastIndex; j++) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex++; + break; + } + } + } + + if (ii.obj != null) + { + SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); + } + else + { + ii.obj = _pool.GetObject(url); + if (forward) + this.AddChildAt(ii.obj, curIndex - newFirstIndex); + else + this.AddChild(ii.obj); + } + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + needRender = forceUpdate; + + if (needRender) + { + if (_autoResizeItem && (_layout == ListLayoutType.SingleColumn || _columnCount > 0)) + ii.obj.SetSize(partSize, ii.obj.height, true); + + itemRenderer(curIndex % _numItems, ii.obj); + if (curIndex % _curLineItemCount == 0) + { + deltaSize += Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; + if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) + { + //当内容向下滚动时,如果新出现的项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 + firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; + } + } + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + + ii.updateFlag = itemInfoVer; + ii.obj.SetXY(curX, curY); + if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 + max += ii.size.y; + + curX += ii.size.x + _columnGap; + + if (curIndex % _curLineItemCount == _curLineItemCount - 1) + { + curX = 0; + curY += ii.size.y + _lineGap; + } + curIndex++; + } + + for (int i = 0; i < childCount; i++) + { + ItemInfo ii = _virtualItems[oldFirstIndex + i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + childCount = _children.Count; + for (int i = 0; i < childCount; i++) + { + GObject obj = _virtualItems[newFirstIndex + i].obj; + if (_children[i] != obj) + SetChildIndex(obj, i); + } + + if (deltaSize != 0 || firstItemDeltaSize != 0) + this.scrollPane.ChangeContentSizeOnScrolling(0, deltaSize, 0, firstItemDeltaSize); + + if (curIndex > 0 && this.numChildren > 0 && this.container.y <= 0 && GetChildAt(0).y > -this.container.y)//最后一页没填满! + return true; + else + return false; + } + + bool HandleScroll2(bool forceUpdate) + { + float pos = scrollPane.scrollingPosX; + float max = pos + scrollPane.viewWidth; + bool end = pos == scrollPane.contentWidth;//这个标志表示当前需要滚动到最末,无论内容变化大小 + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos2(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return false; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + int curIndex = newFirstIndex; + bool forward = oldFirstIndex > newFirstIndex; + int childCount = this.numChildren; + int lastIndex = oldFirstIndex + childCount - 1; + int reuseIndex = forward ? lastIndex : oldFirstIndex; + float curX = pos, curY = 0; + bool needRender; + float deltaSize = 0; + float firstItemDeltaSize = 0; + string url = _defaultItem; + int partSize = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount - 1)) / _curLineItemCount); + + itemInfoVer++; + while (curIndex < _realNumItems && (end || curX < max)) + { + ItemInfo ii = _virtualItems[curIndex]; + + if (ii.obj == null || forceUpdate) + { + if (itemProvider != null) + { + url = itemProvider(curIndex % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + if (ii.obj != null && ii.obj.resourceURL != url) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + if (ii.obj == null) + { + if (forward) + { + for (int j = reuseIndex; j >= oldFirstIndex; j--) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex--; + break; + } + } + } + else + { + for (int j = reuseIndex; j <= lastIndex; j++) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex++; + break; + } + } + } + + if (ii.obj != null) + { + SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); + } + else + { + ii.obj = _pool.GetObject(url); + if (forward) + this.AddChildAt(ii.obj, curIndex - newFirstIndex); + else + this.AddChild(ii.obj); + } + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + needRender = forceUpdate; + + if (needRender) + { + if (_autoResizeItem && (_layout == ListLayoutType.SingleRow || _lineCount > 0)) + ii.obj.SetSize(ii.obj.width, partSize, true); + + itemRenderer(curIndex % _numItems, ii.obj); + if (curIndex % _curLineItemCount == 0) + { + deltaSize += Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; + if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) + { + //当内容向下滚动时,如果新出现的一个项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 + firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; + } + } + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + + ii.updateFlag = itemInfoVer; + ii.obj.SetXY(curX, curY); + if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 + max += ii.size.x; + + curY += ii.size.y + _lineGap; + + if (curIndex % _curLineItemCount == _curLineItemCount - 1) + { + curY = 0; + curX += ii.size.x + _columnGap; + } + curIndex++; + } + + for (int i = 0; i < childCount; i++) + { + ItemInfo ii = _virtualItems[oldFirstIndex + i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + childCount = _children.Count; + for (int i = 0; i < childCount; i++) + { + GObject obj = _virtualItems[newFirstIndex + i].obj; + if (_children[i] != obj) + SetChildIndex(obj, i); + } + + if (deltaSize != 0 || firstItemDeltaSize != 0) + this.scrollPane.ChangeContentSizeOnScrolling(deltaSize, 0, firstItemDeltaSize, 0); + + if (curIndex > 0 && this.numChildren > 0 && this.container.x <= 0 && GetChildAt(0).x > -this.container.x)//最后一页没填满! + return true; + else + return false; + } + + void HandleScroll3(bool forceUpdate) + { + float pos = scrollPane.scrollingPosX; + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos3(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + + //分页模式不支持不等高,所以渲染满一页就好了 + + int reuseIndex = oldFirstIndex; + int virtualItemCount = _virtualItems.Count; + int pageSize = _curLineItemCount * _curLineItemCount2; + int startCol = newFirstIndex % _curLineItemCount; + float viewWidth = this.viewWidth; + int page = (int)(newFirstIndex / pageSize); + int startIndex = page * pageSize; + int lastIndex = startIndex + pageSize * 2; //测试两页 + bool needRender; + string url = _defaultItem; + int partWidth = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); + int partHeight = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount2 - 1)) / _curLineItemCount2); + itemInfoVer++; + + //先标记这次要用到的项目 + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + int col = i % _curLineItemCount; + if (i - startIndex < pageSize) + { + if (col < startCol) + continue; + } + else + { + if (col > startCol) + continue; + } + + ItemInfo ii = _virtualItems[i]; + ii.updateFlag = itemInfoVer; + } + + GObject lastObj = null; + int insertIndex = 0; + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag != itemInfoVer) + continue; + + if (ii.obj == null) + { + //寻找看有没有可重用的 + while (reuseIndex < virtualItemCount) + { + ItemInfo ii2 = _virtualItems[reuseIndex]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + break; + } + reuseIndex++; + } + + if (insertIndex == -1) + insertIndex = GetChildIndex(lastObj) + 1; + + if (ii.obj == null) + { + if (itemProvider != null) + { + url = itemProvider(i % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + ii.obj = _pool.GetObject(url); + this.AddChildAt(ii.obj, insertIndex); + } + else + { + insertIndex = SetChildIndexBefore(ii.obj, insertIndex); + } + insertIndex++; + + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + { + needRender = forceUpdate; + insertIndex = -1; + lastObj = ii.obj; + } + + if (needRender) + { + if (_autoResizeItem) + { + if (_curLineItemCount == _columnCount && _curLineItemCount2 == _lineCount) + ii.obj.SetSize(partWidth, partHeight, true); + else if (_curLineItemCount == _columnCount) + ii.obj.SetSize(partWidth, ii.obj.height, true); + else if (_curLineItemCount2 == _lineCount) + ii.obj.SetSize(ii.obj.width, partHeight, true); + } + + itemRenderer(i % _numItems, ii.obj); + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + } + + //排列item + float borderX = (startIndex / pageSize) * viewWidth; + float xx = borderX; + float yy = 0; + float lineHeight = 0; + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag == itemInfoVer) + ii.obj.SetXY(xx, yy); + + if (ii.size.y > lineHeight) + lineHeight = ii.size.y; + if (i % _curLineItemCount == _curLineItemCount - 1) + { + xx = borderX; + yy += lineHeight + _lineGap; + lineHeight = 0; + + if (i == startIndex + pageSize - 1) + { + borderX += viewWidth; + xx = borderX; + yy = 0; + } + } + else + xx += ii.size.x + _columnGap; + } + + //释放未使用的 + for (int i = reuseIndex; i < virtualItemCount; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + } + + void HandleArchOrder1() + { + if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) + { + float mid = this.scrollPane.posY + this.viewHeight / 2; + float minDist = int.MaxValue, dist; + int apexIndex = 0; + int cnt = this.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + { + dist = Mathf.Abs(mid - obj.y - obj.height / 2); + if (dist < minDist) + { + minDist = dist; + apexIndex = i; + } + } + } + this.apexIndex = apexIndex; + } + } + + void HandleArchOrder2() + { + if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) + { + float mid = this.scrollPane.posX + this.viewWidth / 2; + float minDist = int.MaxValue, dist; + int apexIndex = 0; + int cnt = this.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + { + dist = Mathf.Abs(mid - obj.x - obj.width / 2); + if (dist < minDist) + { + minDist = dist; + apexIndex = i; + } + } + } + this.apexIndex = apexIndex; + } + } + + override public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) + { + if (_virtual) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + float saved = yValue; + int index = GetIndexOnPos1(ref yValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.y; + if (ShouldSnapToNext(yDir, saved - yValue, size)) + yValue += size + _lineGap; + } + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + float saved = xValue; + int index = GetIndexOnPos2(ref xValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.x; + if (ShouldSnapToNext(xDir, saved - xValue, size)) + xValue += size + _columnGap; + } + } + else + { + float saved = xValue; + int index = GetIndexOnPos3(ref xValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.x; + if (ShouldSnapToNext(xDir, saved - xValue, size)) + xValue += size + _columnGap; + } + } + } + else + base.GetSnappingPositionWithDir(ref xValue, ref yValue, xDir, yDir); + } + + private void HandleAlign(float contentWidth, float contentHeight) + { + Vector2 newOffset = Vector2.zero; + + if (contentHeight < viewHeight) + { + if (_verticalAlign == VertAlignType.Middle) + newOffset.y = (int)((viewHeight - contentHeight) / 2); + else if (_verticalAlign == VertAlignType.Bottom) + newOffset.y = viewHeight - contentHeight; + } + + if (contentWidth < this.viewWidth) + { + if (_align == AlignType.Center) + newOffset.x = (int)((viewWidth - contentWidth) / 2); + else if (_align == AlignType.Right) + newOffset.x = viewWidth - contentWidth; + } + + if (newOffset != _alignOffset) + { + _alignOffset = newOffset; + if (scrollPane != null) + scrollPane.AdjustMaskContainer(); + else + container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); + } + } + + override protected void UpdateBounds() + { + if (_virtual) + return; + + int cnt = _children.Count; + int i; + int j = 0; + GObject child; + float curX = 0; + float curY = 0; + float cw, ch; + float maxWidth = 0; + float maxHeight = 0; + float viewWidth = this.viewWidth; + float viewHeight = this.viewHeight; + + if (_layout == ListLayoutType.SingleColumn) + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curY != 0) + curY += _lineGap; + child.y = curY; + if (_autoResizeItem) + child.SetSize(viewWidth, child.height, true); + curY += Mathf.CeilToInt(child.height); + if (child.width > maxWidth) + maxWidth = child.width; + } + + ch = curY; + if (ch <= viewHeight && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.vtScrollBar != null) + { + viewWidth += scrollPane.vtScrollBar.width; + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetSize(viewWidth, child.height, true); + } + } + cw = Mathf.CeilToInt(maxWidth); + } + else if (_layout == ListLayoutType.SingleRow) + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + child.x = curX; + if (_autoResizeItem) + child.SetSize(child.width, viewHeight, true); + curX += Mathf.CeilToInt(child.width); + if (child.height > maxHeight) + maxHeight = child.height; + } + + cw = curX; + if (cw <= viewWidth && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.hzScrollBar != null) + { + viewHeight += scrollPane.hzScrollBar.height; + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetSize(child.width, viewHeight, true); + } + } + ch = Mathf.CeilToInt(maxHeight); + } + else if (_layout == ListLayoutType.FlowHorizontal) + { + if (_autoResizeItem && _columnCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + lineSize += child.sourceWidth; + j++; + if (j == _columnCount || i == cnt - 1) + { + remainSize = viewWidth - (j - 1) * _columnGap; + remainPercent = 1; + curX = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(curX, curY); + float perc = child.sourceWidth / lineSize; + child.SetSize(Mathf.Round(perc / remainPercent * remainSize), child.height, true); + remainSize -= child.width; + remainPercent -= perc; + curX += child.width + _columnGap; + + if (child.height > maxHeight) + maxHeight = child.height; + } + //new line + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + } + } + ch = curY + Mathf.CeilToInt(maxHeight); + cw = viewWidth; + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + + if (_columnCount != 0 && j >= _columnCount + || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) + { + //new line + curX = 0; + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + } + child.SetXY(curX, curY); + curX += Mathf.CeilToInt(child.width); + if (curX > maxWidth) + maxWidth = curX; + if (child.height > maxHeight) + maxHeight = child.height; + j++; + } + ch = curY + Mathf.CeilToInt(maxHeight); + cw = Mathf.CeilToInt(maxWidth); + } + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_autoResizeItem && _lineCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + lineSize += child.sourceHeight; + j++; + if (j == _lineCount || i == cnt - 1) + { + remainSize = viewHeight - (j - 1) * _lineGap; + remainPercent = 1; + curY = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(curX, curY); + float perc = child.sourceHeight / lineSize; + child.SetSize(child.width, Mathf.Round(perc / remainPercent * remainSize), true); + remainSize -= child.height; + remainPercent -= perc; + curY += child.height + _lineGap; + + if (child.width > maxWidth) + maxWidth = child.width; + } + //new line + curX += Mathf.CeilToInt(maxWidth) + _columnGap; + maxWidth = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + } + } + cw = curX + Mathf.CeilToInt(maxWidth); + ch = viewHeight; + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curY != 0) + curY += _lineGap; + + if (_lineCount != 0 && j >= _lineCount + || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0) + { + curY = 0; + curX += Mathf.CeilToInt(maxWidth) + _columnGap; + maxWidth = 0; + j = 0; + } + child.SetXY(curX, curY); + curY += child.height; + if (curY > maxHeight) + maxHeight = curY; + if (child.width > maxWidth) + maxWidth = child.width; + j++; + } + cw = curX + Mathf.CeilToInt(maxWidth); + ch = Mathf.CeilToInt(maxHeight); + } + } + else //pagination + { + int page = 0; + int k = 0; + float eachHeight = 0; + if (_autoResizeItem && _lineCount > 0) + eachHeight = Mathf.Floor((viewHeight - (_lineCount - 1) * _lineGap) / _lineCount); + + if (_autoResizeItem && _columnCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (j == 0 && (_lineCount != 0 && k >= _lineCount + || _lineCount == 0 && curY + (_lineCount > 0 ? eachHeight : child.height) > viewHeight)) + { + //new page + page++; + curY = 0; + k = 0; + } + + lineSize += child.sourceWidth; + j++; + if (j == _columnCount || i == cnt - 1) + { + remainSize = viewWidth - (j - 1) * _columnGap; + remainPercent = 1; + curX = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(page * viewWidth + curX, curY); + float perc = child.sourceWidth / lineSize; + child.SetSize(Mathf.Round(perc / remainPercent * remainSize), _lineCount > 0 ? eachHeight : child.height, true); + remainSize -= child.width; + remainPercent -= perc; + curX += child.width + _columnGap; + + if (child.height > maxHeight) + maxHeight = child.height; + } + //new line + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + + k++; + } + } + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + + if (_autoResizeItem && _lineCount > 0) + child.SetSize(child.width, eachHeight, true); + + if (_columnCount != 0 && j >= _columnCount + || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) + { + curX = 0; + curY += maxHeight + _lineGap; + maxHeight = 0; + j = 0; + k++; + + if (_lineCount != 0 && k >= _lineCount + || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0)//new page + { + page++; + curY = 0; + k = 0; + } + } + child.SetXY(page * viewWidth + curX, curY); + curX += Mathf.CeilToInt(child.width); + if (curX > maxWidth) + maxWidth = curX; + if (child.height > maxHeight) + maxHeight = child.height; + j++; + } + } + ch = page > 0 ? viewHeight : (curY + Mathf.CeilToInt(maxHeight)); + cw = (page + 1) * viewWidth; + } + + HandleAlign(cw, ch); + SetBounds(0, 0, cw, ch); + + InvalidateBatchingState(true); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _layout = (ListLayoutType)buffer.ReadByte(); + selectionMode = (ListSelectionMode)buffer.ReadByte(); + _align = (AlignType)buffer.ReadByte(); + _verticalAlign = (VertAlignType)buffer.ReadByte(); + _lineGap = buffer.ReadShort(); + _columnGap = buffer.ReadShort(); + _lineCount = buffer.ReadShort(); + _columnCount = buffer.ReadShort(); + _autoResizeItem = buffer.ReadBool(); + _childrenRenderOrder = (ChildrenRenderOrder)buffer.ReadByte(); + _apexIndex = buffer.ReadShort(); + + if (buffer.ReadBool()) + { + _margin.top = buffer.ReadInt(); + _margin.bottom = buffer.ReadInt(); + _margin.left = buffer.ReadInt(); + _margin.right = buffer.ReadInt(); + } + + OverflowType overflow = (OverflowType)buffer.ReadByte(); + if (overflow == OverflowType.Scroll) + { + int savedPos = buffer.position; + buffer.Seek(beginPos, 7); + SetupScroll(buffer); + buffer.position = savedPos; + } + else + SetupOverflow(overflow); + + if (buffer.ReadBool()) + { + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + this.clipSoftness = new Vector2(i1, i2); + } + + if (buffer.version >= 2) + { + scrollItemToViewOnClick = buffer.ReadBool(); + foldInvisibleItems = buffer.ReadBool(); + } + + buffer.Seek(beginPos, 8); + + _defaultItem = buffer.ReadS(); + ReadItems(buffer); + } + + virtual protected void ReadItems(ByteBuffer buffer) + { + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + string str = buffer.ReadS(); + if (str == null) + { + str = _defaultItem; + if (string.IsNullOrEmpty(str)) + { + buffer.position = nextPos; + continue; + } + } + + GObject obj = GetFromPool(str); + if (obj != null) + { + AddChild(obj); + SetupItem(buffer, obj); + } + + buffer.position = nextPos; + } + } + + protected void SetupItem(ByteBuffer buffer, GObject obj) + { + string str; + str = buffer.ReadS(); + if (str != null) + obj.text = str; + str = buffer.ReadS(); + if (str != null && (obj is GButton)) + (obj as GButton).selectedTitle = str; + str = buffer.ReadS(); + if (str != null) + obj.icon = str; + str = buffer.ReadS(); + if (str != null && (obj is GButton)) + (obj as GButton).selectedIcon = str; + str = buffer.ReadS(); + if (str != null) + obj.name = str; + + if (obj is GComponent) + { + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + Controller cc = ((GComponent)obj).GetController(buffer.ReadS()); + str = buffer.ReadS(); + if (cc != null) + cc.selectedPageId = str; + } + + if (buffer.version >= 2) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + string value = buffer.ReadS(); + GObject obj2 = ((GComponent)obj).GetChildByPath(target); + if (obj2 != null) + { + if (propertyId == 0) + obj2.text = value; + else if (propertyId == 1) + obj2.icon = value; + } + } + } + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 6); + + int i = buffer.ReadShort(); + if (i != -1) + _selectionController = parent.GetControllerAt(i); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs.meta new file mode 100644 index 0000000..d76672e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5eda689519c51b42955139d2c6caba4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs new file mode 100644 index 0000000..7117558 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs @@ -0,0 +1,701 @@ +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GLoader class + /// + public class GLoader : GObject, IAnimationGear, IColorGear + { + /// + /// Display an error sign if the loader fails to load the content. + /// UIConfig.loaderErrorSign muse be set. + /// + public bool showErrorSign; + + string _url; + AlignType _align; + VertAlignType _verticalAlign; + bool _autoSize; + FillType _fill; + bool _shrinkOnly; + bool _updatingLayout; + PackageItem _contentItem; + Action _reloadDelegate; + + MovieClip _content; + GObject _errorSign; + GComponent _content2; + +#if FAIRYGUI_PUERTS + public Action __loadExternal; + public Action __freeExternal; +#endif + + public GLoader() + { + _url = string.Empty; + _align = AlignType.Left; + _verticalAlign = VertAlignType.Top; + showErrorSign = true; + _reloadDelegate = OnExternalReload; + } + + override protected void CreateDisplayObject() + { + displayObject = new Container("GLoader"); + displayObject.gOwner = this; + _content = new MovieClip(); + ((Container)displayObject).AddChild(_content); + ((Container)displayObject).opaque = true; + } + + override public void Dispose() + { + if (_disposed) return; + + if (_content.texture != null) + { + if (_contentItem == null) + { + _content.texture.onSizeChanged -= _reloadDelegate; + try + { + FreeExternal(_content.texture); + } + catch (Exception err) + { + Debug.LogWarning(err); + } + } + } + if (_errorSign != null) + _errorSign.Dispose(); + if (_content2 != null) + _content2.Dispose(); + _content.Dispose(); + + base.Dispose(); + } + + /// + /// + /// + public string url + { + get { return _url; } + set + { + if (_url == value) + return; + + ClearContent(); + _url = value; + LoadContent(); + UpdateGear(7); + } + } + + override public string icon + { + get { return _url; } + set { this.url = value; } + } + + /// + /// + /// + public AlignType align + { + get { return _align; } + set + { + if (_align != value) + { + _align = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public FillType fill + { + get { return _fill; } + set + { + if (_fill != value) + { + _fill = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool shrinkOnly + { + get { return _shrinkOnly; } + set + { + if (_shrinkOnly != value) + { + _shrinkOnly = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool autoSize + { + get { return _autoSize; } + set + { + if (_autoSize != value) + { + _autoSize = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool playing + { + get { return _content.playing; } + set + { + _content.playing = value; + UpdateGear(5); + } + } + + /// + /// + /// + public int frame + { + get { return _content.frame; } + set + { + _content.frame = value; + UpdateGear(5); + } + } + + /// + /// + /// + public float timeScale + { + get { return _content.timeScale; } + set { _content.timeScale = value; } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _content.ignoreEngineTimeScale; } + set { _content.ignoreEngineTimeScale = value; } + } + + /// + /// + /// + /// + public void Advance(float time) + { + _content.Advance(time); + } + + /// + /// + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + /// + /// + /// + public Color color + { + get { return _content.color; } + set + { + if (_content.color != value) + { + _content.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public FillMethod fillMethod + { + get { return _content.fillMethod; } + set { _content.fillMethod = value; } + } + + /// + /// + /// + public int fillOrigin + { + get { return _content.fillOrigin; } + set { _content.fillOrigin = value; } + } + + /// + /// + /// + public bool fillClockwise + { + get { return _content.fillClockwise; } + set { _content.fillClockwise = value; } + } + + /// + /// + /// + public float fillAmount + { + get { return _content.fillAmount; } + set { _content.fillAmount = value; } + } + + /// + /// + /// + public Image image + { + get { return _content; } + } + + /// + /// + /// + public MovieClip movieClip + { + get { return _content; } + } + + /// + /// + /// + public GComponent component + { + get { return _content2; } + } + + /// + /// + /// + public NTexture texture + { + get + { + return _content.texture; + } + + set + { + this.url = null; + + _content.texture = value; + if (value != null) + { + sourceWidth = value.width; + sourceHeight = value.height; + } + else + { + sourceWidth = sourceHeight = 0; + } + + UpdateLayout(); + } + } + + override public IFilter filter + { + get { return _content.filter; } + set { _content.filter = value; } + } + + override public BlendMode blendMode + { + get { return _content.blendMode; } + set { _content.blendMode = value; } + } + + /// + /// + /// + protected void LoadContent() + { + ClearContent(); + + if (string.IsNullOrEmpty(_url)) + return; + + if (_url.StartsWith(UIPackage.URL_PREFIX)) + LoadFromPackage(_url); + else + LoadExternal(); + } + + protected void LoadFromPackage(string itemURL) + { + _contentItem = UIPackage.GetItemByURL(itemURL); + + if (_contentItem != null) + { + _contentItem = _contentItem.getBranch(); + sourceWidth = _contentItem.width; + sourceHeight = _contentItem.height; + _contentItem = _contentItem.getHighResolution(); + _contentItem.Load(); + + if (_contentItem.type == PackageItemType.Image) + { + _content.texture = _contentItem.texture; + _content.textureScale = new Vector2(_contentItem.width / (float)sourceWidth, _contentItem.height / (float)sourceHeight); + _content.scale9Grid = _contentItem.scale9Grid; + _content.scaleByTile = _contentItem.scaleByTile; + _content.tileGridIndice = _contentItem.tileGridIndice; + + UpdateLayout(); + } + else if (_contentItem.type == PackageItemType.MovieClip) + { + _content.interval = _contentItem.interval; + _content.swing = _contentItem.swing; + _content.repeatDelay = _contentItem.repeatDelay; + _content.frames = _contentItem.frames; + + UpdateLayout(); + } + else if (_contentItem.type == PackageItemType.Component) + { + GObject obj = UIPackage.CreateObjectFromURL(itemURL); + if (obj == null) + SetErrorState(); + else if (!(obj is GComponent)) + { + obj.Dispose(); + SetErrorState(); + } + else + { + _content2 = (GComponent)obj; + ((Container)displayObject).AddChild(_content2.displayObject); + UpdateLayout(); + } + } + else + { + if (_autoSize) + this.SetSize(_contentItem.width, _contentItem.height); + + SetErrorState(); + + Debug.LogWarning("Unsupported type of GLoader: " + _contentItem.type); + } + } + else + SetErrorState(); + } + + virtual protected void LoadExternal() + { +#if FAIRYGUI_PUERTS + if (__loadExternal != null) { + __loadExternal(); + return; + } +#endif + Texture2D tex = (Texture2D)Resources.Load(_url, typeof(Texture2D)); + if (tex != null) + onExternalLoadSuccess(new NTexture(tex)); + else + onExternalLoadFailed(); + } + + virtual protected void FreeExternal(NTexture texture) + { +#if FAIRYGUI_PUERTS + if (__freeExternal != null) { + __freeExternal(texture); + return; + } +#endif + } + + public void onExternalLoadSuccess(NTexture texture) + { + _content.texture = texture; + sourceWidth = texture.width; + sourceHeight = texture.height; + _content.scale9Grid = null; + _content.scaleByTile = false; + texture.onSizeChanged += _reloadDelegate; + UpdateLayout(); + } + + public void onExternalLoadFailed() + { + SetErrorState(); + } + + void OnExternalReload(NTexture texture) + { + sourceWidth = texture.width; + sourceHeight = texture.height; + UpdateLayout(); + } + + private void SetErrorState() + { + if (!showErrorSign || !Application.isPlaying) + return; + + if (_errorSign == null) + { + if (UIConfig.loaderErrorSign != null) + _errorSign = UIPackage.CreateObjectFromURL(UIConfig.loaderErrorSign); + else + return; + } + + if (_errorSign != null) + { + _errorSign.SetSize(this.width, this.height); + ((Container)displayObject).AddChild(_errorSign.displayObject); + } + } + + protected void ClearErrorState() + { + if (_errorSign != null && _errorSign.displayObject.parent != null) + ((Container)displayObject).RemoveChild(_errorSign.displayObject); + } + + protected void UpdateLayout() + { + if (_content2 == null && _content.texture == null && _content.frames == null) + { + if (_autoSize) + { + _updatingLayout = true; + SetSize(50, 30); + _updatingLayout = false; + } + return; + } + + float contentWidth = sourceWidth; + float contentHeight = sourceHeight; + + if (_autoSize) + { + _updatingLayout = true; + if (contentWidth == 0) + contentWidth = 50; + if (contentHeight == 0) + contentHeight = 30; + SetSize(contentWidth, contentHeight); + + _updatingLayout = false; + + if (_width == contentWidth && _height == contentHeight) + { + if (_content2 != null) + { + _content2.SetXY(0, 0); + _content2.SetScale(1, 1); + } + else + { + _content.SetXY(0, 0); + _content.SetSize(contentWidth, contentHeight); + } + + InvalidateBatchingState(); + return; + } + //如果不相等,可能是由于大小限制造成的,要后续处理 + } + + float sx = 1, sy = 1; + if (_fill != FillType.None) + { + sx = this.width / sourceWidth; + sy = this.height / sourceHeight; + + if (sx != 1 || sy != 1) + { + if (_fill == FillType.ScaleMatchHeight) + sx = sy; + else if (_fill == FillType.ScaleMatchWidth) + sy = sx; + else if (_fill == FillType.Scale) + { + if (sx > sy) + sx = sy; + else + sy = sx; + } + else if (_fill == FillType.ScaleNoBorder) + { + if (sx > sy) + sy = sx; + else + sx = sy; + } + + if (_shrinkOnly) + { + if (sx > 1) + sx = 1; + if (sy > 1) + sy = 1; + } + + contentWidth = sourceWidth * sx; + contentHeight = sourceHeight * sy; + } + } + + if (_content2 != null) + _content2.SetScale(sx, sy); + else + _content.size = new Vector2(contentWidth, contentHeight); + + float nx; + float ny; + if (_align == AlignType.Center) + nx = (this.width - contentWidth) / 2; + else if (_align == AlignType.Right) + nx = this.width - contentWidth; + else + nx = 0; + if (_verticalAlign == VertAlignType.Middle) + ny = (this.height - contentHeight) / 2; + else if (_verticalAlign == VertAlignType.Bottom) + ny = this.height - contentHeight; + else + ny = 0; + if (_content2 != null) + _content2.SetXY(nx, ny); + else + _content.SetXY(nx, ny); + + InvalidateBatchingState(); + } + + private void ClearContent() + { + ClearErrorState(); + + if (_content.texture != null) + { + if (_contentItem == null) + { + _content.texture.onSizeChanged -= _reloadDelegate; + FreeExternal(_content.texture); + } + _content.texture = null; + } + _content.frames = null; + + if (_content2 != null) + { + _content2.Dispose(); + _content2 = null; + } + _contentItem = null; + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (!_updatingLayout) + UpdateLayout(); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _url = buffer.ReadS(); + _align = (AlignType)buffer.ReadByte(); + _verticalAlign = (VertAlignType)buffer.ReadByte(); + _fill = (FillType)buffer.ReadByte(); + _shrinkOnly = buffer.ReadBool(); + _autoSize = buffer.ReadBool(); + showErrorSign = buffer.ReadBool(); + _content.playing = buffer.ReadBool(); + _content.frame = buffer.ReadInt(); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.fillMethod = (FillMethod)buffer.ReadByte(); + if (_content.fillMethod != FillMethod.None) + { + _content.fillOrigin = buffer.ReadByte(); + _content.fillClockwise = buffer.ReadBool(); + _content.fillAmount = buffer.ReadFloat(); + } + + if (!string.IsNullOrEmpty(_url)) + LoadContent(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs.meta new file mode 100644 index 0000000..2ae5319 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 43ce591d02b49e8419c431df4af3da0b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs new file mode 100644 index 0000000..fcd5eb4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs @@ -0,0 +1,566 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public partial class GLoader3D : GObject, IAnimationGear, IColorGear + { + string _url; + AlignType _align; + VertAlignType _verticalAlign; + bool _autoSize; + FillType _fill; + bool _shrinkOnly; + string _animationName; + string _skinName; + bool _playing; + int _frame; + bool _loop; + bool _updatingLayout; + Color _color; + + protected PackageItem _contentItem; + protected GoWrapper _content; + + public GLoader3D() + { + _url = string.Empty; + _align = AlignType.Left; + _verticalAlign = VertAlignType.Top; + _playing = true; + _color = Color.white; + } + + override protected void CreateDisplayObject() + { + displayObject = new Container("GLoader3D"); + displayObject.gOwner = this; + + _content = new GoWrapper(); + _content.onUpdate += OnUpdateContent; + ((Container)displayObject).AddChild(_content); + ((Container)displayObject).opaque = true; + } + + override public void Dispose() + { + _content.Dispose(); + base.Dispose(); + } + + /// + /// + /// + public string url + { + get { return _url; } + set + { + if (_url == value) + return; + + ClearContent(); + _url = value; + LoadContent(); + UpdateGear(7); + } + } + + override public string icon + { + get { return _url; } + set { this.url = value; } + } + + /// + /// + /// + public AlignType align + { + get { return _align; } + set + { + if (_align != value) + { + _align = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public FillType fill + { + get { return _fill; } + set + { + if (_fill != value) + { + _fill = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool shrinkOnly + { + get { return _shrinkOnly; } + set + { + if (_shrinkOnly != value) + { + _shrinkOnly = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool autoSize + { + get { return _autoSize; } + set + { + if (_autoSize != value) + { + _autoSize = value; + UpdateLayout(); + } + } + } + + public bool playing + { + get { return _playing; } + set + { + if (_playing != value) + { + _playing = value; + OnChange("playing"); + UpdateGear(5); + } + } + } + + public int frame + { + get { return _frame; } + set + { + + if (_frame != value) + { + _frame = value; + OnChange("frame"); + UpdateGear(5); + } + } + } + + /// + /// Not implemented + /// + public float timeScale + { + get; + set; + } + + /// + /// Not implemented + /// + public bool ignoreEngineTimeScale + { + get; + set; + } + + /// + /// Not implemented + /// + /// + public void Advance(float time) + { + } + + /// + /// + /// + public bool loop + { + get { return _loop; } + set + { + if (_loop != value) + { + _loop = value; + OnChange("loop"); + } + } + } + + /// + /// + /// + /// + public string animationName + { + get { return _animationName; } + set + { + _animationName = value; + OnChange("animationName"); + UpdateGear(5); + } + } + + /// + /// + /// + /// + public string skinName + { + get { return _skinName; } + set + { + _skinName = value; + OnChange("skinName"); + UpdateGear(5); + } + } + + /// + /// + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + /// + /// + /// + public Color color + { + get { return _color; } + set + { + if (_color != value) + { + _color = value; + UpdateGear(4); + + OnChange("color"); + } + } + } + + /// + /// + /// + public GameObject wrapTarget + { + get { return _content.wrapTarget; } + } + + /// + /// + /// + /// + /// + /// + /// + public void SetWrapTarget(GameObject gameObject, bool cloneMaterial, int width, int height) + { + _content.SetWrapTarget(gameObject, cloneMaterial); + _content.SetSize(width, height); + sourceWidth = width; + sourceHeight = height; + + UpdateLayout(); + } + + override public IFilter filter + { + get { return _content.filter; } + set { _content.filter = value; } + } + + override public BlendMode blendMode + { + get { return _content.blendMode; } + set { _content.blendMode = value; } + } + + /// + /// + /// + protected void LoadContent() + { + ClearContent(); + + if (string.IsNullOrEmpty(_url)) + return; + + _contentItem = UIPackage.GetItemByURL(_url); + + if (_contentItem != null) + { + _contentItem = _contentItem.getBranch(); + _contentItem = _contentItem.getHighResolution(); + _contentItem.Load(); + + if (_contentItem.type == PackageItemType.Spine) + { +#if FAIRYGUI_SPINE + LoadSpine(); +#endif + } + else if (_contentItem.type == PackageItemType.DragoneBones) + { +#if FAIRYGUI_DRAGONBONES + LoadDragonBones(); +#endif + } + } + else + LoadExternal(); + } + + virtual protected void OnChange(string propertyName) + { + if (_contentItem == null) + return; + + + if (_contentItem.type == PackageItemType.Spine) + { +#if FAIRYGUI_SPINE + OnChangeSpine(propertyName); +#endif + } + else if (_contentItem.type == PackageItemType.DragoneBones) + { +#if FAIRYGUI_DRAGONBONES + OnChangeDragonBones(propertyName); +#endif + } + } + + virtual protected void LoadExternal() + { + } + + virtual protected void FreeExternal() + { + GameObject.DestroyImmediate(_content.wrapTarget); + } + + protected void UpdateLayout() + { + if (sourceWidth == 0 || sourceHeight == 0) + return; + + float contentWidth = sourceWidth; + float contentHeight = sourceHeight; + + if (_autoSize) + { + _updatingLayout = true; + if (contentWidth == 0) + contentWidth = 50; + if (contentHeight == 0) + contentHeight = 30; + SetSize(contentWidth, contentHeight); + + _updatingLayout = false; + + if (_width == contentWidth && _height == contentHeight) + { + _content.SetXY(0, 0); + _content.SetScale(1, 1); + + InvalidateBatchingState(); + return; + } + //如果不相等,可能是由于大小限制造成的,要后续处理 + } + + float sx = 1, sy = 1; + if (_fill != FillType.None) + { + sx = this.width / sourceWidth; + sy = this.height / sourceHeight; + + if (sx != 1 || sy != 1) + { + if (_fill == FillType.ScaleMatchHeight) + sx = sy; + else if (_fill == FillType.ScaleMatchWidth) + sy = sx; + else if (_fill == FillType.Scale) + { + if (sx > sy) + sx = sy; + else + sy = sx; + } + else if (_fill == FillType.ScaleNoBorder) + { + if (sx > sy) + sy = sx; + else + sx = sy; + } + + if (_shrinkOnly) + { + if (sx > 1) + sx = 1; + if (sy > 1) + sy = 1; + } + + contentWidth = sourceWidth * sx; + contentHeight = sourceHeight * sy; + } + } + + _content.SetScale(sx, sy); + + float nx; + float ny; + if (_align == AlignType.Center) + nx = (this.width - contentWidth) / 2; + else if (_align == AlignType.Right) + nx = this.width - contentWidth; + else + nx = 0; + if (_verticalAlign == VertAlignType.Middle) + ny = (this.height - contentHeight) / 2; + else if (_verticalAlign == VertAlignType.Bottom) + ny = this.height - contentHeight; + else + ny = 0; + _content.SetXY(nx, ny); + + InvalidateBatchingState(); + } + + protected void ClearContent() + { + if (_content.wrapTarget != null) + { + if (_contentItem != null) + { + if (_contentItem.type == PackageItemType.Spine) + { +#if FAIRYGUI_SPINE + FreeSpine(); +#endif + } + else if (_contentItem.type == PackageItemType.DragoneBones) + { +#if FAIRYGUI_DRAGONBONES + FreeDragonBones(); +#endif + } + } + else + FreeExternal(); + } + _content.wrapTarget = null; + _contentItem = null; + } + + protected void OnUpdateContent(UpdateContext context) + { + if (_contentItem == null) + return; + + + if (_contentItem.type == PackageItemType.Spine) + { +#if FAIRYGUI_SPINE + OnUpdateSpine(context); +#endif + } + else if (_contentItem.type == PackageItemType.DragoneBones) + { +#if FAIRYGUI_DRAGONBONES + OnUpdateDragonBones(context); +#endif + } + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (!_updatingLayout) + UpdateLayout(); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _url = buffer.ReadS(); + _align = (AlignType)buffer.ReadByte(); + _verticalAlign = (VertAlignType)buffer.ReadByte(); + _fill = (FillType)buffer.ReadByte(); + _shrinkOnly = buffer.ReadBool(); + _autoSize = buffer.ReadBool(); + _animationName = buffer.ReadS(); + _skinName = buffer.ReadS(); + _playing = buffer.ReadBool(); + _frame = buffer.ReadInt(); + _loop = buffer.ReadBool(); + + if (buffer.ReadBool()) + this.color = buffer.ReadColor(); //color + + if (!string.IsNullOrEmpty(_url)) + LoadContent(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs.meta new file mode 100644 index 0000000..84920c8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GLoader3D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 808355b0b55f945779f2a21d3d69cbfb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs new file mode 100644 index 0000000..4c0663a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs @@ -0,0 +1,190 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GMovieClip class. + /// + public class GMovieClip : GObject, IAnimationGear, IColorGear + { + MovieClip _content; + EventListener _onPlayEnd; + + public GMovieClip() + { + } + + override protected void CreateDisplayObject() + { + _content = new MovieClip(); + _content.gOwner = this; + _content.ignoreEngineTimeScale = true; + displayObject = _content; + } + + /// + /// + /// + public EventListener onPlayEnd + { + get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } + } + + /// + /// + /// + public bool playing + { + get { return _content.playing; } + set + { + _content.playing = value; + UpdateGear(5); + } + } + + /// + /// + /// + public int frame + { + get { return _content.frame; } + set + { + _content.frame = value; + UpdateGear(5); + } + } + + /// + /// + /// + public Color color + { + get { return _content.color; } + set + { + _content.color = value; + UpdateGear(4); + } + } + + /// + /// + /// + public FlipType flip + { + get { return _content.graphics.flip; } + set { _content.graphics.flip = value; } + } + + /// + /// + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + /// + /// + /// + public float timeScale + { + get { return _content.timeScale; } + set { _content.timeScale = value; } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _content.ignoreEngineTimeScale; } + set { _content.ignoreEngineTimeScale = value; } + } + + /// + /// + /// + public void Rewind() + { + _content.Rewind(); + } + + /// + /// + /// + /// + public void SyncStatus(GMovieClip anotherMc) + { + _content.SyncStatus(anotherMc._content); + } + + /// + /// + /// + /// + public void Advance(float time) + { + _content.Advance(time); + } + + /// + /// Play from the start to end, repeat times, set to endAt on complete. + /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) + /// + /// Start frame + /// End frame. -1 indicates the last frame. + /// Repeat times. 0 indicates infinite loop. + /// Stop frame. -1 indicates to equal to the end parameter. + public void SetPlaySettings(int start, int end, int times, int endAt) + { + ((MovieClip)displayObject).SetPlaySettings(start, end, times, endAt); + } + + override public void ConstructFromResource() + { + this.gameObjectName = packageItem.name; + + PackageItem contentItem = packageItem.getBranch(); + sourceWidth = contentItem.width; + sourceHeight = contentItem.height; + initWidth = sourceWidth; + initHeight = sourceHeight; + contentItem = contentItem.getHighResolution(); + contentItem.Load(); + + _content.interval = contentItem.interval; + _content.swing = contentItem.swing; + _content.repeatDelay = contentItem.repeatDelay; + _content.frames = contentItem.frames; + + SetSize(sourceWidth, sourceHeight); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.graphics.flip = (FlipType)buffer.ReadByte(); + _content.frame = buffer.ReadInt(); + _content.playing = buffer.ReadBool(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs.meta new file mode 100644 index 0000000..3755c4b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GMovieClip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 158e4b32fb035414091844233b2b9269 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs new file mode 100644 index 0000000..043261b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs @@ -0,0 +1,2223 @@ +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class GObject : EventDispatcher + { + /// + /// [Y 修改] + /// + + #region 自定义参数 + + public int rt_Id = 0; + + public string rt_Info = string.Empty; + public float rt_Value = 0.0f; + public object rt_Param = null; + public Action rt_Func = null; + + public GTweener rt_GTweener = null; + public DG.Tweening.Tweener rt_Tweener = null; + public GObject rt_GObject = null; + public GComponent rt_GComponent = null; + public UnityEngine.Object rt_UObject = null; + + #endregion + + #region [Du 修改] 自定义扩展 + + public const string Ex_RawURL_PREFIX = "ui://"; + + public string ex_rawElementId { get; private set; } + public string ex_rawElementName { get; private set; } + + public string Ex_GetUrlId() + { + return packageItem.owner.id + packageItem.id; + } + + public string Ex_GetUrl() + { + return Ex_RawURL_PREFIX + packageItem.owner.id + packageItem.id; + } + + public string Ex_GetParentUrlId() + { + return parent.packageItem.owner.id + parent.packageItem.id; + } + + public string Ex_GetParentUrl() + { + return Ex_RawURL_PREFIX + parent.packageItem.owner.id + parent.packageItem.id; + } + + public string Ex_GetMultiLangText() + { + return TranslationHelper.GetLangTextByName(Ex_GetParentUrlId(), ex_rawElementName); + } + + #endregion + + /// + /// GObject的id,仅作为内部使用。与name不同,id值是不会相同的。 + /// id is for internal use only. + /// + public string id { get; private set; } + + /// + /// Name of the object. + /// + public string name; + + /// + /// User defined data. + /// + public object data; + + /// + /// [Y 修改] + /// 自定义数据 + /// + public string customData; + + /// + /// The source width of the object. + /// + public int sourceWidth; + + /// + /// The source height of the object. + /// + public int sourceHeight; + + /// + /// The initial width of the object. + /// + public int initWidth; + + /// + /// The initial height of the object. + /// + public int initHeight; + + /// + /// + /// + public int minWidth; + + /// + /// + /// + public int maxWidth; + + /// + /// + /// + public int minHeight; + + /// + /// + /// + public int maxHeight; + + /// + /// Relations Object. + /// + public Relations relations { get; private set; } + + /// + /// Restricted range of dragging. + /// + public Rect? dragBounds; + + /// + /// Parent object. + /// + public GComponent parent { get; private set; } + + /// + /// Lowlevel display object. + /// + public DisplayObject displayObject { get; protected set; } + + /// + /// 当前全局正在被拖动的对象 + /// + public static GObject draggingObject { get; private set; } + + /// + /// + /// + public PackageItem packageItem; + + float _x; + float _y; + float _z; + float _pivotX; + float _pivotY; + bool _pivotAsAnchor; + float _alpha; + float _rotation; + float _rotationX; + float _rotationY; + bool _visible; + bool _internalVisible; + bool _handlingController; + bool _touchable; + bool _grayed; + bool _draggable; + float _scaleX; + float _scaleY; + int _sortingOrder; + string _tooltips; + GGroup _group; + + GearBase[] _gears; + + EventListener _onClick; + EventListener _onRightClick; + EventListener _onTouchBegin; + EventListener _onTouchMove; + EventListener _onTouchEnd; + EventListener _onRollOver; + EventListener _onRollOut; + EventListener _onAddedToStage; + EventListener _onRemovedFromStage; + EventListener _onKeyDown; + EventListener _onClickLink; + EventListener _onPositionChanged; + EventListener _onSizeChanged; + EventListener _onDragStart; + EventListener _onDragMove; + EventListener _onDragEnd; + EventListener _onGearStop; + EventListener _onFocusIn; + EventListener _onFocusOut; + + internal protected bool underConstruct; + internal float _width; + internal float _height; + internal float _rawWidth; + internal float _rawHeight; + internal bool _gearLocked; + internal float _sizePercentInGroup; + internal bool _disposed; + internal GTreeNode _treeNode; + + internal static uint _gInstanceCounter; + + public GObject() + { + _width = 0; + _height = 0; + _alpha = 1; + _visible = true; + _touchable = true; + _scaleX = 1; + _scaleY = 1; + _internalVisible = true; + id = "_n" + _gInstanceCounter++; + name = string.Empty; + + CreateDisplayObject(); + + relations = new Relations(this); + _gears = new GearBase[10]; + } + + /// + /// Dispatched when the object or its child was clicked. + /// + public EventListener onClick + { + get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } + } + + /// + /// Dispatched when the object or its child was clicked by right mouse button. Web only. + /// + public EventListener onRightClick + { + get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } + } + + /// + /// Dispatched when the finger touched the object or its child just now. + /// + public EventListener onTouchBegin + { + get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } + } + + /// + /// + /// + public EventListener onTouchMove + { + get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } + } + + /// + /// Dispatched when the finger was lifted from the screen or from the mouse button. + /// + public EventListener onTouchEnd + { + get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } + } + + /// + /// The cursor or finger hovers over an object. + /// + public EventListener onRollOver + { + get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } + } + + /// + /// The cursor or finger leave an object. + /// + public EventListener onRollOut + { + get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } + } + + /// + /// Dispatched when the object was added to the stage. + /// + public EventListener onAddedToStage + { + get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } + } + + /// + /// Dispatched when the object was removed from the stage. + /// + public EventListener onRemovedFromStage + { + get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } + } + + /// + /// Dispatched on key pressed when the object is in focus. + /// + public EventListener onKeyDown + { + get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } + } + + /// + /// Dispatched when links in the object or its child was clicked. + /// + public EventListener onClickLink + { + get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } + } + + /// + /// Dispatched when the object was moved. + /// + public EventListener onPositionChanged + { + get { return _onPositionChanged ?? (_onPositionChanged = new EventListener(this, "onPositionChanged")); } + } + + /// + /// Dispatched when the object was resized. + /// + public EventListener onSizeChanged + { + get { return _onSizeChanged ?? (_onSizeChanged = new EventListener(this, "onSizeChanged")); } + } + + /// + /// Dispatched when drag start. + /// + public EventListener onDragStart + { + get { return _onDragStart ?? (_onDragStart = new EventListener(this, "onDragStart")); } + } + + /// + /// Dispatched when dragging. + /// + public EventListener onDragMove + { + get { return _onDragMove ?? (_onDragMove = new EventListener(this, "onDragMove")); } + } + + /// + /// Dispatched when drag end. + /// + public EventListener onDragEnd + { + get { return _onDragEnd ?? (_onDragEnd = new EventListener(this, "onDragEnd")); } + } + + /// + /// + /// + public EventListener onGearStop + { + get { return _onGearStop ?? (_onGearStop = new EventListener(this, "onGearStop")); } + } + + /// + /// + /// + public EventListener onFocusIn + { + get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } + } + + /// + /// + /// + public EventListener onFocusOut + { + get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } + } + + /// + /// The x coordinate of the object relative to the local coordinates of the parent. + /// + public float x + { + get { return _x; } + set { SetPosition(value, _y, _z); } + } + + /// + /// The y coordinate of the object relative to the local coordinates of the parent. + /// + public float y + { + get { return _y; } + set { SetPosition(_x, value, _z); } + } + + /// + /// The z coordinate of the object relative to the local coordinates of the parent. + /// + public float z + { + get { return _z; } + set { SetPosition(_x, _y, value); } + } + + /// + /// The x and y coordinates of the object relative to the local coordinates of the parent. + /// + public Vector2 xy + { + get { return new Vector2(_x, _y); } + set { SetPosition(value.x, value.y, _z); } + } + + /// + /// The x,y,z coordinates of the object relative to the local coordinates of the parent. + /// + public Vector3 position + { + get { return new Vector3(_x, _y, _z); } + set { SetPosition(value.x, value.y, value.z); } + } + + /// + /// change the x and y coordinates of the object relative to the local coordinates of the parent. + /// + /// x value. + /// y value. + public void SetXY(float xv, float yv) + { + SetPosition(xv, yv, _z); + } + + /// + /// + /// + /// + /// + /// + public void SetXY(float xv, float yv, bool topLeftValue) + { + if (_pivotAsAnchor) + SetPosition(xv + _pivotX * _width, yv + _pivotY * _height, _z); + else + SetPosition(xv, yv, _z); + } + + /// + /// change the x,y,z coordinates of the object relative to the local coordinates of the parent. + /// + /// x value. + /// y value. + /// z value. + public void SetPosition(float xv, float yv, float zv) + { + if (_x != xv || _y != yv || _z != zv) + { + float dx = xv - _x; + float dy = yv - _y; + _x = xv; + _y = yv; + _z = zv; + + HandlePositionChanged(); + + if (this is GGroup) + ((GGroup)this).MoveChildren(dx, dy); + + UpdateGear(1); + + if (parent != null && !(parent is GList)) + { + parent.SetBoundsChangedFlag(); + if (_group != null) + _group.SetBoundsChangedFlag(true); + DispatchEvent("onPositionChanged", null); + } + + if (draggingObject == this && !sUpdateInDragging) + sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); + } + } + + [Obsolete("Use UIConfig.makePixelPerfect or DisplayObject.pixelPerfect")] + public bool pixelSnapping + { + get { return false; } + set { } + } + + /// + /// Set the object in middle of the parent or GRoot if the parent is not set. + /// + public void Center() + { + Center(false); + } + + /// + /// Set the object in middle of the parent or GRoot if the parent is not set. + /// + /// Add relations to maintain the center state. + public void Center(bool restraint) + { + GComponent r; + if (parent != null) + r = parent; + else + r = this.root; + + this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2), true); + if (restraint) + { + this.AddRelation(r, RelationType.Center_Center); + this.AddRelation(r, RelationType.Middle_Middle); + } + } + + /// + /// 设置对象为全屏大小(逻辑屏幕)。 + /// + public void MakeFullScreen() + { + this.SetSize(GRoot.inst.width, GRoot.inst.height); + } + + /// + /// The width of the object in pixels. + /// + public float width + { + get { return _width; } + set { SetSize(value, _rawHeight); } + } + + /// + /// The height of the object in pixels. + /// + public float height + { + get { return _height; } + set { SetSize(_rawWidth, value); } + } + + /// + /// The size of the object in pixels. + /// + public Vector2 size + { + get { return new Vector2(width, height); } + set { SetSize(value.x, value.y); } + } + + /// + /// actualWidth = width * scalex + /// + public float actualWidth + { + get { return this.width * _scaleX; } + } + + /// + /// actualHeight = height * scaleY + /// + public float actualHeight + { + get { return this.height * _scaleY; } + } + + /// + /// Change size. + /// + /// Width value. + /// Height value. + public void SetSize(float wv, float hv) + { + SetSize(wv, hv, false); + } + + /// + /// Change size. + /// + /// Width value. + /// Height value. + /// If pivot is set, the object's positon will change when its size change. Set ignorePivot=true to keep the position. + public void SetSize(float wv, float hv, bool ignorePivot) + { + if (_rawWidth != wv || _rawHeight != hv) + { + _rawWidth = wv; + _rawHeight = hv; + if (wv < minWidth) + wv = minWidth; + else if (maxWidth > 0 && wv > maxWidth) + wv = maxWidth; + if (hv < minHeight) + hv = minHeight; + else if (maxHeight > 0 && hv > maxHeight) + hv = maxHeight; + float dWidth = wv - _width; + float dHeight = hv - _height; + _width = wv; + _height = hv; + + HandleSizeChanged(); + + if (_pivotX != 0 || _pivotY != 0) + { + if (!_pivotAsAnchor) + { + if (!ignorePivot) + SetXY(_x - _pivotX * dWidth, _y - _pivotY * dHeight); + else + HandlePositionChanged(); + } + else + HandlePositionChanged(); + } + + if (this is GGroup) + ((GGroup)this).ResizeChildren(dWidth, dHeight); + + UpdateGear(2); + + if (parent != null) + { + relations.OnOwnerSizeChanged(dWidth, dHeight, _pivotAsAnchor || !ignorePivot); + parent.SetBoundsChangedFlag(); + if (_group != null) + _group.SetBoundsChangedFlag(); + } + + DispatchEvent("onSizeChanged", null); + } + } + + protected void SetSizeDirectly(float wv, float hv) + { + _rawWidth = wv; + _rawHeight = hv; + if (wv < 0) + wv = 0; + if (hv < 0) + hv = 0; + _width = wv; + _height = hv; + } + + /// + /// + /// + public float xMin + { + get { return _pivotAsAnchor ? (_x - _width * _pivotX) : _x; } + set + { + if (_pivotAsAnchor) + SetPosition(value + _width * _pivotX, _y, _z); + else + SetPosition(value, _y, _z); + } + } + + /// + /// + /// + public float yMin + { + get { return _pivotAsAnchor ? (_y - _height * _pivotY) : _y; } + set + { + if (_pivotAsAnchor) + SetPosition(_x, value + _height * _pivotY, _z); + else + SetPosition(_x, value, _z); + } + } + + /// + /// The horizontal scale factor. '1' means no scale, cannt be negative. + /// + public float scaleX + { + get { return _scaleX; } + set { SetScale(value, _scaleY); } + } + + /// + /// The vertical scale factor. '1' means no scale, cannt be negative. + /// + public float scaleY + { + get { return _scaleY; } + set { SetScale(_scaleX, value); } + } + + /// + /// The scale factor. + /// + public Vector2 scale + { + get { return new Vector2(_scaleX, _scaleY); } + set { SetScale(value.x, value.y); } + } + + /// + /// Change the scale factor. + /// + /// The horizontal scale factor. + /// The vertical scale factor + public void SetScale(float wv, float hv) + { + if (_scaleX != wv || _scaleY != hv) + { + _scaleX = wv; + _scaleY = hv; + HandleScaleChanged(); + + UpdateGear(2); + } + } + + /// + /// + /// + public Vector2 skew + { + get + { + if (displayObject != null) + return displayObject.skew; + else + return Vector2.zero; + } + + set + { + if (displayObject != null) + displayObject.skew = value; + } + } + + /// + /// The x coordinate of the object's origin in its own coordinate space. + /// + public float pivotX + { + get { return _pivotX; } + set { SetPivot(value, _pivotY, _pivotAsAnchor); } + } + + /// + /// The y coordinate of the object's origin in its own coordinate space. + /// + public float pivotY + { + get { return _pivotY; } + set { SetPivot(_pivotX, value, _pivotAsAnchor); } + } + + /// + /// The x and y coordinates of the object's origin in its own coordinate space. + /// + public Vector2 pivot + { + get { return new Vector2(_pivotX, _pivotY); } + set { SetPivot(value.x, value.y, _pivotAsAnchor); } + } + + public bool pivotAsAnchor + { + get { return _pivotAsAnchor; } + set { SetPivot(_pivotX, _pivotY, value); } + } + + /// + /// Change the x and y coordinates of the object's origin in its own coordinate space. + /// + /// x value in ratio + /// y value in ratio + public void SetPivot(float xv, float yv) + { + SetPivot(xv, yv, false); + } + + /// + /// Change the x and y coordinates of the object's origin in its own coordinate space. + /// + /// x value in ratio + /// y value in ratio + /// If use the pivot as the anchor position + public void SetPivot(float xv, float yv, bool asAnchor) + { + if (_pivotX != xv || _pivotY != yv || _pivotAsAnchor != asAnchor) + { + _pivotX = xv; + _pivotY = yv; + _pivotAsAnchor = asAnchor; + if (displayObject != null) + displayObject.pivot = new Vector2(_pivotX, _pivotY); + HandlePositionChanged(); + } + } + + /// + /// If the object can touch or click. GImage/GTextField is not touchable even it is true. + /// + public bool touchable + { + get { return _touchable; } + set + { + if (_touchable != value) + { + _touchable = value; + UpdateGear(3); + + if (displayObject != null) + displayObject.touchable = _touchable; + } + } + } + + /// + /// If true, apply a grayed effect on this object. + /// + public bool grayed + { + get { return _grayed; } + set + { + if (_grayed != value) + { + _grayed = value; + HandleGrayedChanged(); + UpdateGear(3); + } + } + } + + /// + /// Enabled is shortcut for grayed and !touchable combination. + /// + public bool enabled + { + get { return !_grayed && _touchable; } + set + { + this.grayed = !value; + this.touchable = value; + } + } + + /// + /// The rotation around the z axis of the object in degrees. + /// + public float rotation + { + get { return _rotation; } + set + { + _rotation = value; + if (displayObject != null) + displayObject.rotation = _rotation; + UpdateGear(3); + } + } + + /// + /// The rotation around the x axis of the object in degrees. + /// + public float rotationX + { + get { return _rotationX; } + set + { + _rotationX = value; + if (displayObject != null) + displayObject.rotationX = _rotationX; + } + } + + /// + /// The rotation around the y axis of the object in degrees. + /// + public float rotationY + { + get { return _rotationY; } + set + { + _rotationY = value; + if (displayObject != null) + displayObject.rotationY = _rotationY; + } + } + + /// + /// The opacity of the object. 0 = transparent, 1 = opaque. + /// + public float alpha + { + get { return _alpha; } + + set + { + _alpha = value; + HandleAlphaChanged(); + UpdateGear(3); + } + } + + /// + /// The visibility of the object. An invisible object will be untouchable. + /// + public bool visible + { + get { return _visible; } + + set + { + if (_visible != value) + { + _visible = value; + HandleVisibleChanged(); + if (parent != null) + parent.SetBoundsChangedFlag(); + if (_group != null && _group.excludeInvisibles) + _group.SetBoundsChangedFlag(); + } + } + } + + internal bool internalVisible + { + get { return _internalVisible && (group == null || group.internalVisible); } + } + + internal bool internalVisible2 + { + get { return _visible && (group == null || group.internalVisible2); } + } + + internal bool internalVisible3 + { + get { return _visible && _internalVisible; } + } + + /// + /// By default(when sortingOrder==0), object added to component is arrange by the added roder. + /// The bigger is the sorting order, the object is more in front. + /// + public int sortingOrder + { + get { return _sortingOrder; } + set + { + if (value < 0) + value = 0; + if (_sortingOrder != value) + { + int old = _sortingOrder; + _sortingOrder = value; + if (parent != null) + parent.ChildSortingOrderChanged(this, old, _sortingOrder); + } + } + } + + /// + /// If the object can be focused? + /// + public bool focusable + { + get { return displayObject != null && displayObject.focusable; } + set + { + if (displayObject != null) displayObject.focusable = value; + } + } + + /// + /// If the object can be navigated by TAB? + /// + public bool tabStop + { + get { return displayObject != null && displayObject.tabStop; } + set + { + if (displayObject != null) displayObject.tabStop = value; + } + } + + /// + /// If the object is focused. + /// + public bool focused + { + get { return displayObject != null && displayObject.focused; } + } + + /// + /// Request focus on this object. + /// + public void RequestFocus() + { + if (displayObject != null) + Stage.inst.SetFocus(displayObject, false); + } + + /// + /// Request focus on this object. + /// + public void RequestFocus(bool byKey) + { + if (displayObject != null) + Stage.inst.SetFocus(displayObject, byKey); + } + + /// + /// Tooltips of this object. UIConfig.tooltipsWin must be set first. + /// + public string tooltips + { + get { return _tooltips; } + set + { + if (!string.IsNullOrEmpty(_tooltips)) + { + this.onRollOver.Remove(__rollOver); + this.onRollOut.Remove(__rollOut); + } + + _tooltips = value; + if (!string.IsNullOrEmpty(_tooltips)) + { + this.onRollOver.Add(__rollOver); + this.onRollOut.Add(__rollOut); + } + } + } + + + /// + /// + /// + /// + public string cursor + { + get { return displayObject != null ? displayObject.cursor : null; } + set + { + if (displayObject != null) + displayObject.cursor = value; + } + } + + private void __rollOver() + { + this.root.ShowTooltips(tooltips); + } + + private void __rollOut() + { + this.root.HideTooltips(); + } + + /// + /// + /// + virtual public IFilter filter + { + get { return displayObject != null ? displayObject.filter : null; } + set + { + if (displayObject != null) displayObject.filter = value; + } + } + + /// + /// + /// + virtual public BlendMode blendMode + { + get { return displayObject != null ? displayObject.blendMode : BlendMode.None; } + set + { + if (displayObject != null) displayObject.blendMode = value; + } + } + + /// + /// 设定GameObject的名称 + /// + public string gameObjectName + { + get + { + if (displayObject != null) + return displayObject.gameObject.name; + else + return null; + } + + set + { + if (displayObject != null) + displayObject.gameObject.name = value; + } + } + + /// + /// + /// + /// + public void SetHome(GObject obj) + { + if (obj != null && displayObject != null && obj.displayObject != null) + displayObject.home = obj.displayObject.cachedTransform; + } + + /// + /// If the object has lowlevel displayobject and the displayobject has a container parent? + /// + public bool inContainer + { + get { return displayObject != null && displayObject.parent != null; } + } + + /// + /// If the object is on stage. + /// + public bool onStage + { + get { return displayObject != null && displayObject.stage != null; } + } + + /// + /// Resource url of this object. + /// + public string resourceURL + { + get + { + if (packageItem != null) + return UIPackage.URL_PREFIX + packageItem.owner.id + packageItem.id; + else + return null; + } + } + + /// + /// Gear to xy controller. + /// + public GearXY gearXY + { + get { return (GearXY)GetGear(1); } + } + + /// + /// Gear to size controller. + /// + public GearSize gearSize + { + get { return (GearSize)GetGear(2); } + } + + /// + /// Gear to look controller. + /// + public GearLook gearLook + { + get { return (GearLook)GetGear(3); } + } + + public GearBase GetGear(int index) + { + GearBase gear = _gears[index]; + if (gear == null) + { + switch (index) + { + case 0: + gear = new GearDisplay(this); + break; + case 1: + gear = new GearXY(this); + break; + case 2: + gear = new GearSize(this); + break; + case 3: + gear = new GearLook(this); + break; + case 4: + gear = new GearColor(this); + break; + case 5: + gear = new GearAnimation(this); + break; + case 6: + gear = new GearText(this); + break; + case 7: + gear = new GearIcon(this); + break; + case 8: + gear = new GearDisplay2(this); + break; + case 9: + gear = new GearFontSize(this); + break; + default: + throw new System.Exception("FairyGUI: invalid gear index!"); + } + + _gears[index] = gear; + } + + return gear; + } + + protected void UpdateGear(int index) + { + if (underConstruct || _gearLocked) + return; + + GearBase gear = _gears[index]; + if (gear != null && gear.controller != null) + gear.UpdateState(); + } + + internal bool CheckGearController(int index, Controller c) + { + return _gears[index] != null && _gears[index].controller == c; + } + + internal void UpdateGearFromRelations(int index, float dx, float dy) + { + if (_gears[index] != null) + _gears[index].UpdateFromRelations(dx, dy); + } + + internal uint AddDisplayLock() + { + GearDisplay gearDisplay = (GearDisplay)_gears[0]; + if (gearDisplay != null && gearDisplay.controller != null) + { + uint ret = gearDisplay.AddLock(); + CheckGearDisplay(); + + return ret; + } + else + return 0; + } + + internal void ReleaseDisplayLock(uint token) + { + GearDisplay gearDisplay = (GearDisplay)_gears[0]; + if (gearDisplay != null && gearDisplay.controller != null) + { + gearDisplay.ReleaseLock(token); + CheckGearDisplay(); + } + } + + void CheckGearDisplay() + { + if (_handlingController) + return; + + bool connected = _gears[0] == null || ((GearDisplay)_gears[0]).connected; + if (_gears[8] != null) + connected = ((GearDisplay2)_gears[8]).Evaluate(connected); + + if (connected != _internalVisible) + { + _internalVisible = connected; + if (parent != null) + parent.ChildStateChanged(this); + if (_group != null && _group.excludeInvisibles) + _group.SetBoundsChangedFlag(); + } + } + + /// + /// Mark the fairy batching state is invalid. + /// + public void InvalidateBatchingState() + { + if (displayObject != null) + displayObject.InvalidateBatchingState(); + else if ((this is GGroup) && parent != null) + parent.container.InvalidateBatchingState(true); + } + + virtual public void HandleControllerChanged(Controller c) + { + _handlingController = true; + for (int i = 0; i < 10; i++) + { + GearBase gear = _gears[i]; + if (gear != null && gear.controller == c) + gear.Apply(); + } + + _handlingController = false; + + CheckGearDisplay(); + } + + /// + /// + /// + /// + /// + public void AddRelation(GObject target, RelationType relationType) + { + AddRelation(target, relationType, false); + } + + /// + /// + /// + /// + /// + /// + public void AddRelation(GObject target, RelationType relationType, bool usePercent) + { + relations.Add(target, relationType, usePercent); + } + + /// + /// + /// + /// + /// + public void RemoveRelation(GObject target, RelationType relationType) + { + relations.Remove(target, relationType); + } + + /// + /// + /// + public void RemoveFromParent() + { + if (parent != null) + parent.RemoveChild(this); + } + + /// + /// Group belonging to. + /// + public GGroup group + { + get { return _group; } + set + { + if (_group != value) + { + if (_group != null) + _group.SetBoundsChangedFlag(); + _group = value; + if (_group != null) + _group.SetBoundsChangedFlag(); + HandleVisibleChanged(); + if (parent != null) + parent.ChildStateChanged(this); + } + } + } + + /// + /// + /// + public GRoot root + { + get + { + GObject p = this; + while (p.parent != null) + p = p.parent; + + if (p is GRoot) + return (GRoot)p; + + if (p.displayObject != null && p.displayObject.parent != null) + { + DisplayObject d = p.displayObject.parent.GetChild("GRoot"); + if (d != null && (d.gOwner is GRoot)) + return (GRoot)d.gOwner; + } + + return GRoot.inst; + } + } + + /// + /// [Y 修改] + /// + public virtual string inText + { + get { return null; } + set + { + /*override in child*/ + } + } + + /// + /// + /// + /// + virtual public string text + { + get { return null; } + set + { + /*override in child*/ + } + } + + /// + /// + /// + virtual public string icon + { + get { return null; } + set + { + /*override in child*/ + } + } + + /// + /// + /// + public bool draggable + { + get { return _draggable; } + set + { + if (_draggable != value) + { + _draggable = value; + InitDrag(); + } + } + } + + /// + /// + /// + public void StartDrag() + { + StartDrag(-1); + } + + /// + /// + /// + /// + public void StartDrag(int touchId) + { + if (displayObject.stage == null) + return; + + DragBegin(touchId); + } + + /// + /// + /// + public void StopDrag() + { + DragEnd(); + } + + /// + /// + /// + public bool dragging + { + get { return draggingObject == this; } + } + + /// + /// Transforms a point from the local coordinate system to global (Stage) coordinates. + /// + /// + /// + public Vector2 LocalToGlobal(Vector2 pt) + { + if (_pivotAsAnchor) + { + pt.x += _width * _pivotX; + pt.y += _height * _pivotY; + } + + return displayObject.LocalToGlobal(pt); + } + + /// + /// Transforms a point from global (Stage) coordinates to the local coordinate system. + /// + /// + /// + public Vector2 GlobalToLocal(Vector2 pt) + { + pt = displayObject.GlobalToLocal(pt); + if (_pivotAsAnchor) + { + pt.x -= _width * _pivotX; + pt.y -= _height * _pivotY; + } + + return pt; + } + + /// + /// + /// + /// + /// + public Rect LocalToGlobal(Rect rect) + { + Rect ret = new Rect(); + Vector2 v = this.LocalToGlobal(new Vector2(rect.xMin, rect.yMin)); + ret.xMin = v.x; + ret.yMin = v.y; + v = this.LocalToGlobal(new Vector2(rect.xMax, rect.yMax)); + ret.xMax = v.x; + ret.yMax = v.y; + return ret; + } + + /// + /// + /// + /// + /// + public Rect GlobalToLocal(Rect rect) + { + Rect ret = new Rect(); + Vector2 v = this.GlobalToLocal(new Vector2(rect.xMin, rect.yMin)); + ret.xMin = v.x; + ret.yMin = v.y; + v = this.GlobalToLocal(new Vector2(rect.xMax, rect.yMax)); + ret.xMax = v.x; + ret.yMax = v.y; + return ret; + } + + /// + /// Transforms a point from the local coordinate system to GRoot coordinates. + /// + /// + /// + /// + public Vector2 LocalToRoot(Vector2 pt, GRoot r) + { + pt = LocalToGlobal(pt); + if (r == null || r == GRoot.inst) + { + //fast + pt.x /= UIContentScaler.scaleFactor; + pt.y /= UIContentScaler.scaleFactor; + return pt; + } + else + return r.GlobalToLocal(pt); + } + + /// + /// Transforms a point from the GRoot coordinate to local coordinates system. + /// + /// + /// + /// + public Vector2 RootToLocal(Vector2 pt, GRoot r) + { + if (r == null || r == GRoot.inst) + { + //fast + pt.x *= UIContentScaler.scaleFactor; + pt.y *= UIContentScaler.scaleFactor; + } + else + pt = r.LocalToGlobal(pt); + + return GlobalToLocal(pt); + } + + /// + /// + /// + /// + /// + public Vector2 WorldToLocal(Vector3 pt) + { + return WorldToLocal(pt, HitTestContext.cachedMainCamera); + } + + /// + /// + /// + /// + /// + /// + public Vector2 WorldToLocal(Vector3 pt, Camera camera) + { + Vector3 v = camera.WorldToScreenPoint(pt); + v.y = Screen.height - v.y; + v.z = 0; + return GlobalToLocal(v); + } + + /// + /// + /// + /// + /// + /// + public Vector2 TransformPoint(Vector2 pt, GObject targetSpace) + { + if (_pivotAsAnchor) + { + pt.x += _width * _pivotX; + pt.y += _height * _pivotY; + } + + return this.displayObject.TransformPoint(pt, targetSpace != null ? targetSpace.displayObject : Stage.inst); + } + + /// + /// + /// + /// + /// + /// + public Rect TransformRect(Rect rect, GObject targetSpace) + { + if (_pivotAsAnchor) + { + rect.x += _width * _pivotX; + rect.y += _height * _pivotY; + } + + return this.displayObject.TransformRect(rect, targetSpace != null ? targetSpace.displayObject : Stage.inst); + } + + /// + /// + /// + public bool isDisposed + { + get { return _disposed; } + } + + /// + /// + /// + virtual public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + + RemoveFromParent(); + RemoveEventListeners(); + relations.Dispose(); + relations = null; + for (int i = 0; i < 10; i++) + { + GearBase gear = _gears[i]; + if (gear != null) + gear.Dispose(); + } + + if (displayObject != null) + { + displayObject.gOwner = null; + displayObject.Dispose(); + } + + data = null; + + // [Y 修改] + + #region 自定义扩展 + + rt_Id = 0; + rt_Info = string.Empty; + rt_Value = 0.0f; + rt_Param = null; + rt_Func = null; + + rt_GTweener = null; + rt_Tweener = null; + rt_GObject = null; + rt_GComponent = null; + rt_UObject = null; + + #endregion + } + + /// + /// + /// + public GImage asImage + { + get { return this as GImage; } + } + + /// + /// + /// + public GComponent asCom + { + get { return this as GComponent; } + } + + /// + /// + /// + public GButton asButton + { + get { return this as GButton; } + } + + /// + /// + /// + public GLabel asLabel + { + get { return this as GLabel; } + } + + /// + /// + /// + public GProgressBar asProgress + { + get { return this as GProgressBar; } + } + + /// + /// + /// + public GSlider asSlider + { + get { return this as GSlider; } + } + + /// + /// + /// + public GComboBox asComboBox + { + get { return this as GComboBox; } + } + + /// + /// + /// + public GTextField asTextField + { + get { return this as GTextField; } + } + + /// + /// + /// + public GRichTextField asRichTextField + { + get { return this as GRichTextField; } + } + + /// + /// + /// + public GTextInput asTextInput + { + get { return this as GTextInput; } + } + + /// + /// + /// + public GLoader asLoader + { + get { return this as GLoader; } + } + + /// + /// + /// + public GLoader3D asLoader3D + { + get { return this as GLoader3D; } + } + + /// + /// + /// + public GList asList + { + get { return this as GList; } + } + + /// + /// + /// + public GGraph asGraph + { + get { return this as GGraph; } + } + + /// + /// + /// + public GGroup asGroup + { + get { return this as GGroup; } + } + + /// + /// + /// + public GMovieClip asMovieClip + { + get { return this as GMovieClip; } + } + + /// + /// + /// + public GTree asTree + { + get { return this as GTree; } + } + + /// + /// + /// + public GTreeNode treeNode + { + get { return _treeNode; } + } + + virtual protected void CreateDisplayObject() + { + } + + internal void InternalSetParent(GComponent value) + { + parent = value; + } + + virtual protected void HandlePositionChanged() + { + if (displayObject != null) + { + float xv = _x; + float yv = _y; + if (!_pivotAsAnchor) + { + xv += _width * _pivotX; + yv += _height * _pivotY; + } + + displayObject.location = new Vector3(xv, yv, _z); + } + } + + virtual protected void HandleSizeChanged() + { + if (displayObject != null) + displayObject.SetSize(_width, _height); + } + + virtual protected void HandleScaleChanged() + { + if (displayObject != null) + displayObject.SetScale(_scaleX, _scaleY); + } + + virtual protected void HandleGrayedChanged() + { + if (displayObject != null) + displayObject.grayed = _grayed; + } + + virtual protected void HandleAlphaChanged() + { + if (displayObject != null) + displayObject.alpha = _alpha; + } + + virtual internal protected void HandleVisibleChanged() + { + if (displayObject != null) + displayObject.visible = internalVisible2; + } + + virtual public void ConstructFromResource() + { + } + + virtual public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + buffer.Seek(beginPos, 0); + buffer.Skip(5); + + id = buffer.ReadS(); + name = buffer.ReadS(); + + // [Y 修改] + ex_rawElementId = id; + ex_rawElementName = name; + + float f1 = buffer.ReadInt(); + float f2 = buffer.ReadInt(); + SetXY(f1, f2); + + if (buffer.ReadBool()) + { + initWidth = buffer.ReadInt(); + initHeight = buffer.ReadInt(); + SetSize(initWidth, initHeight, true); + } + + if (buffer.ReadBool()) + { + minWidth = buffer.ReadInt(); + maxWidth = buffer.ReadInt(); + minHeight = buffer.ReadInt(); + maxHeight = buffer.ReadInt(); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + SetScale(f1, f2); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + this.skew = new Vector2(f1, f2); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + SetPivot(f1, f2, buffer.ReadBool()); + } + + f1 = buffer.ReadFloat(); + if (f1 != 1) + this.alpha = f1; + + f1 = buffer.ReadFloat(); + if (f1 != 0) + this.rotation = f1; + + if (!buffer.ReadBool()) + this.visible = false; + if (!buffer.ReadBool()) + this.touchable = false; + if (buffer.ReadBool()) + this.grayed = true; + this.blendMode = (BlendMode)buffer.ReadByte(); + + int filter = buffer.ReadByte(); + if (filter == 1) + { + ColorFilter cf = new ColorFilter(); + this.filter = cf; + + cf.AdjustBrightness(buffer.ReadFloat()); + cf.AdjustContrast(buffer.ReadFloat()); + cf.AdjustSaturation(buffer.ReadFloat()); + cf.AdjustHue(buffer.ReadFloat()); + } + + string str = buffer.ReadS(); + // [Y 修改] + if (str != null && !string.IsNullOrWhiteSpace(str)) + { + this.data = str; + // [Y 修改] + this.customData = str; + } + } + + virtual public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + buffer.Seek(beginPos, 1); + + string str = buffer.ReadS(); + if (str != null) + this.tooltips = str; + + int groupId = buffer.ReadShort(); + if (groupId >= 0) + group = parent.GetChildAt(groupId) as GGroup; + + buffer.Seek(beginPos, 2); + + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + GearBase gear = GetGear(buffer.ReadByte()); + gear.Setup(buffer); + + buffer.position = nextPos; + } + } + + #region Drag support + + Vector2 _dragTouchStartPos; + bool _dragTesting; + + static Vector2 sGlobalDragStart = new Vector2(); + static Rect sGlobalRect = new Rect(); + static bool sUpdateInDragging = false; + + private void InitDrag() + { + if (_draggable) + { + onTouchBegin.Add(__touchBegin); + onTouchMove.Add(__touchMove); + onTouchEnd.Add(__touchEnd); + } + else + { + onTouchBegin.Remove(__touchBegin); + onTouchMove.Remove(__touchMove); + onTouchEnd.Remove(__touchEnd); + } + } + + private void DragBegin(int touchId) + { + if (DispatchEvent("onDragStart", touchId)) + return; + + if (draggingObject != null) + { + GObject tmp = draggingObject; + draggingObject.StopDrag(); + draggingObject = null; + tmp.DispatchEvent("onDragEnd", null); + } + + onTouchMove.Add(__touchMove); + onTouchEnd.Add(__touchEnd); + + sGlobalDragStart = Stage.inst.GetTouchPosition(touchId); + sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); + _dragTesting = false; + + draggingObject = this; + Stage.inst.AddTouchMonitor(touchId, this); + } + + private void DragEnd() + { + if (draggingObject == this) + { + _dragTesting = false; + draggingObject = null; + } + } + + private void __touchBegin(EventContext context) + { + if ((Stage.inst.focus is InputTextField) && ((InputTextField)Stage.inst.focus).editable) + { + _dragTesting = false; + return; + } + + InputEvent evt = context.inputEvent; + _dragTouchStartPos = evt.position; + _dragTesting = true; + context.CaptureTouch(); + } + + private void __touchMove(EventContext context) + { + InputEvent evt = context.inputEvent; + + if (_dragTesting && draggingObject != this) + { + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchDragSensitivity; + else + sensitivity = UIConfig.clickDragSensitivity; + if (Mathf.Abs(_dragTouchStartPos.x - evt.x) < sensitivity + && Mathf.Abs(_dragTouchStartPos.y - evt.y) < sensitivity) + return; + + _dragTesting = false; + DragBegin(evt.touchId); + } + + if (draggingObject == this) + { + float xx = evt.x - sGlobalDragStart.x + sGlobalRect.x; + float yy = evt.y - sGlobalDragStart.y + sGlobalRect.y; + + if (dragBounds != null) + { + Rect rect = GRoot.inst.LocalToGlobal((Rect)dragBounds); + if (xx < rect.x) + xx = rect.x; + else if (xx + sGlobalRect.width > rect.xMax) + { + xx = rect.xMax - sGlobalRect.width; + if (xx < rect.x) + xx = rect.x; + } + + if (yy < rect.y) + yy = rect.y; + else if (yy + sGlobalRect.height > rect.yMax) + { + yy = rect.yMax - sGlobalRect.height; + if (yy < rect.y) + yy = rect.y; + } + } + + Vector2 pt = this.parent.GlobalToLocal(new Vector2(xx, yy)); + if (float.IsNaN(pt.x)) + return; + + sUpdateInDragging = true; + this.SetXY(Mathf.RoundToInt(pt.x), Mathf.RoundToInt(pt.y)); + sUpdateInDragging = false; + + DispatchEvent("onDragMove", null); + } + } + + private void __touchEnd(EventContext context) + { + if (draggingObject == this) + { + draggingObject = null; + DispatchEvent("onDragEnd", null); + } + } + + #endregion + + #region Tween Helpers + + public GTweener TweenMove(Vector2 endValue, float duration) + { + return GTween.To(this.xy, endValue, duration).SetTarget(this, TweenPropType.XY); + } + + public GTweener TweenMoveX(float endValue, float duration) + { + return GTween.To(_x, endValue, duration).SetTarget(this, TweenPropType.X); + } + + public GTweener TweenMoveY(float endValue, float duration) + { + return GTween.To(_y, endValue, duration).SetTarget(this, TweenPropType.Y); + } + + public GTweener TweenScale(Vector2 endValue, float duration) + { + return GTween.To(this.scale, endValue, duration).SetTarget(this, TweenPropType.Scale); + } + + public GTweener TweenScaleX(float endValue, float duration) + { + return GTween.To(_scaleX, endValue, duration).SetTarget(this, TweenPropType.ScaleX); + } + + public GTweener TweenScaleY(float endValue, float duration) + { + return GTween.To(_scaleY, endValue, duration).SetTarget(this, TweenPropType.ScaleY); + } + + public GTweener TweenResize(Vector2 endValue, float duration) + { + return GTween.To(this.size, endValue, duration).SetTarget(this, TweenPropType.Size); + } + + public GTweener TweenFade(float endValue, float duration) + { + return GTween.To(_alpha, endValue, duration).SetTarget(this, TweenPropType.Alpha); + } + + public GTweener TweenRotate(float endValue, float duration) + { + return GTween.To(_rotation, endValue, duration).SetTarget(this, TweenPropType.Rotation); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs.meta new file mode 100644 index 0000000..03a7853 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3ab09a55620b5f40a544e775edc4b22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs new file mode 100644 index 0000000..0ef203d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs @@ -0,0 +1,105 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// GObjectPool is use for GObject pooling. + /// + public class GObjectPool + { + /// + /// Callback function when a new object is creating. + /// + /// + public delegate void InitCallbackDelegate(GObject obj); + + /// + /// Callback function when a new object is creating. + /// + public InitCallbackDelegate initCallback; + + Dictionary> _pool; + Transform _manager; + + /// + /// 需要设置一个manager,加入池里的对象都成为这个manager的孩子 + /// + /// + public GObjectPool(Transform manager) + { + _manager = manager; + _pool = new Dictionary>(); + } + + /// + /// Dispose all objects in the pool. + /// + public void Clear() + { + foreach (KeyValuePair> kv in _pool) + { + Queue list = kv.Value; + foreach (GObject obj in list) + obj.Dispose(); + } + _pool.Clear(); + } + + /// + /// + /// + public int count + { + get { return _pool.Count; } + } + + /// + /// + /// + /// + /// + public GObject GetObject(string url) + { + url = UIPackage.NormalizeURL(url); + if (url == null) + return null; + + Queue arr; + if (_pool.TryGetValue(url, out arr) + && arr.Count > 0) + return arr.Dequeue(); + + GObject obj = UIPackage.CreateObjectFromURL(url); + if (obj != null) + { + if (initCallback != null) + initCallback(obj); + } + + return obj; + } + + /// + /// + /// + /// + public void ReturnObject(GObject obj) + { + if (obj.displayObject.isDisposed) + return; + + string url = obj.resourceURL; + Queue arr; + if (!_pool.TryGetValue(url, out arr)) + { + arr = new Queue(); + _pool.Add(url, arr); + } + + if (_manager != null) + obj.displayObject.cachedTransform.SetParent(_manager, false); + arr.Enqueue(obj); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs.meta new file mode 100644 index 0000000..27fc70a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GObjectPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb355b8d4ba140f469be6be6b062dfda +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs new file mode 100644 index 0000000..f08bb48 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs @@ -0,0 +1,322 @@ +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GProgressBar class. + /// + public class GProgressBar : GComponent + { + double _min; + double _max; + double _value; + ProgressTitleType _titleType; + bool _reverse; + + GObject _titleObject; + GMovieClip _aniObject; + GObject _barObjectH; + GObject _barObjectV; + float _barMaxWidth; + float _barMaxHeight; + float _barMaxWidthDelta; + float _barMaxHeightDelta; + float _barStartX; + float _barStartY; + + public GProgressBar() + { + _value = 50; + _max = 100; + } + + /// + /// 返回title对象 + /// + public GObject title + { + get + { + return _titleObject; + } + } + + /// + /// + /// + public ProgressTitleType titleType + { + + get + { + return _titleType; + } + set + { + if (_titleType != value) + { + _titleType = value; + Update(_value); + } + } + } + + /// + /// + /// + public double min + { + get + { + return _min; + } + set + { + if (_min != value) + { + _min = value; + Update(_value); + } + } + } + + /// + /// + /// + public double max + { + get + { + return _max; + } + set + { + if (_max != value) + { + _max = value; + Update(_value); + } + } + } + + /// + /// + /// + public double value + { + get + { + return _value; + } + set + { + if (_value != value) + { + GTween.Kill(this, TweenPropType.Progress, false); + + _value = value; + Update(_value); + } + } + } + + public bool reverse + { + get { return _reverse; } + set { _reverse = value; } + } + + /// + /// 动态改变进度值。 + /// + /// + /// + public GTweener TweenValue(double value, float duration) + { + double oldValule; + + GTweener twener = GTween.GetTween(this, TweenPropType.Progress); + if (twener != null) + { + oldValule = twener.value.d; + twener.Kill(false); + } + else + oldValule = _value; + + _value = value; + return GTween.ToDouble(oldValule, _value, duration) + .SetEase(EaseType.Linear) + .SetTarget(this, TweenPropType.Progress); + } + + /// + /// + /// + /// + public void Update(double newValue) + { + float percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); + if (_titleObject != null) + { + switch (_titleType) + { + case ProgressTitleType.Percent: + if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) + _titleObject.text = "%" + Mathf.FloorToInt(percent * 100); + else + _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; + break; + + case ProgressTitleType.ValueAndMax: + if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) + _titleObject.text = Math.Round(max) + "/" + Math.Round(newValue); + else + _titleObject.text = Math.Round(newValue) + "/" + Math.Round(max); + break; + + case ProgressTitleType.Value: + _titleObject.text = "" + Math.Round(newValue); + break; + + case ProgressTitleType.Max: + _titleObject.text = "" + Math.Round(_max); + break; + } + } + + float fullWidth = this.width - _barMaxWidthDelta; + float fullHeight = this.height - _barMaxHeightDelta; + if (!_reverse) + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, percent)) + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, percent)) + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + } + } + else + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, 1 - percent)) + { + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); + } + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, 1 - percent)) + { + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); + } + } + } + if (_aniObject != null) + _aniObject.frame = Mathf.RoundToInt(percent * 100); + + InvalidateBatchingState(true); + } + + bool SetFillAmount(GObject bar, float amount) + { + if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) + ((GImage)bar).fillAmount = amount; + else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) + ((GLoader)bar).fillAmount = amount; + else + return false; + + return true; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _titleType = (ProgressTitleType)buffer.ReadByte(); + _reverse = buffer.ReadBool(); + + _titleObject = GetChild("title"); + _barObjectH = GetChild("bar"); + _barObjectV = GetChild("bar_v"); + _aniObject = GetChild("ani") as GMovieClip; + + if (_barObjectH != null) + { + _barMaxWidth = _barObjectH.width; + _barMaxWidthDelta = this.width - _barMaxWidth; + _barStartX = _barObjectH.x; + } + if (_barObjectV != null) + { + _barMaxHeight = _barObjectV.height; + _barMaxHeightDelta = this.height - _barMaxHeight; + _barStartY = _barObjectV.y; + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + { + Update(_value); + return; + } + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + { + Update(_value); + return; + } + + _value = buffer.ReadInt(); + _max = buffer.ReadInt(); + if (buffer.version >= 2) + _min = buffer.ReadInt(); + + if (buffer.version >= 5) + { + string sound = buffer.ReadS(); + if (!string.IsNullOrEmpty(sound)) + { + float volumeScale = buffer.ReadFloat(); + displayObject.onClick.Add(() => + { + NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; + if (audioClip != null && audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); + }); + } + else + buffer.Skip(4); + } + + Update(_value); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (_barObjectH != null) + _barMaxWidth = this.width - _barMaxWidthDelta; + if (_barObjectV != null) + _barMaxHeight = this.height - _barMaxHeightDelta; + + if (!this.underConstruct) + Update(_value); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs.meta new file mode 100644 index 0000000..abc5756 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GProgressBar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f13bf1fdc7711c4aa9c5e1631138025 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs new file mode 100644 index 0000000..5a150fc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GRichTextField class. + /// + public class GRichTextField : GTextField + { + /// + /// + /// + public RichTextField richTextField { get; private set; } + + public GRichTextField() + : base() + { + } + + override protected void CreateDisplayObject() + { + richTextField = new RichTextField(); + richTextField.gOwner = this; + displayObject = richTextField; + + _textField = richTextField.textField; + } + + override protected void SetTextFieldText() + { + string str = _text; + if (_templateVars != null) + str = ParseTemplate(str); + + _textField.maxWidth = maxWidth; + if (_ubbEnabled) + richTextField.htmlText = UBBParser.inst.Parse(str); + else + richTextField.htmlText = str; + } + + /// + /// + /// + public Dictionary emojies + { + get { return richTextField.emojies; } + set { richTextField.emojies = value; } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs.meta new file mode 100644 index 0000000..77b2431 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRichTextField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c329d14f7b7d35348be7ec3e2a4b0591 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs new file mode 100644 index 0000000..284bd1b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs @@ -0,0 +1,861 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// GRoot is a topmost component of UI display list.You dont need to create GRoot. It is created automatically. + /// + public class GRoot : GComponent + { + /// + /// + /// + public static float contentScaleFactor + { + get { return UIContentScaler.scaleFactor; } + } + + /// + /// + /// + public static int contentScaleLevel + { + get { return UIContentScaler.scaleLevel; } + } + + GGraph _modalLayer; + GObject _modalWaitPane; + List _popupStack; + List _justClosedPopups; + HashSet _specialPopups; + GObject _tooltipWin; + GObject _defaultTooltipWin; + + internal static GRoot _inst; + + public static GRoot inst + { + get + { + if (_inst == null) + { + Stage.Instantiate(); + } + + return _inst; + } + } + + public GRoot() + { + this.name = this.rootContainer.name = this.rootContainer.gameObject.name = "GRoot"; + this.opaque = false; + + _popupStack = new List(); + _justClosedPopups = new List(); + _specialPopups = new HashSet(); + + Stage.inst.onTouchBegin.AddCapture(__stageTouchBegin); + Stage.inst.onTouchEnd.AddCapture(__stageTouchEnd); + } + + override public void Dispose() + { + base.Dispose(); + + Stage.inst.onTouchBegin.RemoveCapture(__stageTouchBegin); + Stage.inst.onTouchEnd.RemoveCapture(__stageTouchEnd); + } + + /// + /// Set content scale factor. + /// + /// Design resolution of x axis. + /// Design resolution of y axis. + public void SetContentScaleFactor(int designResolutionX, int designResolutionY) + { + SetContentScaleFactor(designResolutionX, designResolutionY, + UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + } + + /// + /// Set content scale factor. + /// + /// Design resolution of x axis. + /// Design resolution of y axis. + /// Match mode. + public void SetContentScaleFactor(int designResolutionX, int designResolutionY, + UIContentScaler.ScreenMatchMode screenMatchMode) + { + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + scaler.designResolutionX = designResolutionX; + scaler.designResolutionY = designResolutionY; + scaler.scaleMode = UIContentScaler.ScaleMode.ScaleWithScreenSize; + scaler.screenMatchMode = screenMatchMode; + scaler.ApplyChange(); + ApplyContentScaleFactor(); + } + + /// + /// + /// + /// + public void SetContentScaleFactor(float constantScaleFactor) + { + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + scaler.scaleMode = UIContentScaler.ScaleMode.ConstantPixelSize; + scaler.constantScaleFactor = constantScaleFactor; + scaler.ApplyChange(); + ApplyContentScaleFactor(); + } + + /// + /// This is called after screen size changed. + /// + public void ApplyContentScaleFactor() + { + this.SetSize(Mathf.CeilToInt(Stage.inst.width / UIContentScaler.scaleFactor), + Mathf.CeilToInt(Stage.inst.height / UIContentScaler.scaleFactor)); + this.SetScale(UIContentScaler.scaleFactor, UIContentScaler.scaleFactor); + } + + /// + /// Display a window. + /// + /// + public void ShowWindow(Window win) + { + AddChild(win); + AdjustModalLayer(); + } + + /// + /// Call window.Hide + /// 关闭一个窗口。将调用Window.Hide方法。 + /// + /// + public void HideWindow(Window win) + { + win.Hide(); + } + + /// + /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. + ///立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 + /// + /// + public void HideWindowImmediately(Window win) + { + HideWindowImmediately(win, false); + } + + /// + /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. + /// 立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 + /// + /// + /// True to dispose the window. + public void HideWindowImmediately(Window win, bool dispose) + { + if (win.parent == this) + RemoveChild(win, dispose); + else if (dispose) + win.Dispose(); + + AdjustModalLayer(); + } + + /// + /// 将一个窗口提到所有窗口的最前面 + /// + /// + public void BringToFront(Window win) + { + int cnt = this.numChildren; + int i; + if (_modalLayer != null && _modalLayer.parent != null && !win.modal) + i = GetChildIndex(_modalLayer) - 1; + else + i = cnt - 1; + + for (; i >= 0; i--) + { + GObject g = GetChildAt(i); + if (g == win) + return; + if (g is Window) + break; + } + + if (i >= 0) + SetChildIndex(win, i); + } + + /// + /// Display a modal layer and a waiting sign in the front. + /// 显示一个半透明层和一个等待标志在最前面。半透明层的颜色可以通过UIConfig.modalLayerColor设定。 + /// 等待标志的资源可以通过UIConfig.globalModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 + /// + public void ShowModalWait() + { + if (UIConfig.globalModalWaiting != null) + { + if (_modalWaitPane == null || _modalWaitPane.isDisposed) + { + _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.globalModalWaiting); + _modalWaitPane.SetHome(this); + } + + _modalWaitPane.SetSize(this.width, this.height); + _modalWaitPane.AddRelation(this, RelationType.Size); + + AddChild(_modalWaitPane); + } + } + + /// + /// Hide modal layer and waiting sign. + /// + public void CloseModalWait() + { + if (_modalWaitPane != null && _modalWaitPane.parent != null) + RemoveChild(_modalWaitPane); + } + + /// + /// Close all windows except modal windows. + /// + public void CloseAllExceptModals() + { + GObject[] arr = _children.ToArray(); + foreach (GObject g in arr) + { + if ((g is Window) && !(g as Window).modal) + HideWindowImmediately(g as Window); + } + } + + /// + /// Close all windows. + /// + public void CloseAllWindows() + { + GObject[] arr = _children.ToArray(); + foreach (GObject g in arr) + { + if (g is Window) + HideWindowImmediately(g as Window); + } + } + + /// + /// Get window on top. + /// + /// + public Window GetTopWindow() + { + int cnt = this.numChildren; + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = this.GetChildAt(i); + if (g is Window) + { + return (Window)(g); + } + } + + return null; + } + + /// + /// + /// + public GGraph modalLayer + { + get + { + if (_modalLayer == null || _modalLayer.isDisposed) + CreateModalLayer(); + + return _modalLayer; + } + } + + void CreateModalLayer() + { + _modalLayer = new GGraph(); + _modalLayer.DrawRect(this.width, this.height, 0, Color.white, UIConfig.modalLayerColor); + _modalLayer.AddRelation(this, RelationType.Size); + _modalLayer.name = _modalLayer.gameObjectName = "ModalLayer"; + _modalLayer.SetHome(this); + } + + /// + /// Return true if a modal window is on stage. + /// + public bool hasModalWindow + { + get { return _modalLayer != null && _modalLayer.parent != null; } + } + + /// + /// Return true if modal waiting layer is on stage. + /// + public bool modalWaiting + { + get { return (_modalWaitPane != null) && _modalWaitPane.onStage; } + } + + /// + /// Get current touch target. (including hover) + /// + public GObject touchTarget + { + get { return DisplayObjectToGObject(Stage.inst.touchTarget); } + } + + /// + /// + /// + /// + /// + public GObject DisplayObjectToGObject(DisplayObject obj) + { + while (obj != null) + { + if (obj.gOwner != null) + return obj.gOwner; + + obj = obj.parent; + } + + return null; + } + + private void AdjustModalLayer() + { + if (_modalLayer == null || _modalLayer.isDisposed) + CreateModalLayer(); + + int cnt = this.numChildren; + + if (_modalWaitPane != null && _modalWaitPane.parent != null) + SetChildIndex(_modalWaitPane, cnt - 1); + + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = this.GetChildAt(i); + if ((g is Window) && (g as Window).modal) + { + if (_modalLayer.parent == null) + AddChildAt(_modalLayer, i); + else + SetChildIndexBefore(_modalLayer, i); + return; + } + } + + if (_modalLayer.parent != null) + RemoveChild(_modalLayer); + } + + /// + /// Show a popup object. + /// 显示一个popup。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + public void ShowPopup(GObject popup) + { + ShowPopup(popup, null, PopupDirection.Auto, false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上边或者下边。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + /// + public void ShowPopup(GObject popup, GObject target) + { + ShowPopup(popup, target, PopupDirection.Auto, false); + } + + [Obsolete] + public void ShowPopup(GObject popup, GObject target, object downward) + { + ShowPopup(popup, target, + downward == null + ? PopupDirection.Auto + : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), + false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上方或者下方。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + /// + /// + public void ShowPopup(GObject popup, GObject target, PopupDirection dir) + { + ShowPopup(popup, target, dir, false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上方或者下方。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// 默认情况下,popup在touchEnd事件中关闭;特别设置closeUntilUpEvent=true则可使该popup在touchEnd中才关闭。 + /// + /// + /// + /// + /// + public void ShowPopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) + { + if (_popupStack.Count > 0) + { + int k = _popupStack.IndexOf(popup); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i >= k; i--) + { + int last = _popupStack.Count - 1; + GObject obj = _popupStack[last]; + ClosePopup(obj); + _popupStack.RemoveAt(last); + _specialPopups.Remove(obj); + } + } + } + + _popupStack.Add(popup); + if (closeUntilUpEvent) + _specialPopups.Add(popup); + + if (target != null) + { + GObject p = target; + while (p != null) + { + if (p.parent == this) + { + if (popup.sortingOrder < p.sortingOrder) + { + popup.sortingOrder = p.sortingOrder; + } + + break; + } + + p = p.parent; + } + } + + AddChild(popup); + AdjustModalLayer(); + + if ((popup is Window) && target == null && dir == PopupDirection.Auto) + return; + + Vector2 pos = GetPoupPosition(popup, target, dir); + popup.xy = pos; + } + + [Obsolete] + public Vector2 GetPoupPosition(GObject popup, GObject target, object downward) + { + return GetPoupPosition(popup, target, + downward == null + ? PopupDirection.Auto + : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up)); + } + + /// + /// + /// + /// + /// + /// + /// + public Vector2 GetPoupPosition(GObject popup, GObject target, PopupDirection dir) + { + Vector2 pos; + Vector2 size = Vector2.zero; + if (target != null) + { + pos = target.LocalToRoot(Vector2.zero, this); + size = target.LocalToRoot(target.size, this) - pos; + } + else + { + pos = this.GlobalToLocal(Stage.inst.touchPosition); + } + + float xx, yy; + xx = pos.x; + if (xx + popup.width > this.width) + xx = xx + size.x - popup.width; + yy = pos.y + size.y; + if ((dir == PopupDirection.Auto && yy + popup.height > this.height) + || dir == PopupDirection.Up) + { + yy = pos.y - popup.height - 1; + if (yy < 0) + { + yy = 0; + xx += size.x / 2; + } + } + + return new Vector2(Mathf.RoundToInt(xx), Mathf.RoundToInt(yy)); + } + + /// + /// If a popup is showing, then close it; otherwise, open it. + /// + /// + public void TogglePopup(GObject popup) + { + TogglePopup(popup, null, PopupDirection.Auto, false); + } + + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target) + { + TogglePopup(popup, target, PopupDirection.Auto, false); + } + + [Obsolete] + public void TogglePopup(GObject popup, GObject target, object downward) + { + TogglePopup(popup, target, + downward == null + ? PopupDirection.Auto + : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), + false); + } + + /// + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target, PopupDirection dir) + { + TogglePopup(popup, target, dir, false); + } + + /// + /// + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) + { + if (_justClosedPopups.IndexOf(popup) != -1) + return; + + ShowPopup(popup, target, dir, closeUntilUpEvent); + } + + /// + /// Close all popups. + /// + public void HidePopup() + { + HidePopup(null); + } + + /// + /// Close a popup. + /// + /// + public void HidePopup(GObject popup) + { + if (popup != null) + { + int k = _popupStack.IndexOf(popup); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i >= k; i--) + { + int last = _popupStack.Count - 1; + GObject obj = _popupStack[last]; + ClosePopup(obj); + _popupStack.RemoveAt(last); + _specialPopups.Remove(obj); + } + } + } + else + { + foreach (GObject obj in _popupStack) + ClosePopup(obj); + _popupStack.Clear(); + _specialPopups.Clear(); + } + } + + /// + /// + /// + public bool hasAnyPopup + { + get { return _popupStack.Count > 0; } + } + + void ClosePopup(GObject target) + { + if (target.parent != null) + { + if (target is Window) + ((Window)target).Hide(); + else + RemoveChild(target); + } + } + + /// + /// + /// + /// + public void ShowTooltips(string msg) + { + ShowTooltips(msg, 0.1f); + } + + /// + /// + /// + /// + /// + public void ShowTooltips(string msg, float delay) + { + if (_defaultTooltipWin == null || _defaultTooltipWin.isDisposed) + { + string resourceURL = UIConfig.tooltipsWin; + if (string.IsNullOrEmpty(resourceURL)) + { + Debug.LogWarning("FairyGUI: UIConfig.tooltipsWin not defined"); + return; + } + + _defaultTooltipWin = UIPackage.CreateObjectFromURL(resourceURL); + _defaultTooltipWin.SetHome(this); + _defaultTooltipWin.touchable = false; + } + + _defaultTooltipWin.text = msg; + ShowTooltipsWin(_defaultTooltipWin, delay); + } + + /// + /// + /// + /// + public void ShowTooltipsWin(GObject tooltipWin) + { + ShowTooltipsWin(tooltipWin, 0.1f); + } + + /// + /// + /// + /// + /// + public void ShowTooltipsWin(GObject tooltipWin, float delay) + { + HideTooltips(); + + _tooltipWin = tooltipWin; + Timers.inst.Add(delay, 1, __showTooltipsWin); + } + + void __showTooltipsWin(object param) + { + if (_tooltipWin == null) + return; + + float xx = Stage.inst.touchPosition.x + 10; + float yy = Stage.inst.touchPosition.y + 20; + + Vector2 pt = this.GlobalToLocal(new Vector2(xx, yy)); + xx = pt.x; + yy = pt.y; + + if (xx + _tooltipWin.width > this.width) + xx = xx - _tooltipWin.width; + if (yy + _tooltipWin.height > this.height) + { + yy = yy - _tooltipWin.height - 1; + if (yy < 0) + yy = 0; + } + + _tooltipWin.x = Mathf.RoundToInt(xx); + _tooltipWin.y = Mathf.RoundToInt(yy); + AddChild(_tooltipWin); + } + + /// + /// + /// + public void HideTooltips() + { + if (_tooltipWin != null) + { + if (_tooltipWin.parent != null) + RemoveChild(_tooltipWin); + _tooltipWin = null; + } + } + + /// + /// + /// + public GObject focus + { + get + { + GObject obj = DisplayObjectToGObject(Stage.inst.focus); + if (obj != null && !IsAncestorOf(obj)) + return null; + else + return obj; + } + + set + { + if (value == null) + Stage.inst.focus = null; + else + Stage.inst.focus = value.displayObject; + } + } + + void __stageTouchBegin(EventContext context) + { + if (_tooltipWin != null) + HideTooltips(); + + CheckPopups(true); + } + + void __stageTouchEnd(EventContext context) + { + CheckPopups(false); + } + + void CheckPopups(bool touchBegin) + { + if (touchBegin) + _justClosedPopups.Clear(); + + if (_popupStack.Count > 0) + { + DisplayObject mc = Stage.inst.touchTarget as DisplayObject; + bool handled = false; + while (mc != Stage.inst && mc != null) + { + if (mc.gOwner != null) + { + int k = _popupStack.IndexOf(mc.gOwner); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i > k; i--) + { + int last = _popupStack.Count - 1; + GObject popup = _popupStack[last]; + if (touchBegin == _specialPopups.Contains(popup)) + continue; + + ClosePopup(popup); + _justClosedPopups.Add(popup); + _popupStack.RemoveAt(last); + _specialPopups.Remove(popup); + } + + handled = true; + break; + } + } + + mc = mc.parent; + } + + if (!handled) + { + for (int i = _popupStack.Count - 1; i >= 0; i--) + { + GObject popup = _popupStack[i]; + if (touchBegin == _specialPopups.Contains(popup)) + continue; + + ClosePopup(popup); + _justClosedPopups.Add(popup); + _popupStack.RemoveAt(i); + _specialPopups.Remove(popup); + } + } + } + } + + /// + /// + /// + public void EnableSound() + { + Stage.inst.EnableSound(); + } + + /// + /// + /// + public void DisableSound() + { + Stage.inst.DisableSound(); + } + + /// + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip, float volumeScale) + { + Stage.inst.PlayOneShotSound(clip, volumeScale); + } + + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip) + { + Stage.inst.PlayOneShotSound(clip); + } + + /// + /// + /// + public float soundVolume + { + get { return Stage.inst.soundVolume; } + set { Stage.inst.soundVolume = value; } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs.meta new file mode 100644 index 0000000..998aa8c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GRoot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c82e50658ca58b2459448b9c86cb4777 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs new file mode 100644 index 0000000..db4f157 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs @@ -0,0 +1,226 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GScrollBar class. + /// + public class GScrollBar : GComponent + { + GObject _grip; + GObject _arrowButton1; + GObject _arrowButton2; + GObject _bar; + ScrollPane _target; + + bool _vertical; + float _scrollPerc; + bool _fixedGripSize; + bool _gripDragging; + + Vector2 _dragOffset; + + public GScrollBar() + { + _scrollPerc = 0; + } + + /// + /// + /// + /// + /// + public void SetScrollPane(ScrollPane target, bool vertical) + { + _target = target; + _vertical = vertical; + } + + /// + /// + /// + public void SetDisplayPerc(float value) + { + if (_vertical) + { + if (!_fixedGripSize) + _grip.height = Mathf.FloorToInt(value * _bar.height); + _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); + } + else + { + if (!_fixedGripSize) + _grip.width = Mathf.FloorToInt(value * _bar.width); + _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); + } + + _grip.visible = value != 0 && value != 1; + } + + /// + /// + /// + public void setScrollPerc(float value) + { + _scrollPerc = value; + if (_vertical) + _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); + else + _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); + } + + /// + /// + /// + public float minSize + { + get + { + if (_vertical) + return (_arrowButton1 != null ? _arrowButton1.height : 0) + (_arrowButton2 != null ? _arrowButton2.height : 0); + else + return (_arrowButton1 != null ? _arrowButton1.width : 0) + (_arrowButton2 != null ? _arrowButton2.width : 0); + } + } + + /// + /// + /// + public bool gripDragging + { + get + { + return _gripDragging; + } + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _fixedGripSize = buffer.ReadBool(); + + _grip = GetChild("grip"); + if (_grip == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define grip"); + return; + } + + _bar = GetChild("bar"); + if (_bar == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define bar"); + return; + } + + _arrowButton1 = GetChild("arrow1"); + _arrowButton2 = GetChild("arrow2"); + + _grip.onTouchBegin.Add(__gripTouchBegin); + _grip.onTouchMove.Add(__gripTouchMove); + _grip.onTouchEnd.Add(__gripTouchEnd); + + this.onTouchBegin.Add(__touchBegin); + if (_arrowButton1 != null) + _arrowButton1.onTouchBegin.Add(__arrowButton1Click); + if (_arrowButton2 != null) + _arrowButton2.onTouchBegin.Add(__arrowButton2Click); + } + + void __gripTouchBegin(EventContext context) + { + if (_bar == null) + return; + + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + _gripDragging = true; + _target.UpdateScrollBarVisible(); + + _dragOffset = this.GlobalToLocal(new Vector2(evt.x, evt.y)) - _grip.xy; + } + + void __gripTouchMove(EventContext context) + { + InputEvent evt = context.inputEvent; + Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (float.IsNaN(pt.x)) + return; + + if (_vertical) + { + float curY = pt.y - _dragOffset.y; + float diff = _bar.height - _grip.height; + if (diff == 0) + _target.percY = 0; + else + _target.percY = (curY - _bar.y) / diff; + } + else + { + float curX = pt.x - _dragOffset.x; + float diff = _bar.width - _grip.width; + if (diff == 0) + _target.percX = 0; + else + _target.percX = (curX - _bar.x) / diff; + } + } + + void __gripTouchEnd(EventContext context) + { + _gripDragging = false; + _target.UpdateScrollBarVisible(); + } + + void __arrowButton1Click(EventContext context) + { + context.StopPropagation(); + + if (_vertical) + _target.ScrollUp(); + else + _target.ScrollLeft(); + } + + void __arrowButton2Click(EventContext context) + { + context.StopPropagation(); + + if (_vertical) + _target.ScrollDown(); + else + _target.ScrollRight(); + } + + void __touchBegin(EventContext context) + { + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + Vector2 pt = _grip.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (_vertical) + { + if (pt.y < 0) + _target.ScrollUp(4, false); + else + _target.ScrollDown(4, false); + } + else + { + if (pt.x < 0) + _target.ScrollLeft(4, false); + else + _target.ScrollRight(4, false); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs.meta new file mode 100644 index 0000000..826aac1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GScrollBar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6b0ce43cdb60cf4e8e1ddccdf2f5082 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs new file mode 100644 index 0000000..e313d59 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs @@ -0,0 +1,405 @@ +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class GSlider : GComponent + { + double _min; + double _max; + double _value; + ProgressTitleType _titleType; + bool _reverse; + bool _wholeNumbers; + + GObject _titleObject; + GObject _barObjectH; + GObject _barObjectV; + float _barMaxWidth; + float _barMaxHeight; + float _barMaxWidthDelta; + float _barMaxHeightDelta; + GObject _gripObject; + Vector2 _clickPos; + float _clickPercent; + float _barStartX; + float _barStartY; + + EventListener _onChanged; + EventListener _onGripTouchEnd; + + public bool changeOnClick; + public bool canDrag; + + public GSlider() + { + _value = 50; + _max = 100; + changeOnClick = true; + canDrag = true; + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onGripTouchEnd + { + get { return _onGripTouchEnd ?? (_onGripTouchEnd = new EventListener(this, "onGripTouchEnd")); } + } + + /// + /// + /// + public ProgressTitleType titleType + { + get + { + return _titleType; + } + set + { + if (_titleType != value) + { + _titleType = value; + Update(); + } + } + } + + /// + /// + /// + public double min + { + get + { + return _min; + } + set + { + if (_min != value) + { + _min = value; + Update(); + } + } + } + + /// + /// + /// + public double max + { + get + { + return _max; + } + set + { + if (_max != value) + { + _max = value; + Update(); + } + } + } + + /// + /// + /// + public double value + { + get + { + return _value; + } + set + { + if (_value != value) + { + _value = value; + Update(); + } + } + } + + /// + /// + /// + public bool wholeNumbers + { + get + { + return _wholeNumbers; + } + set + { + if (_wholeNumbers != value) + { + _wholeNumbers = value; + Update(); + } + } + } + + private void Update() + { + UpdateWithPercent((float)((_value - _min) / (_max - _min)), false); + } + + private void UpdateWithPercent(float percent, bool manual) + { + percent = Mathf.Clamp01(percent); + if (manual) + { + double newValue = _min + (_max - _min) * percent; + if (newValue < _min) + newValue = _min; + if (newValue > _max) + newValue = _max; + if (_wholeNumbers) + { + newValue = Math.Round(newValue); + percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); + } + + if (newValue != _value) + { + _value = newValue; + if (DispatchEvent("onChanged", null)) + return; + } + } + + if (_titleObject != null) + { + switch (_titleType) + { + case ProgressTitleType.Percent: + _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; + break; + + case ProgressTitleType.ValueAndMax: + _titleObject.text = Math.Round(_value) + "/" + Math.Round(max); + break; + + case ProgressTitleType.Value: + _titleObject.text = "" + Math.Round(_value); + break; + + case ProgressTitleType.Max: + _titleObject.text = "" + Math.Round(_max); + break; + } + } + + float fullWidth = this.width - _barMaxWidthDelta; + float fullHeight = this.height - _barMaxHeightDelta; + if (!_reverse) + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, percent)) + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, percent)) + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + } + } + else + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, 1 - percent)) + { + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); + } + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, 1 - percent)) + { + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); + } + } + } + + InvalidateBatchingState(true); + } + + bool SetFillAmount(GObject bar, float amount) + { + if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) + ((GImage)bar).fillAmount = amount; + else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) + ((GLoader)bar).fillAmount = amount; + else + return false; + + return true; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _titleType = (ProgressTitleType)buffer.ReadByte(); + _reverse = buffer.ReadBool(); + if (buffer.version >= 2) + { + _wholeNumbers = buffer.ReadBool(); + this.changeOnClick = buffer.ReadBool(); + } + + _titleObject = GetChild("title"); + _barObjectH = GetChild("bar"); + _barObjectV = GetChild("bar_v"); + _gripObject = GetChild("grip"); + + if (_barObjectH != null) + { + _barMaxWidth = _barObjectH.width; + _barMaxWidthDelta = this.width - _barMaxWidth; + _barStartX = _barObjectH.x; + } + if (_barObjectV != null) + { + _barMaxHeight = _barObjectV.height; + _barMaxHeightDelta = this.height - _barMaxHeight; + _barStartY = _barObjectV.y; + } + + if (_gripObject != null) + { + _gripObject.onTouchBegin.Add(__gripTouchBegin); + _gripObject.onTouchMove.Add(__gripTouchMove); + _gripObject.onTouchEnd.Add(__gripTouchEnd); + } + + onTouchBegin.Add(__barTouchBegin); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + { + Update(); + return; + } + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + { + Update(); + return; + } + + _value = buffer.ReadInt(); + _max = buffer.ReadInt(); + if (buffer.version >= 2) + _min = buffer.ReadInt(); + + + Update(); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (_barObjectH != null) + _barMaxWidth = this.width - _barMaxWidthDelta; + if (_barObjectV != null) + _barMaxHeight = this.height - _barMaxHeightDelta; + + if (!this.underConstruct) + Update(); + } + + private void __gripTouchBegin(EventContext context) + { + this.canDrag = true; + + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + _clickPos = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + _clickPercent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); + } + + private void __gripTouchMove(EventContext context) + { + if (!this.canDrag) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (float.IsNaN(pt.x)) + return; + + float deltaX = pt.x - _clickPos.x; + float deltaY = pt.y - _clickPos.y; + if (_reverse) + { + deltaX = -deltaX; + deltaY = -deltaY; + } + + float percent; + if (_barObjectH != null) + percent = _clickPercent + deltaX / _barMaxWidth; + else + percent = _clickPercent + deltaY / _barMaxHeight; + + UpdateWithPercent(percent, true); + } + + private void __gripTouchEnd(EventContext context) + { + DispatchEvent("onGripTouchEnd", null); + } + + private void __barTouchBegin(EventContext context) + { + if (!changeOnClick) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = _gripObject.GlobalToLocal(new Vector2(evt.x, evt.y)); + float percent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); + float delta = 0; + if (_barObjectH != null) + delta = (pt.x - _gripObject.width / 2) / _barMaxWidth; + if (_barObjectV != null) + delta = (pt.y - _gripObject.height / 2) / _barMaxHeight; + if (_reverse) + percent -= delta; + else + percent += delta; + + UpdateWithPercent(percent, true); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs.meta new file mode 100644 index 0000000..33e1060 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GSlider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2a1a4a3ec0a296489e15eb1ae1214ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs new file mode 100644 index 0000000..1c21e9b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs @@ -0,0 +1,505 @@ +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class GTextField : GObject, ITextColorGear + { + // [Y 修改] + public bool Ex_IsAutoMultiLang { private set; get; } + + // [Y 修改] + public int Ex_ControllerSelectedIndex { private set; get; } + + protected TextField _textField; + protected string _text; + protected bool _ubbEnabled; + protected bool _updatingSize; + protected Dictionary _templateVars; + + public GTextField() + : base() + { + TextFormat tf = _textField.textFormat; + tf.font = UIConfig.defaultFont; + tf.size = 12; + tf.color = Color.black; + tf.lineSpacing = 3; + tf.letterSpacing = 0; + _textField.textFormat = tf; + + _text = string.Empty; + _textField.autoSize = AutoSizeType.Both; + _textField.wordWrap = false; + + // [Y 修改] + Ex_IsAutoMultiLang = true; + } + + override protected void CreateDisplayObject() + { + _textField = new TextField(); + _textField.gOwner = this; + displayObject = _textField; + } + + /// + /// [Y 修改] + /// + public void SetText(object setText) + { + if (Ex_IsAutoMultiLang) + { + Ex_IsAutoMultiLang = false; + } + + if (setText != null) + { + text = setText.ToString(); + return; + } + + text = string.Empty; + } + + /// + /// [Y 修改] + /// + public void SetText(string setText) + { + if (Ex_IsAutoMultiLang) + { + Ex_IsAutoMultiLang = false; + } + + if (setText != null) + { + text = setText; + return; + } + + text = string.Empty; + } + + /// + /// [Y 修改] + /// + public override string inText + { + get + { + if (this is GTextInput) + _text = ((GTextInput)this).inputTextField.text; + return _text; + } + set + { + if (Ex_IsAutoMultiLang) + { + Ex_IsAutoMultiLang = false; + } + + if (value == null) + value = string.Empty; + _text = value; + SetTextFieldText(); + UpdateSize(); + UpdateGear(6); + } + } + + /// + /// + /// + override public string text + { + get + { + if (this is GTextInput) + _text = ((GTextInput)this).inputTextField.text; + return _text; + } + set + { + if (value == null) + value = string.Empty; + _text = value; + SetTextFieldText(); + UpdateSize(); + UpdateGear(6); + } + } + + virtual protected void SetTextFieldText() + { + string str = _text; + if (_templateVars != null) + str = ParseTemplate(str); + + _textField.maxWidth = maxWidth; + if (_ubbEnabled) + _textField.htmlText = UBBParser.inst.Parse(XMLUtils.EncodeString(str)); + else + _textField.text = str; + } + + /// + /// + /// + public Dictionary templateVars + { + get { return _templateVars; } + set + { + if (_templateVars == null && value == null) + return; + + _templateVars = value; + + FlushVars(); + } + } + + /// + /// + /// + /// + /// + /// + public GTextField SetVar(string name, string value) + { + if (_templateVars == null) + _templateVars = new Dictionary(); + _templateVars[name] = value; + + return this; + } + + /// + /// + /// + public void FlushVars() + { + SetTextFieldText(); + UpdateSize(); + } + + /// + /// + /// + public bool HasCharacter(char ch) + { + return _textField.HasCharacter(ch); + } + + protected string ParseTemplate(string template) + { + int pos1 = 0, pos2 = 0; + int pos3; + string tag; + string value; + StringBuilder buffer = new StringBuilder(); + + while ((pos2 = template.IndexOf('{', pos1)) != -1) + { + if (pos2 > 0 && template[pos2 - 1] == '\\') + { + buffer.Append(template, pos1, pos2 - pos1 - 1); + buffer.Append('{'); + pos1 = pos2 + 1; + continue; + } + + buffer.Append(template, pos1, pos2 - pos1); + pos1 = pos2; + pos2 = template.IndexOf('}', pos1); + if (pos2 == -1) + break; + + if (pos2 == pos1 + 1) + { + buffer.Append(template, pos1, 2); + pos1 = pos2 + 1; + continue; + } + + tag = template.Substring(pos1 + 1, pos2 - pos1 - 1); + pos3 = tag.IndexOf('='); + if (pos3 != -1) + { + if (!_templateVars.TryGetValue(tag.Substring(0, pos3), out value)) + value = tag.Substring(pos3 + 1); + } + else + { + if (!_templateVars.TryGetValue(tag, out value)) + value = ""; + } + + buffer.Append(value); + pos1 = pos2 + 1; + } + + if (pos1 < template.Length) + buffer.Append(template, pos1, template.Length - pos1); + + return buffer.ToString(); + } + + /// + /// + /// + public TextFormat textFormat + { + get { return _textField.textFormat; } + set + { + _textField.textFormat = value; + if (!underConstruct) + UpdateSize(); + } + } + + /// + /// + /// + public Color color + { + get { return _textField.textFormat.color; } + set + { + if (_textField.textFormat.color != value) + { + TextFormat tf = _textField.textFormat; + tf.color = value; + _textField.textFormat = tf; + UpdateGear(4); + } + } + } + + /// + /// + /// + public AlignType align + { + get { return _textField.align; } + set { _textField.align = value; } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _textField.verticalAlign; } + set { _textField.verticalAlign = value; } + } + + /// + /// + /// + public bool singleLine + { + get { return _textField.singleLine; } + set { _textField.singleLine = value; } + } + + /// + /// + /// + public float stroke + { + get { return _textField.stroke; } + set { _textField.stroke = value; } + } + + /// + /// + /// + public Color strokeColor + { + get { return _textField.strokeColor; } + set + { + _textField.strokeColor = value; + UpdateGear(4); + } + } + + /// + /// + /// + public Vector2 shadowOffset + { + get { return _textField.shadowOffset; } + set { _textField.shadowOffset = value; } + } + + /// + /// + /// + public bool UBBEnabled + { + get { return _ubbEnabled; } + set { _ubbEnabled = value; } + } + + /// + /// + /// + public AutoSizeType autoSize + { + get { return _textField.autoSize; } + set + { + _textField.autoSize = value; + if (value == AutoSizeType.Both) + { + _textField.wordWrap = false; + + if (!underConstruct) + this.SetSize(_textField.textWidth, _textField.textHeight); + } + else + { + _textField.wordWrap = true; + + if (value == AutoSizeType.Height) + { + if (!underConstruct) + { + displayObject.width = this.width; + this.height = _textField.textHeight; + } + } + else + displayObject.SetSize(this.width, this.height); + } + } + } + + /// + /// + /// + public float textWidth + { + get { return _textField.textWidth; } + } + + /// + /// + /// + public float textHeight + { + get { return _textField.textHeight; } + } + + protected void UpdateSize() + { + if (_updatingSize) + return; + + _updatingSize = true; + + if (_textField.autoSize == AutoSizeType.Both) + { + this.size = displayObject.size; + InvalidateBatchingState(); + } + else if (_textField.autoSize == AutoSizeType.Height) + { + this.height = displayObject.height; + InvalidateBatchingState(); + } + + _updatingSize = false; + } + + protected override void HandleSizeChanged() + { + if (_updatingSize) + return; + + if (underConstruct) + displayObject.SetSize(this.width, this.height); + else if (_textField.autoSize != AutoSizeType.Both) + { + if (_textField.autoSize == AutoSizeType.Height) + { + // 先调整宽度,让文本重排 + displayObject.width = this.width; + // 文本为空时,1是本来就不需要调整, 2是为了防止改掉文本为空时的默认高度,造成关联错误 + if (_text != string.Empty) + { + SetSizeDirectly(this.width, displayObject.height); + } + } + else + displayObject.SetSize(this.width, this.height); + } + } + + public override void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + TextFormat tf = _textField.textFormat; + + tf.font = buffer.ReadS(); + tf.size = buffer.ReadShort(); + tf.color = buffer.ReadColor(); + this.align = (AlignType)buffer.ReadByte(); + this.verticalAlign = (VertAlignType)buffer.ReadByte(); + tf.lineSpacing = buffer.ReadShort(); + tf.letterSpacing = buffer.ReadShort(); + _ubbEnabled = buffer.ReadBool(); + this.autoSize = (AutoSizeType)buffer.ReadByte(); + tf.underline = buffer.ReadBool(); + tf.italic = buffer.ReadBool(); + tf.bold = buffer.ReadBool(); + this.singleLine = buffer.ReadBool(); + if (buffer.ReadBool()) + { + tf.outlineColor = buffer.ReadColor(); + tf.outline = buffer.ReadFloat(); + } + + if (buffer.ReadBool()) + { + tf.shadowColor = buffer.ReadColor(); + float f1 = buffer.ReadFloat(); + float f2 = buffer.ReadFloat(); + tf.shadowOffset = new Vector2(f1, f2); + } + + if (buffer.ReadBool()) + _templateVars = new Dictionary(); + + if (buffer.version >= 3) + { + tf.strikethrough = buffer.ReadBool(); + } + + _textField.textFormat = tf; + } + + public override void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 6); + + string str = buffer.ReadS(); + if (str != null) + this.text = str; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs.meta new file mode 100644 index 0000000..e5e602c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextField.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d64856957bd90d24aa05d134fb14e01d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs new file mode 100644 index 0000000..323fd73 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs @@ -0,0 +1,243 @@ +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class GTextInput : GTextField + { + /// + /// + /// + public InputTextField inputTextField { get; private set; } + + EventListener _onChanged; + EventListener _onSubmit; + + public GTextInput() + { + _textField.autoSize = AutoSizeType.None; + _textField.wordWrap = false; + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onSubmit + { + get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } + } + + /// + /// + /// + public bool editable + { + get { return inputTextField.editable; } + set { inputTextField.editable = value; } + } + + /// + /// + /// + public bool hideInput + { + get { return inputTextField.hideInput; } + set { inputTextField.hideInput = value; } + } + + /// + /// + /// + public int maxLength + { + get { return inputTextField.maxLength; } + set { inputTextField.maxLength = value; } + } + + /// + /// + /// + public string restrict + { + get { return inputTextField.restrict; } + set { inputTextField.restrict = value; } + } + + /// + /// + /// + public bool displayAsPassword + { + get { return inputTextField.displayAsPassword; } + set { inputTextField.displayAsPassword = value; } + } + + /// + /// + /// + public int caretPosition + { + get { return inputTextField.caretPosition; } + set { inputTextField.caretPosition = value; } + } + + /// + /// + /// + public string promptText + { + get { return inputTextField.promptText; } + set { inputTextField.promptText = value; } + } + + /// + /// 在移动设备上是否使用键盘输入。如果false,则文本在获得焦点后不会弹出键盘。 + /// + public bool keyboardInput + { + get { return inputTextField.keyboardInput; } + set { inputTextField.keyboardInput = value; } + } + + /// + /// + /// + public int keyboardType + { + get { return inputTextField.keyboardType; } + set { inputTextField.keyboardType = value; } + } + + /// + /// + /// + public bool disableIME + { + get { return inputTextField.disableIME; } + set { inputTextField.disableIME = value; } + } + + /// + /// + /// + public Dictionary emojies + { + get { return inputTextField.emojies; } + set { inputTextField.emojies = value; } + } + + /// + /// + /// + public int border + { + get { return inputTextField.border; } + set { inputTextField.border = value; } + } + + /// + /// + /// + public int corner + { + get { return inputTextField.corner; } + set { inputTextField.corner = value; } + } + + /// + /// + /// + public Color borderColor + { + get { return inputTextField.borderColor; } + set { inputTextField.borderColor = value; } + } + + /// + /// + /// + public Color backgroundColor + { + get { return inputTextField.backgroundColor; } + set { inputTextField.backgroundColor = value; } + } + + /// + /// + /// + public bool mouseWheelEnabled + { + get { return inputTextField.mouseWheelEnabled; } + set { inputTextField.mouseWheelEnabled = value; } + } + + /// + /// + /// + /// + /// + public void SetSelection(int start, int length) + { + inputTextField.SetSelection(start, length); + } + + /// + /// + /// + /// + public void ReplaceSelection(string value) + { + inputTextField.ReplaceSelection(value); + } + + override protected void SetTextFieldText() + { + inputTextField.text = _text; + } + + override protected void CreateDisplayObject() + { + inputTextField = new InputTextField(); + inputTextField.gOwner = this; + displayObject = inputTextField; + + _textField = inputTextField.textField; + } + + public override void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 4); + + string str = buffer.ReadS(); + if (str != null) + inputTextField.promptText = str; + + str = buffer.ReadS(); + if (str != null) + inputTextField.restrict = str; + + int iv = buffer.ReadInt(); + if (iv != 0) + inputTextField.maxLength = iv; + iv = buffer.ReadInt(); + if (iv != 0) + inputTextField.keyboardType = iv; + if (buffer.ReadBool()) + inputTextField.displayAsPassword = true; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs.meta new file mode 100644 index 0000000..3e66238 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTextInput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e6f98107e4db9142b9de3358cf95378 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs new file mode 100644 index 0000000..de45629 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class GTree : GList + { + public delegate void TreeNodeRenderDelegate(GTreeNode node, GComponent obj); + public delegate void TreeNodeWillExpandDelegate(GTreeNode node, bool expand); + + /// + /// 当TreeNode需要更新时回调 + /// + public TreeNodeRenderDelegate treeNodeRender; + + /// + /// 当TreeNode即将展开或者收缩时回调。可以在回调中动态增加子节点。 + /// + public TreeNodeWillExpandDelegate treeNodeWillExpand; + + int _indent; + GTreeNode _rootNode; + int _clickToExpand; + bool _expandedStatusInEvt; + + private static List helperIntList = new List(); + + /// + /// + /// + public GTree() + { + _indent = 30; + + _rootNode = new GTreeNode(true); + _rootNode._SetTree(this); + _rootNode.expanded = true; + + } + + /// + /// TreeView的顶层节点,这是个虚拟节点,也就是他不会显示出来。 + /// + public GTreeNode rootNode + { + get { return _rootNode; } + } + + /// + /// TreeView每级的缩进,单位像素。 + /// + public int indent + { + get { return _indent; } + set { _indent = value; } + } + + /// + /// + /// + public int clickToExpand + { + get { return _clickToExpand; } + set { _clickToExpand = value; } + } + + /// + /// + /// + /// + public GTreeNode GetSelectedNode() + { + int i = this.selectedIndex; + if (i != -1) + return (GTreeNode)this.GetChildAt(i)._treeNode; + else + return null; + } + + /// + /// + /// + /// + public List GetSelectedNodes() + { + return GetSelectedNodes(null); + } + + /// + /// + /// + /// + /// + public List GetSelectedNodes(List result) + { + if (result == null) + result = new List(); + helperIntList.Clear(); + List sels = GetSelection(helperIntList); + int cnt = sels.Count; + for (int i = 0; i < cnt; i++) + { + GTreeNode node = GetChildAt(sels[i])._treeNode; + result.Add(node); + } + return result; + } + /// + /// + /// + /// + public void SelectNode(GTreeNode node) + { + SelectNode(node, false); + } + + /// + /// + /// + /// + /// + public void SelectNode(GTreeNode node, bool scrollItToView) + { + GTreeNode parentNode = node.parent; + while (parentNode != null && parentNode != _rootNode) + { + parentNode.expanded = true; + parentNode = parentNode.parent; + } + AddSelection(GetChildIndex(node.cell), scrollItToView); + } + + /// + /// + /// + /// + public void UnselectNode(GTreeNode node) + { + RemoveSelection(GetChildIndex(node.cell)); + } + + /// + /// + /// + public void ExpandAll() + { + ExpandAll(_rootNode); + } + + /// + /// + /// + /// + public void ExpandAll(GTreeNode folderNode) + { + folderNode.expanded = true; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + GTreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + ExpandAll(node); + } + } + + /// + /// + /// + /// + public void CollapseAll() + { + CollapseAll(_rootNode); + } + + /// + /// + /// + /// + public void CollapseAll(GTreeNode folderNode) + { + if (folderNode != _rootNode) + folderNode.expanded = false; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + GTreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + CollapseAll(node); + } + } + + /// + /// + /// + /// + void CreateCell(GTreeNode node) + { + GComponent child = itemPool.GetObject(string.IsNullOrEmpty(node._resURL) ? this.defaultItem : node._resURL) as GComponent; + if (child == null) + throw new Exception("FairyGUI: cannot create tree node object."); + child.displayObject.home = this.displayObject.cachedTransform; + child._treeNode = node; + node._cell = child; + + GObject indentObj = node.cell.GetChild("indent"); + if (indentObj != null) + indentObj.width = (node.level - 1) * indent; + + Controller cc; + + cc = child.GetController("expanded"); + if (cc != null) + { + cc.onChanged.Add(__expandedStateChanged); + cc.selectedIndex = node.expanded ? 1 : 0; + } + + cc = child.GetController("leaf"); + if (cc != null) + cc.selectedIndex = node.isFolder ? 0 : 1; + + if (node.isFolder) + child.onTouchBegin.Add(__cellTouchBegin); + + if (treeNodeRender != null) + treeNodeRender(node, node._cell); + } + + /// + /// + /// + /// + internal void _AfterInserted(GTreeNode node) + { + if (node._cell == null) + CreateCell(node); + + int index = GetInsertIndexForNode(node); + AddChildAt(node.cell, index); + if (treeNodeRender != null) + treeNodeRender(node, node._cell); + + if (node.isFolder && node.expanded) + CheckChildren(node, index); + } + + /// + /// + /// + /// + /// + int GetInsertIndexForNode(GTreeNode node) + { + GTreeNode prevNode = node.GetPrevSibling(); + if (prevNode == null) + prevNode = node.parent; + int insertIndex = GetChildIndex(prevNode.cell) + 1; + int myLevel = node.level; + int cnt = this.numChildren; + for (int i = insertIndex; i < cnt; i++) + { + GTreeNode testNode = GetChildAt(i)._treeNode; + if (testNode.level <= myLevel) + break; + + insertIndex++; + } + + return insertIndex; + } + + /// + /// + /// + /// + internal void _AfterRemoved(GTreeNode node) + { + RemoveNode(node); + } + + /// + /// + /// + /// + internal void _AfterExpanded(GTreeNode node) + { + if (node == _rootNode) + { + CheckChildren(_rootNode, 0); + return; + } + + if (this.treeNodeWillExpand != null) + this.treeNodeWillExpand(node, true); + + if (node._cell == null) + return; + + if (this.treeNodeRender != null) + this.treeNodeRender(node, node._cell); + + Controller cc = node._cell.GetController("expanded"); + if (cc != null) + cc.selectedIndex = 1; + + if (node._cell.parent != null) + CheckChildren(node, GetChildIndex(node._cell)); + } + + /// + /// + /// + /// + internal void _AfterCollapsed(GTreeNode node) + { + if (node == _rootNode) + { + CheckChildren(_rootNode, 0); + return; + } + + if (this.treeNodeWillExpand != null) + this.treeNodeWillExpand(node, false); + + if (node._cell == null) + return; + + if (this.treeNodeRender != null) + this.treeNodeRender(node, node._cell); + + Controller cc = node._cell.GetController("expanded"); + if (cc != null) + cc.selectedIndex = 0; + + if (node._cell.parent != null) + HideFolderNode(node); + } + + /// + /// + /// + /// + internal void _AfterMoved(GTreeNode node) + { + int startIndex = GetChildIndex(node._cell); + int endIndex; + if (node.isFolder) + endIndex = GetFolderEndIndex(startIndex, node.level); + else + endIndex = startIndex + 1; + int insertIndex = GetInsertIndexForNode(node); + int cnt = endIndex - startIndex; + + if (insertIndex < startIndex) + { + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(startIndex + i); + SetChildIndex(obj, insertIndex + i); + } + } + else + { + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(startIndex); + SetChildIndex(obj, insertIndex); + } + } + } + + private int GetFolderEndIndex(int startIndex, int level) + { + int cnt = this.numChildren; + for (int i = startIndex + 1; i < cnt; i++) + { + GTreeNode node = GetChildAt(i)._treeNode; + if (node.level <= level) + return i; + } + + return cnt; + } + + /// + /// + /// + /// + /// + /// + int CheckChildren(GTreeNode folderNode, int index) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + index++; + GTreeNode node = folderNode.GetChildAt(i); + if (node.cell == null) + CreateCell(node); + + if (node.cell.parent == null) + AddChildAt(node.cell, index); + + if (node.isFolder && node.expanded) + index = CheckChildren(node, index); + } + + return index; + } + + /// + /// + /// + /// + void HideFolderNode(GTreeNode folderNode) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + GTreeNode node = folderNode.GetChildAt(i); + if (node.cell != null && node.cell.parent != null) + RemoveChild(node.cell); + + if (node.isFolder && node.expanded) + HideFolderNode(node); + } + } + + /// + /// + /// + /// + void RemoveNode(GTreeNode node) + { + if (node.cell != null) + { + if (node.cell.parent != null) + RemoveChild(node.cell); + itemPool.ReturnObject(node.cell); + node._cell._treeNode = null; + node._cell = null; + } + + if (node.isFolder) + { + int cnt = node.numChildren; + for (int i = 0; i < cnt; i++) + { + GTreeNode node2 = node.GetChildAt(i); + RemoveNode(node2); + } + } + } + + void __cellTouchBegin(EventContext context) + { + GTreeNode node = ((GObject)context.sender)._treeNode; + _expandedStatusInEvt = node.expanded; + } + + void __expandedStateChanged(EventContext context) + { + Controller cc = (Controller)context.sender; + GTreeNode node = cc.parent._treeNode; + node.expanded = cc.selectedIndex == 1; + } + + override protected void DispatchItemEvent(GObject item, EventContext context) + { + if (_clickToExpand != 0) + { + GTreeNode node = item._treeNode; + if (node != null && _expandedStatusInEvt == node.expanded) + { + if (_clickToExpand == 2) + { + if (context.inputEvent.isDoubleClick) + node.expanded = !node.expanded; + } + else + node.expanded = !node.expanded; + } + } + + base.DispatchItemEvent(item, context); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 9); + + _indent = buffer.ReadInt(); + _clickToExpand = buffer.ReadByte(); + } + + override protected void ReadItems(ByteBuffer buffer) + { + int nextPos; + string str; + bool isFolder; + GTreeNode lastNode = null; + int level; + int prevLevel = 0; + + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + str = buffer.ReadS(); + if (str == null) + { + str = this.defaultItem; + if (str == null) + { + buffer.position = nextPos; + continue; + } + } + + isFolder = buffer.ReadBool(); + level = buffer.ReadByte(); + + GTreeNode node = new GTreeNode(isFolder, str); + node.expanded = true; + if (i == 0) + _rootNode.AddChild(node); + else + { + if (level > prevLevel) + lastNode.AddChild(node); + else if (level < prevLevel) + { + for (int j = level; j <= prevLevel; j++) + lastNode = lastNode.parent; + lastNode.AddChild(node); + } + else + lastNode.parent.AddChild(node); + } + lastNode = node; + prevLevel = level; + + SetupItem(buffer, node.cell); + + buffer.position = nextPos; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs.meta new file mode 100644 index 0000000..f3872c9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTree.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2d05bd744ca041a8beb8cfd9421d8a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs new file mode 100644 index 0000000..3ac04eb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs @@ -0,0 +1,406 @@ +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + public class GTreeNode + { + /// + /// + /// + public object data; + + /// + /// + /// + public GTreeNode parent { get; private set; } + + /// + /// + /// + public GTree tree { get; private set; } + + List _children; + bool _expanded; + int _level; + internal GComponent _cell; + internal string _resURL; + + /// + /// + /// + /// + public GTreeNode(bool hasChild) : this(hasChild, null) + { + + } + + /// + /// + /// + /// + /// + public GTreeNode(bool hasChild, string resURL) + { + if (hasChild) + _children = new List(); + _resURL = resURL; + } + + /// + /// + /// + public GComponent cell + { + get { return _cell; } + } + + /// + /// + /// + public int level + { + get { return _level; } + } + + /// + /// + /// + public bool expanded + { + get + { + return _expanded; + } + + set + { + if (_children == null) + return; + + if (_expanded != value) + { + _expanded = value; + if (tree != null) + { + if (_expanded) + tree._AfterExpanded(this); + else + tree._AfterCollapsed(this); + } + } + } + } + + /// + /// + /// + public void ExpandToRoot() + { + GTreeNode p = this; + while (p != null) + { + p.expanded = true; + p = p.parent; + } + } + + /// + /// + /// + public bool isFolder + { + get { return _children != null; } + } + + /// + /// + /// + public string text + { + get + { + if (_cell != null) + return _cell.text; + else + return null; + } + + set + { + if (_cell != null) + _cell.text = value; + } + } + + /// + /// + /// + public string icon + { + get + { + if (_cell != null) + return _cell.icon; + else + return null; + } + + set + { + if (_cell != null) + _cell.icon = value; + } + } + + /// + /// + /// + /// + /// + public GTreeNode AddChild(GTreeNode child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// + /// + /// + /// + /// + public GTreeNode AddChildAt(GTreeNode child, int index) + { + if (child == null) + throw new Exception("child is null"); + + int numChildren = _children.Count; + + if (index >= 0 && index <= numChildren) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + if (child.parent != null) + child.parent.RemoveChild(child); + + int cnt = _children.Count; + if (index == cnt) + _children.Add(child); + else + _children.Insert(index, child); + + child.parent = this; + child._level = _level + 1; + child._SetTree(this.tree); + if (tree != null && this == tree.rootNode || _cell != null && _cell.parent != null && _expanded) + tree._AfterInserted(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public GTreeNode RemoveChild(GTreeNode child) + { + int childIndex = _children.IndexOf(child); + if (childIndex != -1) + { + RemoveChildAt(childIndex); + } + return child; + } + + /// + /// + /// + /// + /// + public GTreeNode RemoveChildAt(int index) + { + if (index >= 0 && index < numChildren) + { + GTreeNode child = _children[index]; + _children.RemoveAt(index); + + child.parent = null; + if (tree != null) + { + child._SetTree(null); + tree._AfterRemoved(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public void RemoveChildren(int beginIndex = 0, int endIndex = -1) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex); + } + + /// + /// + /// + /// + /// + public GTreeNode GetChildAt(int index) + { + if (index >= 0 && index < numChildren) + return _children[index]; + else + throw new Exception("Invalid child index"); + } + + /// + /// + /// + /// + /// + public int GetChildIndex(GTreeNode child) + { + return _children.IndexOf(child); + } + + /// + /// + /// + /// + public GTreeNode GetPrevSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i <= 0) + return null; + + return parent._children[i - 1]; + } + + /// + /// + /// + /// + public GTreeNode GetNextSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i < 0 || i >= parent._children.Count - 1) + return null; + + return parent._children[i + 1]; + } + + /// + /// + /// + /// + /// + public void SetChildIndex(GTreeNode child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new Exception("Not a child of this container"); + + int cnt = _children.Count; + if (index < 0) + index = 0; + else if (index > cnt) + index = cnt; + + if (oldIndex == index) + return; + + _children.RemoveAt(oldIndex); + _children.Insert(index, child); + if (tree != null && this == tree.rootNode || _cell != null && _cell.parent != null && _expanded) + tree._AfterMoved(child); + } + + /// + /// + /// + /// + /// + public void SwapChildren(GTreeNode child1, GTreeNode child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// + /// + /// + /// + public void SwapChildrenAt(int index1, int index2) + { + GTreeNode child1 = _children[index1]; + GTreeNode child2 = _children[index2]; + + SetChildIndex(child1, index2); + SetChildIndex(child2, index1); + } + + /// + /// + /// + public int numChildren + { + get { return (null == _children) ? 0 : _children.Count; } + } + + internal void _SetTree(GTree value) + { + tree = value; + if (tree != null && tree.treeNodeWillExpand != null && _expanded) + tree.treeNodeWillExpand(this, true); + + if (_children != null) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GTreeNode node = _children[i]; + node._level = _level + 1; + node._SetTree(value); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs.meta new file mode 100644 index 0000000..f074700 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/GTreeNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0507f7de6e0d34b85853b6a2f591aaf9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears.meta new file mode 100644 index 0000000..8052938 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b22c996c870881c438177e27f3450ac7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs new file mode 100644 index 0000000..a525d7d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearAnimationValue + { + public bool playing; + public int frame; + public string animationName; + public string skinName; + + public GearAnimationValue(bool playing, int frame) + { + this.playing = playing; + this.frame = frame; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearAnimation : GearBase + { + Dictionary _storage; + GearAnimationValue _default; + + public GearAnimation(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearAnimationValue(((IAnimationGear)_owner).playing, ((IAnimationGear)_owner).frame); + if (_owner is GLoader3D) + { + _default.animationName = ((GLoader3D)_owner).animationName; + _default.skinName = ((GLoader3D)_owner).skinName; + } + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearAnimationValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearAnimationValue(false, 0); + _storage[pageId] = gv; + } + + gv.playing = buffer.ReadBool(); + gv.frame = buffer.ReadInt(); + } + + public void AddExtStatus(string pageId, ByteBuffer buffer) + { + GearAnimationValue gv; + if (pageId == null) + gv = _default; + else + gv = _storage[pageId]; + gv.animationName = buffer.ReadS(); + gv.skinName = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + GearAnimationValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + IAnimationGear mc = (IAnimationGear)_owner; + mc.frame = gv.frame; + mc.playing = gv.playing; + if (_owner is GLoader3D) + { + ((GLoader3D)_owner).animationName = gv.animationName; + ((GLoader3D)_owner).skinName = gv.skinName; + } + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + IAnimationGear mc = (IAnimationGear)_owner; + GearAnimationValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearAnimationValue(mc.playing, mc.frame); + else + { + gv.playing = mc.playing; + gv.frame = mc.frame; + } + + if (_owner is GLoader3D) + { + gv.animationName = ((GLoader3D)_owner).animationName; + gv.skinName = ((GLoader3D)_owner).skinName; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs.meta new file mode 100644 index 0000000..2460cca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearAnimation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87e99c1910ca9684d8719dae7bdb7658 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs new file mode 100644 index 0000000..9f10d55 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs @@ -0,0 +1,203 @@ +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + abstract public class GearBase + { + public static bool disableAllTweenEffect = false; + + protected GObject _owner; + protected Controller _controller; + protected GearTweenConfig _tweenConfig; + + public GearBase(GObject owner) + { + _owner = owner; + } + + public void Dispose() + { + if (_tweenConfig != null && _tweenConfig._tweener != null) + { + _tweenConfig._tweener.Kill(); + _tweenConfig._tweener = null; + } + } + + /// + /// Controller object. + /// + public Controller controller + { + get + { + return _controller; + } + + set + { + if (value != _controller) + { + _controller = value; + if (_controller != null) + Init(); + } + } + } + + public GearTweenConfig tweenConfig + { + get + { + if (_tweenConfig == null) + _tweenConfig = new GearTweenConfig(); + return _tweenConfig; + } + } + + public void Setup(ByteBuffer buffer) + { + _controller = _owner.parent.GetControllerAt(buffer.ReadShort()); + Init(); + + int cnt = buffer.ReadShort(); + if (this is GearDisplay) + { + ((GearDisplay)this).pages = buffer.ReadSArray(cnt); + } + else if (this is GearDisplay2) + { + ((GearDisplay2)this).pages = buffer.ReadSArray(cnt); + } + else + { + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + AddStatus(page, buffer); + } + + if (buffer.ReadBool()) + AddStatus(null, buffer); + } + + if (buffer.ReadBool()) + { + _tweenConfig = new GearTweenConfig(); + _tweenConfig.easeType = (EaseType)buffer.ReadByte(); + _tweenConfig.duration = buffer.ReadFloat(); + _tweenConfig.delay = buffer.ReadFloat(); + } + + if (buffer.version >= 2) + { + if (this is GearXY) + { + if (buffer.ReadBool()) + { + ((GearXY)this).positionsInPercent = true; + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + ((GearXY)this).AddExtStatus(page, buffer); + } + + if (buffer.ReadBool()) + ((GearXY)this).AddExtStatus(null, buffer); + } + } + else if (this is GearDisplay2) + ((GearDisplay2)this).condition = buffer.ReadByte(); + } + + if (buffer.version >= 4 && _tweenConfig != null && _tweenConfig.easeType == EaseType.Custom) + { + _tweenConfig.customEase = new CustomEase(); + _tweenConfig.customEase.Create(buffer.ReadPath()); + } + + if (buffer.version >= 6) + { + if (this is GearAnimation) + { + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + ((GearAnimation)this).AddExtStatus(page, buffer); + } + + if (buffer.ReadBool()) + ((GearAnimation)this).AddExtStatus(null, buffer); + } + } + } + + virtual public void UpdateFromRelations(float dx, float dy) + { + } + + abstract protected void AddStatus(string pageId, ByteBuffer buffer); + abstract protected void Init(); + + /// + /// Call when controller active page changed. + /// + abstract public void Apply(); + + /// + /// Call when object's properties changed. + /// + abstract public void UpdateState(); + } + + public class GearTweenConfig + { + /// + /// Use tween to apply change. + /// + public bool tween; + + /// + /// Ease type. + /// + public EaseType easeType; + + /// + /// + /// + public CustomEase customEase; + + /// + /// Tween duration in seconds. + /// + public float duration; + + /// + /// Tween delay in seconds. + /// + public float delay; + + internal uint _displayLockToken; + internal GTweener _tweener; + + public GearTweenConfig() + { + tween = true; + easeType = EaseType.QuadOut; + duration = 0.3f; + delay = 0; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs.meta new file mode 100644 index 0000000..99f7766 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2050e67af29d06a44834f7ffbfe14e83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs new file mode 100644 index 0000000..3be167f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs @@ -0,0 +1,142 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearColorValue + { + public Color color; + public Color strokeColor; + + public GearColorValue() + { + } + + public GearColorValue(Color color, Color strokeColor) + { + this.color = color; + this.strokeColor = strokeColor; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearColor : GearBase, ITweenListener + { + Dictionary _storage; + GearColorValue _default; + + public GearColor(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearColorValue(); + _default.color = ((IColorGear)_owner).color; + if (_owner is ITextColorGear) + _default.strokeColor = ((ITextColorGear)_owner).strokeColor; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearColorValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearColorValue(Color.black, Color.black); + _storage[pageId] = gv; + } + + gv.color = buffer.ReadColor(); + gv.strokeColor = buffer.ReadColor(); + } + + override public void Apply() + { + GearColorValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) + { + _owner._gearLocked = true; + ((ITextColorGear)_owner).strokeColor = gv.strokeColor; + _owner._gearLocked = false; + } + + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.color != gv.color) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + if (((IColorGear)_owner).color != gv.color) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(((IColorGear)_owner).color, gv.color, _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + ((IColorGear)_owner).color = gv.color; + if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) + ((ITextColorGear)_owner).strokeColor = gv.strokeColor; + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + ((IColorGear)_owner).color = tweener.value.color; + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearColorValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearColorValue(); + gv.color = ((IColorGear)_owner).color; + if (_owner is ITextColorGear) + gv.strokeColor = ((ITextColorGear)_owner).strokeColor; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs.meta new file mode 100644 index 0000000..049443c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearColor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4878a5e9a94c1d429c827f93ca3072b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs new file mode 100644 index 0000000..a562c6b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs @@ -0,0 +1,68 @@ +using System; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearDisplay : GearBase + { + /// + /// Pages involed in this gear. + /// + public string[] pages { get; set; } + + int _visible; + uint _displayLockToken; + + public GearDisplay(GObject owner) + : base(owner) + { + _displayLockToken = 1; + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + } + + override protected void Init() + { + pages = null; + } + + override public void Apply() + { + _displayLockToken++; + if (_displayLockToken == 0) + _displayLockToken = 1; + + if (pages == null || pages.Length == 0 + || Array.IndexOf(pages, _controller.selectedPageId) != -1) + _visible = 1; + else + _visible = 0; + } + + override public void UpdateState() + { + } + + public uint AddLock() + { + _visible++; + return _displayLockToken; + } + + public void ReleaseLock(uint token) + { + if (token == _displayLockToken) + _visible--; + } + + public bool connected + { + get { return _controller == null || _visible > 0; } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs.meta new file mode 100644 index 0000000..bb3f45a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f88c3ac62122e7141a5d6c41eb11da27 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs new file mode 100644 index 0000000..8e812d0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs @@ -0,0 +1,55 @@ +using System; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearDisplay2 : GearBase + { + /// + /// Pages involed in this gear. + /// + public string[] pages { get; set; } + public int condition; + + int _visible; + + public GearDisplay2(GObject owner) + : base(owner) + { + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + } + + override protected void Init() + { + pages = null; + } + + override public void Apply() + { + if (pages == null || pages.Length == 0 + || Array.IndexOf(pages, _controller.selectedPageId) != -1) + _visible = 1; + else + _visible = 0; + } + + override public void UpdateState() + { + } + public bool Evaluate(bool connected) + { + bool v = _controller == null || _visible > 0; + if (this.condition == 0) + v = v && connected; + else + v = v || connected; + return v; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs.meta new file mode 100644 index 0000000..a0dbf5e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearDisplay2.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96390d060150348e98dfe41bf7d23f5f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs new file mode 100644 index 0000000..5d6ef05 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearFontSize : GearBase + { + Dictionary _storage; + int _default; + + public GearFontSize(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = ((GTextField)_owner).textFormat.size; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + if (pageId == null) + _default = buffer.ReadInt(); + else + _storage[pageId] = buffer.ReadInt(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + int cv; + if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) + cv = _default; + + TextFormat tf = ((GTextField)_owner).textFormat; + tf.size = cv; + ((GTextField)_owner).textFormat = tf; + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + _storage[_controller.selectedPageId] = ((GTextField)_owner).textFormat.size; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs.meta new file mode 100644 index 0000000..e1ee194 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearFontSize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d3a7b66a83334b44bb8630ecc980a59 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs new file mode 100644 index 0000000..8c6526b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearIcon : GearBase + { + Dictionary _storage; + string _default; + + public GearIcon(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = _owner.icon; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + if (pageId == null) + _default = buffer.ReadS(); + else + _storage[pageId] = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + string cv; + if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) + cv = _default; + + _owner.icon = cv; + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + _storage[_controller.selectedPageId] = _owner.icon; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs.meta new file mode 100644 index 0000000..ee00d36 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearIcon.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 27b2a638ddb815f40994e0477c3ea4c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs new file mode 100644 index 0000000..da0ffa6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs @@ -0,0 +1,152 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearLookValue + { + public float alpha; + public float rotation; + public bool grayed; + public bool touchable; + + public GearLookValue(float alpha, float rotation, bool grayed, bool touchable) + { + this.alpha = alpha; + this.rotation = rotation; + this.grayed = grayed; + this.touchable = touchable; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearLook : GearBase, ITweenListener + { + Dictionary _storage; + GearLookValue _default; + + public GearLook(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearLookValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearLookValue(0, 0, false, false); + _storage[pageId] = gv; + } + + gv.alpha = buffer.ReadFloat(); + gv.rotation = buffer.ReadFloat(); + gv.grayed = buffer.ReadBool(); + gv.touchable = buffer.ReadBool(); + } + + override public void Apply() + { + GearLookValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + _owner._gearLocked = true; + _owner.grayed = gv.grayed; + _owner.touchable = gv.touchable; + _owner._gearLocked = false; + + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != gv.alpha || _tweenConfig._tweener.endValue.y != gv.rotation) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + bool a = gv.alpha != _owner.alpha; + bool b = gv.rotation != _owner.rotation; + if (a || b) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(new Vector2(_owner.alpha, _owner.rotation), new Vector2(gv.alpha, gv.rotation), _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.alpha = gv.alpha; + _owner.rotation = gv.rotation; + _owner.grayed = gv.grayed; + _owner.touchable = gv.touchable; + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + int flag = (int)tweener.userData; + _owner._gearLocked = true; + if ((flag & 1) != 0) + _owner.alpha = tweener.value.x; + if ((flag & 2) != 0) + { + _owner.rotation = tweener.value.y; + _owner.InvalidateBatchingState(); + } + _owner._gearLocked = false; + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearLookValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); + else + { + gv.alpha = _owner.alpha; + gv.rotation = _owner.rotation; + gv.grayed = _owner.grayed; + gv.touchable = _owner.touchable; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs.meta new file mode 100644 index 0000000..49a97c7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearLook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 77704143cdb38714196c9ff520a079f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs new file mode 100644 index 0000000..15312ee --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearSizeValue + { + public float width; + public float height; + public float scaleX; + public float scaleY; + + public GearSizeValue(float width, float height, float scaleX, float scaleY) + { + this.width = width; + this.height = height; + this.scaleX = scaleX; + this.scaleY = scaleY; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearSize : GearBase, ITweenListener + { + Dictionary _storage; + GearSizeValue _default; + + public GearSize(GObject owner) + : base(owner) + { + + } + + protected override void Init() + { + _default = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearSizeValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearSizeValue(0, 0, 1, 1); + _storage[pageId] = gv; + } + + gv.width = buffer.ReadInt(); + gv.height = buffer.ReadInt(); + gv.scaleX = buffer.ReadFloat(); + gv.scaleY = buffer.ReadFloat(); + } + + override public void Apply() + { + GearSizeValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != gv.width || _tweenConfig._tweener.endValue.y != gv.height + || _tweenConfig._tweener.endValue.z != gv.scaleX || _tweenConfig._tweener.endValue.w != gv.scaleY) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + bool a = gv.width != _owner.width || gv.height != _owner.height; + bool b = gv.scaleX != _owner.scaleX || gv.scaleY != _owner.scaleY; + if (a || b) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(new Vector4(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY), + new Vector4(gv.width, gv.height, gv.scaleX, gv.scaleY), _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.SetSize(gv.width, gv.height, _owner.CheckGearController(1, _controller)); + _owner.SetScale(gv.scaleX, gv.scaleY); + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + int flag = (int)tweener.userData; + if ((flag & 1) != 0) + _owner.SetSize(tweener.value.x, tweener.value.y, _owner.CheckGearController(1, _controller)); + if ((flag & 2) != 0) + _owner.SetScale(tweener.value.z, tweener.value.w); + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearSizeValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); + else + { + gv.width = _owner.width; + gv.height = _owner.height; + gv.scaleX = _owner.scaleX; + gv.scaleY = _owner.scaleY; + } + } + + override public void UpdateFromRelations(float dx, float dy) + { + if (_controller != null && _storage != null) + { + foreach (GearSizeValue gv in _storage.Values) + { + gv.width += dx; + gv.height += dy; + } + _default.width += dx; + _default.height += dy; + + UpdateState(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs.meta new file mode 100644 index 0000000..5596497 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearSize.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 254f71ab913968a4e853a99ce79f0266 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs new file mode 100644 index 0000000..9f35dd5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearText : GearBase + { + Dictionary _storage; + string _default; + + public GearText(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = _owner.text; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + if (pageId == null) + _default = buffer.ReadS(); + else + _storage[pageId] = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + string cv; + if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) + cv = _default; + + _owner.text = cv; + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + _storage[_controller.selectedPageId] = _owner.text; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs.meta new file mode 100644 index 0000000..332df8f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearText.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8b20f3a5dd39ec42bed3456334916fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs new file mode 100644 index 0000000..5e0e6c9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs @@ -0,0 +1,177 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearXYValue + { + public float x; + public float y; + public float px; + public float py; + + public GearXYValue(float x = 0, float y = 0, float px = 0, float py = 0) + { + this.x = x; + this.y = y; + this.px = px; + this.py = py; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearXY : GearBase, ITweenListener + { + public bool positionsInPercent; + + Dictionary _storage; + GearXYValue _default; + + public GearXY(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearXYValue(_owner.x, _owner.y, _owner.x / _owner.parent.width, _owner.y / _owner.parent.height); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearXYValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearXYValue(); + _storage[pageId] = gv; + } + + gv.x = buffer.ReadInt(); + gv.y = buffer.ReadInt(); + } + + public void AddExtStatus(string pageId, ByteBuffer buffer) + { + GearXYValue gv; + if (pageId == null) + gv = _default; + else + gv = _storage[pageId]; + gv.px = buffer.ReadFloat(); + gv.py = buffer.ReadFloat(); + } + + override public void Apply() + { + GearXYValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + Vector2 endPos = new Vector2(); + + if (positionsInPercent && _owner.parent != null) + { + endPos.x = gv.px * _owner.parent.width; + endPos.y = gv.py * _owner.parent.height; + } + else + { + endPos.x = gv.x; + endPos.y = gv.y; + } + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != endPos.x || _tweenConfig._tweener.endValue.y != endPos.y) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + Vector2 origin = _owner.xy; + + if (endPos != origin) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(origin, endPos, _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.SetXY(endPos.x, endPos.y); + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + {//nothing + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + _owner.SetXY(tweener.value.x, tweener.value.y); + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearXYValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearXYValue(); + + gv.x = _owner.x; + gv.y = _owner.y; + + gv.px = _owner.x / _owner.parent.width; + gv.py = _owner.y / _owner.parent.height; + + } + + override public void UpdateFromRelations(float dx, float dy) + { + if (_controller != null && _storage != null && !positionsInPercent) + { + foreach (GearXYValue gv in _storage.Values) + { + gv.x += dx; + gv.y += dy; + } + _default.x += dx; + _default.y += dy; + + UpdateState(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs.meta new file mode 100644 index 0000000..b24a769 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/GearXY.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 082a852494dc8b94485733188788d58c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs new file mode 100644 index 0000000..cae623f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs @@ -0,0 +1,35 @@ + +namespace FairyGUI +{ + /// + /// + /// + public interface IAnimationGear + { + /// + /// + /// + bool playing { get; set; } + + /// + /// + /// + int frame { get; set; } + + /// + /// + /// + float timeScale { get; set; } + + /// + /// + /// + bool ignoreEngineTimeScale { get; set; } + + /// + /// + /// + /// + void Advance(float time); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs.meta new file mode 100644 index 0000000..77b476f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IAnimationGear.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d68e5b2a3af5c444689f459a8b265df7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs new file mode 100644 index 0000000..d2e0ece --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public interface IColorGear + { + /// + /// + /// + Color color { get; set; } + } + + /// + /// + /// + public interface ITextColorGear : IColorGear + { + /// + /// + /// + Color strokeColor { get; set; } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs.meta new file mode 100644 index 0000000..6ebcfaf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Gears/IColorGear.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e872cd17b52152a4fa250c830b9bb8cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs new file mode 100644 index 0000000..c08111b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs @@ -0,0 +1,36 @@ + +namespace FairyGUI +{ + /// + /// + /// + public delegate void UILoadCallback(); + + /// + /// + /// + public interface IUISource + { + /// + /// + /// + string fileName { get; set; } + + /// + /// + /// + bool loaded { get; } + + /// + /// + /// + /// + void Load(UILoadCallback callback); + + /// + /// 取消加载 + /// + void Cancel(); + + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs.meta new file mode 100644 index 0000000..c5e2536 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/IUISource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c742c10608d6ac84bb210a9d6abcb05d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs new file mode 100644 index 0000000..0ce0ae7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs @@ -0,0 +1,29 @@ + +namespace FairyGUI +{ + /// + /// + /// + public struct Margin + { + /// + /// + /// + public int left; + + /// + /// + /// + public int right; + + /// + /// + /// + public int top; + + /// + /// + /// + public int bottom; + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs.meta new file mode 100644 index 0000000..5751fa6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Margin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f31f9a61b0590943ac37f1c16ff0dc9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs new file mode 100644 index 0000000..ae7f0a8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs @@ -0,0 +1,85 @@ +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class PackageItem + { + public UIPackage owner; + + public PackageItemType type; + public ObjectType objectType; + + public string id; + public string name; + public int width; + public int height; + public string file; + public bool exported; + public NTexture texture; + public ByteBuffer rawData; + public string[] branches; + public string[] highResolution; + + //image + public Rect? scale9Grid; + public bool scaleByTile; + public int tileGridIndice; + public PixelHitTestData pixelHitTestData; + + //movieclip + public float interval; + public float repeatDelay; + public bool swing; + public MovieClip.Frame[] frames; + + //component + public bool translated; + public UIObjectFactory.GComponentCreator extensionCreator; + + //font + public BitmapFont bitmapFont; + + //sound + public NAudioClip audioClip; + + //spine/dragonbones + public Vector2 skeletonAnchor; + public object skeletonAsset; + + public object Load() + { + return owner.GetItemAsset(this); + } + + public PackageItem getBranch() + { + if (branches != null && owner._branchIndex != -1) + { + string itemId = branches[owner._branchIndex]; + if (itemId != null) + return owner.GetItem(itemId); + } + + return this; + } + + public PackageItem getHighResolution() + { + if (highResolution != null && GRoot.contentScaleLevel > 0) + { + int i = GRoot.contentScaleLevel - 1; + if (i >= highResolution.Length) + i = highResolution.Length - 1; + string itemId = highResolution[i]; + if (itemId != null) + return owner.GetItem(itemId); + } + + return this; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs.meta new file mode 100644 index 0000000..91f31aa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PackageItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: acb6fb5c63e3f49409db871a5a97261b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs new file mode 100644 index 0000000..e2c2b60 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs @@ -0,0 +1,565 @@ +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PopupMenu : EventDispatcher + { + protected GComponent _contentPane; + protected GList _list; + protected GObject _expandingItem; + + PopupMenu _parentMenu; + TimerCallback _showSubMenu; + TimerCallback _closeSubMenu; + EventListener _onPopup; + EventListener _onClose; + + public int visibleItemCount; + public bool hideOnClickItem; + public bool autoSize; + + const string EVENT_TYPE = "PopupMenuItemClick"; + + public PopupMenu() + { + Create(null); + } + + /// + /// + /// + /// + public PopupMenu(string resourceURL) + { + Create(resourceURL); + } + + public EventListener onPopup + { + get { return _onPopup ?? (_onPopup = new EventListener(this, "onPopup")); } + } + + public EventListener onClose + { + get { return _onClose ?? (_onClose = new EventListener(this, "onClose")); } + } + + void Create(string resourceURL) + { + if (resourceURL == null) + { + resourceURL = UIConfig.popupMenu; + if (resourceURL == null) + { + Debug.LogError("FairyGUI: UIConfig.popupMenu not defined"); + return; + } + } + + _contentPane = UIPackage.CreateObjectFromURL(resourceURL).asCom; + _contentPane.onAddedToStage.Add(__addedToStage); + _contentPane.onRemovedFromStage.Add(__removeFromStage); + _contentPane.focusable = false; + + _list = _contentPane.GetChild("list").asList; + _list.RemoveChildrenToPool(); + + _list.AddRelation(_contentPane, RelationType.Width); + _list.RemoveRelation(_contentPane, RelationType.Height); + _contentPane.AddRelation(_list, RelationType.Height); + + _list.onClickItem.Add(__clickItem); + + hideOnClickItem = true; + _showSubMenu = __showSubMenu; + _closeSubMenu = CloseSubMenu; + } + + /// + /// + /// + /// + /// + /// + public GButton AddItem(string caption, EventCallback0 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChild(item); + + return item; + } + + /// + /// + /// + /// + /// + /// + public GButton AddItem(string caption, EventCallback1 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChild(item); + + return item; + } + + /// + /// + /// + /// + /// + /// + /// + public GButton AddItemAt(string caption, int index, EventCallback1 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChildAt(item, index); + + return item; + } + + /// + /// + /// + /// + /// + /// + /// + public GButton AddItemAt(string caption, int index, EventCallback0 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChildAt(item, index); + + return item; + } + + GButton CreateItem(string caption, Delegate callback) + { + GButton item = _list.GetFromPool(_list.defaultItem).asButton; + item.title = caption; + item.grayed = false; + Controller c = item.GetController("checked"); + if (c != null) + c.selectedIndex = 0; + item.RemoveEventListeners(EVENT_TYPE); + if (callback is EventCallback0) + item.AddEventListener(EVENT_TYPE, (EventCallback0)callback); + else + item.AddEventListener(EVENT_TYPE, (EventCallback1)callback); + + item.onRollOver.Add(__rollOver); + item.onRollOut.Add(__rollOut); + + return item; + } + + /// + /// + /// + public void AddSeperator() + { + AddSeperator(-1); + } + + /// + /// + /// + public void AddSeperator(int index) + { + if (UIConfig.popupMenu_seperator == null) + { + Debug.LogError("FairyGUI: UIConfig.popupMenu_seperator not defined"); + return; + } + + if (index == -1) + _list.AddItemFromPool(UIConfig.popupMenu_seperator); + else + { + GObject item = _list.GetFromPool(UIConfig.popupMenu_seperator); + _list.AddChildAt(item, index); + } + } + + /// + /// + /// + /// + /// + public string GetItemName(int index) + { + GButton item = _list.GetChildAt(index).asButton; + return item.name; + } + + /// + /// + /// + /// + /// + public void SetItemText(string name, string caption) + { + GButton item = _list.GetChild(name).asButton; + item.title = caption; + } + + /// + /// + /// + /// + /// + public void SetItemVisible(string name, bool visible) + { + GButton item = _list.GetChild(name).asButton; + if (item.visible != visible) + { + item.visible = visible; + _list.SetBoundsChangedFlag(); + } + } + + /// + /// + /// + /// + /// + public void SetItemGrayed(string name, bool grayed) + { + GButton item = _list.GetChild(name).asButton; + item.grayed = grayed; + } + + /// + /// + /// + /// + /// + public void SetItemCheckable(string name, bool checkable) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + { + if (checkable) + { + if (c.selectedIndex == 0) + c.selectedIndex = 1; + } + else + c.selectedIndex = 0; + } + } + + /// + /// + /// + /// + /// + public void SetItemChecked(string name, bool check) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + c.selectedIndex = check ? 2 : 1; + } + + [Obsolete("Use IsItemChecked instead")] + public bool isItemChecked(string name) + { + return IsItemChecked(name); + } + + /// + /// + /// + /// + /// + public bool IsItemChecked(string name) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + return c.selectedIndex == 2; + else + return false; + } + + /// + /// + /// + /// + public void RemoveItem(string name) + { + GComponent item = _list.GetChild(name).asCom; + if (item != null) + { + item.RemoveEventListeners(EVENT_TYPE); + if (item.data is PopupMenu) + { + ((PopupMenu)item.data).Dispose(); + item.data = null; + } + int index = _list.GetChildIndex(item); + _list.RemoveChildToPoolAt(index); + } + } + + /// + /// + /// + public void ClearItems() + { + _list.RemoveChildrenToPool(); + } + + /// + /// + /// + public int itemCount + { + get { return _list.numChildren; } + } + + /// + /// + /// + public GComponent contentPane + { + get { return _contentPane; } + } + + /// + /// + /// + public GList list + { + get { return _list; } + } + + public void Dispose() + { + int cnt = _list.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _list.GetChildAt(i); + if (obj.data is PopupMenu) + ((PopupMenu)obj.data).Dispose(); + } + _contentPane.Dispose(); + } + + /// + /// + /// + public void Show() + { + Show(null, PopupDirection.Auto); + } + + /// + /// + /// + /// + public void Show(GObject target) + { + Show(target, PopupDirection.Auto, null); + } + + [Obsolete] + public void Show(GObject target, object downward) + { + Show(target, downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), null); + } + + /// + /// + /// + /// + /// + public void Show(GObject target, PopupDirection dir) + { + Show(target, PopupDirection.Auto, null); + } + + /// + /// + /// + /// + /// + /// + public void Show(GObject target, PopupDirection dir, PopupMenu parentMenu) + { + GRoot r = target != null ? target.root : GRoot.inst; + r.ShowPopup(this.contentPane, (target is GRoot) ? null : target, dir); + _parentMenu = parentMenu; + } + + public void Hide() + { + if (contentPane.parent != null) + ((GRoot)contentPane.parent).HidePopup(contentPane); + } + + void ShowSubMenu(GObject item) + { + _expandingItem = item; + + PopupMenu popup = item.data as PopupMenu; + if (item is GButton) + ((GButton)item).selected = true; + popup.Show(item, PopupDirection.Auto, this); + + Vector2 pt = contentPane.LocalToRoot(new Vector2(item.x + item.width - 5, item.y - 5), item.root); + popup.contentPane.position = pt; + } + + void CloseSubMenu(object param) + { + if (contentPane.isDisposed) + return; + + if (_expandingItem == null) + return; + + if (_expandingItem is GButton) + ((GButton)_expandingItem).selected = false; + PopupMenu popup = (PopupMenu)_expandingItem.data; + if (popup == null) + return; + + _expandingItem = null; + popup.Hide(); + } + + private void __clickItem(EventContext context) + { + GButton item = ((GObject)context.data).asButton; + if (item == null) + return; + + if (item.grayed) + { + _list.selectedIndex = -1; + return; + } + + Controller c = item.GetController("checked"); + if (c != null && c.selectedIndex != 0) + { + if (c.selectedIndex == 1) + c.selectedIndex = 2; + else + c.selectedIndex = 1; + } + + if (hideOnClickItem) + { + if (_parentMenu != null) + _parentMenu.Hide(); + Hide(); + } + + item.DispatchEvent(EVENT_TYPE, item); //event data is for backward compatibility + } + + void __addedToStage() + { + DispatchEvent("onPopup", null); + + if (autoSize) + { + _list.EnsureBoundsCorrect(); + int cnt = _list.numChildren; + float maxDelta = -1000; + for (int i = 0; i < cnt; i++) + { + GButton obj = _list.GetChildAt(i).asButton; + if (obj == null) + continue; + GTextField tf = obj.GetTextField(); + if (tf != null) + { + float v = tf.textWidth - tf.width; + if (v > maxDelta) + maxDelta = v; + } + } + + if (contentPane.width + maxDelta > contentPane.initWidth) + contentPane.width += maxDelta; + else + contentPane.width = contentPane.initWidth; + } + + _list.selectedIndex = -1; + _list.ResizeToFit(visibleItemCount > 0 ? visibleItemCount : int.MaxValue, 10); + } + + void __removeFromStage() + { + _parentMenu = null; + + if (_expandingItem != null) + Timers.inst.Add(0, 1, _closeSubMenu); + + DispatchEvent("onClose", null); + } + + void __rollOver(EventContext context) + { + GObject item = (GObject)context.sender; + if ((item.data is PopupMenu) || _expandingItem != null) + { + Timers.inst.Add(0.1f, 1, _showSubMenu, item); + } + } + + void __showSubMenu(object param) + { + if (contentPane.isDisposed) + return; + + GObject item = (GObject)param; + GRoot r = contentPane.root; + if (r == null) + return; + + if (_expandingItem != null) + { + if (_expandingItem == item) + return; + + CloseSubMenu(null); + } + + PopupMenu popup = item.data as PopupMenu; + if (popup == null) + return; + + ShowSubMenu(item); + } + + void __rollOut(EventContext context) + { + if (_expandingItem == null) + return; + + Timers.inst.Remove(_showSubMenu); + + GRoot r = contentPane.root; + if (r != null) + { + PopupMenu popup = (PopupMenu)_expandingItem.data; + Vector2 pt = popup.contentPane.GlobalToLocal(context.inputEvent.position); + if (pt.x >= 0 && pt.y >= 0 && pt.x < popup.contentPane.width && pt.y < popup.contentPane.height) + return; + } + + CloseSubMenu(null); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs.meta new file mode 100644 index 0000000..0a00a62 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/PopupMenu.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f15a5c9ba9a949d468aeb92e75f70dbd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs new file mode 100644 index 0000000..edf099e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs @@ -0,0 +1,671 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + class RelationDef + { + public bool percent; + public RelationType type; + public int axis; + + public void copyFrom(RelationDef source) + { + this.percent = source.percent; + this.type = source.type; + this.axis = source.axis; + } + } + + class RelationItem + { + GObject _owner; + GObject _target; + List _defs; + Vector4 _targetData; + + public RelationItem(GObject owner) + { + _owner = owner; + _defs = new List(); + } + + public GObject target + { + get { return _target; } + set + { + if (_target != value) + { + if (_target != null) + ReleaseRefTarget(_target); + _target = value; + if (_target != null) + AddRefTarget(_target); + } + } + } + + public void Add(RelationType relationType, bool usePercent) + { + if (relationType == RelationType.Size) + { + Add(RelationType.Width, usePercent); + Add(RelationType.Height, usePercent); + return; + } + + int dc = _defs.Count; + for (int k = 0; k < dc; k++) + { + if (_defs[k].type == relationType) + return; + } + + InternalAdd(relationType, usePercent); + } + + public void InternalAdd(RelationType relationType, bool usePercent) + { + if (relationType == RelationType.Size) + { + InternalAdd(RelationType.Width, usePercent); + InternalAdd(RelationType.Height, usePercent); + return; + } + + RelationDef info = new RelationDef(); + info.percent = usePercent; + info.type = relationType; + info.axis = (relationType <= RelationType.Right_Right || relationType == RelationType.Width || relationType >= RelationType.LeftExt_Left && relationType <= RelationType.RightExt_Right) ? 0 : 1; + _defs.Add(info); + } + + public void Remove(RelationType relationType) + { + if (relationType == RelationType.Size) + { + Remove(RelationType.Width); + Remove(RelationType.Height); + return; + } + + int dc = _defs.Count; + for (int k = 0; k < dc; k++) + { + if (_defs[k].type == relationType) + { + _defs.RemoveAt(k); + break; + } + } + } + + public void CopyFrom(RelationItem source) + { + this.target = source.target; + + _defs.Clear(); + foreach (RelationDef info in source._defs) + { + RelationDef info2 = new RelationDef(); + info2.copyFrom(info); + _defs.Add(info2); + } + } + + public void Dispose() + { + if (_target != null) + { + ReleaseRefTarget(_target); + _target = null; + } + } + + public bool isEmpty + { + get { return _defs.Count == 0; } + } + + public void ApplyOnSelfSizeChanged(float dWidth, float dHeight, bool applyPivot) + { + int cnt = _defs.Count; + if (cnt == 0) + return; + + float ox = _owner.x; + float oy = _owner.y; + + for (int i = 0; i < cnt; i++) + { + RelationDef info = _defs[i]; + switch (info.type) + { + case RelationType.Center_Center: + _owner.x -= (0.5f - (applyPivot ? _owner.pivotX : 0)) * dWidth; + break; + + case RelationType.Right_Center: + case RelationType.Right_Left: + case RelationType.Right_Right: + _owner.x -= (1 - (applyPivot ? _owner.pivotX : 0)) * dWidth; + break; + + case RelationType.Middle_Middle: + _owner.y -= (0.5f - (applyPivot ? _owner.pivotY : 0)) * dHeight; + break; + + case RelationType.Bottom_Middle: + case RelationType.Bottom_Top: + case RelationType.Bottom_Bottom: + _owner.y -= (1 - (applyPivot ? _owner.pivotY : 0)) * dHeight; + break; + } + } + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + } + + void ApplyOnXYChanged(RelationDef info, float dx, float dy) + { + float tmp; + switch (info.type) + { + case RelationType.Left_Left: + case RelationType.Left_Center: + case RelationType.Left_Right: + case RelationType.Center_Center: + case RelationType.Right_Left: + case RelationType.Right_Center: + case RelationType.Right_Right: + _owner.x += dx; + break; + + case RelationType.Top_Top: + case RelationType.Top_Middle: + case RelationType.Top_Bottom: + case RelationType.Middle_Middle: + case RelationType.Bottom_Top: + case RelationType.Bottom_Middle: + case RelationType.Bottom_Bottom: + _owner.y += dy; + break; + + case RelationType.Width: + case RelationType.Height: + break; + + case RelationType.LeftExt_Left: + case RelationType.LeftExt_Right: + if (_owner != _target.parent) + { + tmp = _owner.xMin; + _owner.width = _owner._rawWidth - dx; + _owner.xMin = tmp + dx; + } + else + _owner.width = _owner._rawWidth - dx; + break; + + case RelationType.RightExt_Left: + case RelationType.RightExt_Right: + if (_owner != _target.parent) + { + tmp = _owner.xMin; + _owner.width = _owner._rawWidth + dx; + _owner.xMin = tmp; + } + else + _owner.width = _owner._rawWidth + dx; + break; + + case RelationType.TopExt_Top: + case RelationType.TopExt_Bottom: + if (_owner != _target.parent) + { + tmp = _owner.yMin; + _owner.height = _owner._rawHeight - dy; + _owner.yMin = tmp + dy; + } + else + _owner.height = _owner._rawHeight - dy; + break; + + case RelationType.BottomExt_Top: + case RelationType.BottomExt_Bottom: + if (_owner != _target.parent) + { + tmp = _owner.yMin; + _owner.height = _owner._rawHeight + dy; + _owner.yMin = tmp; + } + else + _owner.height = _owner._rawHeight + dy; + break; + } + } + + void ApplyOnSizeChanged(RelationDef info) + { + float pos = 0, pivot = 0, delta = 0; + if (info.axis == 0) + { + if (_target != _owner.parent) + { + pos = _target.x; + if (_target.pivotAsAnchor) + pivot = _target.pivotX; + } + + if (info.percent) + { + if (_targetData.z != 0) + delta = _target._width / _targetData.z; + } + else + delta = _target._width - _targetData.z; + } + else + { + if (_target != _owner.parent) + { + pos = _target.y; + if (_target.pivotAsAnchor) + pivot = _target.pivotY; + } + + if (info.percent) + { + if (_targetData.w != 0) + delta = _target._height / _targetData.w; + } + else + delta = _target._height - _targetData.w; + } + + float v, tmp; + + switch (info.type) + { + case RelationType.Left_Left: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else if (pivot != 0) + _owner.x += delta * (-pivot); + break; + case RelationType.Left_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Left_Right: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else + _owner.x += delta * (1 - pivot); + break; + case RelationType.Center_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth * 0.5f - pos) * delta - _owner._rawWidth * 0.5f; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Right_Left: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else if (pivot != 0) + _owner.x += delta * (-pivot); + break; + case RelationType.Right_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Right_Right: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else + _owner.x += delta * (1 - pivot); + break; + + case RelationType.Top_Top: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else if (pivot != 0) + _owner.y += delta * (-pivot); + break; + case RelationType.Top_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Top_Bottom: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else + _owner.y += delta * (1 - pivot); + break; + case RelationType.Middle_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight * 0.5f - pos) * delta - _owner._rawHeight * 0.5f; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Bottom_Top: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else if (pivot != 0) + _owner.y += delta * (-pivot); + break; + case RelationType.Bottom_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Bottom_Bottom: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else + _owner.y += delta * (1 - pivot); + break; + + case RelationType.Width: + if (_owner.underConstruct && _owner == _target.parent) + v = _owner.sourceWidth - _target.initWidth; + else + v = _owner._rawWidth - _targetData.z; + if (info.percent) + v = v * delta; + if (_target == _owner.parent) + { + if (_owner.pivotAsAnchor) + { + tmp = _owner.xMin; + _owner.SetSize(_target._width + v, _owner._rawHeight, true); + _owner.xMin = tmp; + } + else + _owner.SetSize(_target._width + v, _owner._rawHeight, true); + } + else + _owner.width = _target._width + v; + break; + case RelationType.Height: + if (_owner.underConstruct && _owner == _target.parent) + v = _owner.sourceHeight - _target.initHeight; + else + v = _owner._rawHeight - _targetData.w; + if (info.percent) + v = v * delta; + if (_target == _owner.parent) + { + if (_owner.pivotAsAnchor) + { + tmp = _owner.yMin; + _owner.SetSize(_owner._rawWidth, _target._height + v, true); + _owner.yMin = tmp; + } + else + _owner.SetSize(_owner._rawWidth, _target._height + v, true); + } + else + _owner.height = _target._height + v; + break; + + case RelationType.LeftExt_Left: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (-pivot); + _owner.width = _owner._rawWidth - v; + _owner.xMin = tmp + v; + break; + case RelationType.LeftExt_Right: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (1 - pivot); + _owner.width = _owner._rawWidth - v; + _owner.xMin = tmp + v; + break; + case RelationType.RightExt_Left: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); + else + v = delta * (-pivot); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + break; + case RelationType.RightExt_Right: + tmp = _owner.xMin; + if (info.percent) + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.width = pos + _target._width - _target._width * pivot + + (_owner.sourceWidth - pos - _target.initWidth + _target.initWidth * pivot) * delta; + else + _owner.width = pos + (_owner._rawWidth - pos) * delta; + } + else + { + v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + } + } + else + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.width = _owner.sourceWidth + (_target._width - _target.initWidth) * (1 - pivot); + else + _owner.width = _owner._rawWidth + delta * (1 - pivot); + } + else + { + v = delta * (1 - pivot); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + } + } + break; + case RelationType.TopExt_Top: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (-pivot); + _owner.height = _owner._rawHeight - v; + _owner.yMin = tmp + v; + break; + case RelationType.TopExt_Bottom: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (1 - pivot); + _owner.height = _owner._rawHeight - v; + _owner.yMin = tmp + v; + break; + case RelationType.BottomExt_Top: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); + else + v = delta * (-pivot); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + break; + case RelationType.BottomExt_Bottom: + tmp = _owner.yMin; + if (info.percent) + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.height = pos + _target._height - _target._height * pivot + + (_owner.sourceHeight - pos - _target.initHeight + _target.initHeight * pivot) * delta; + else + _owner.height = pos + (_owner._rawHeight - pos) * delta; + } + else + { + v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + } + } + else + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.height = _owner.sourceHeight + (_target._height - _target.initHeight) * (1 - pivot); + else + _owner.height = _owner._rawHeight + delta * (1 - pivot); + } + else + { + v = delta * (1 - pivot); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + } + } + break; + } + } + + void AddRefTarget(GObject target) + { + if (target != _owner.parent) + target.onPositionChanged.Add(__targetXYChanged); + target.onSizeChanged.Add(__targetSizeChanged); + _targetData.x = _target.x; + _targetData.y = _target.y; + _targetData.z = _target._width; + _targetData.w = _target._height; + } + + void ReleaseRefTarget(GObject target) + { + target.onPositionChanged.Remove(__targetXYChanged); + target.onSizeChanged.Remove(__targetSizeChanged); + } + + void __targetXYChanged(EventContext context) + { + if (_owner.relations.handling != null + || _owner.group != null && _owner.group._updating != 0) + { + _targetData.x = _target.x; + _targetData.y = _target.y; + return; + } + + _owner.relations.handling = (GObject)context.sender; + + float ox = _owner.x; + float oy = _owner.y; + float dx = _target.x - _targetData.x; + float dy = _target.y - _targetData.y; + + int cnt = _defs.Count; + for (int i = 0; i < cnt; i++) + ApplyOnXYChanged(_defs[i], dx, dy); + + _targetData.x = _target.x; + _targetData.y = _target.y; + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + + _owner.relations.handling = null; + } + + void __targetSizeChanged(EventContext context) + { + if (_owner.relations.handling != null + || _owner.group != null && _owner.group._updating != 0) + { + _targetData.z = _target._width; + _targetData.w = _target._height; + return; + } + + _owner.relations.handling = (GObject)context.sender; + + float ox = _owner.x; + float oy = _owner.y; + float ow = _owner._rawWidth; + float oh = _owner._rawHeight; + + int cnt = _defs.Count; + for (int i = 0; i < cnt; i++) + ApplyOnSizeChanged(_defs[i]); + + _targetData.z = _target._width; + _targetData.w = _target._height; + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + + if (!Mathf.Approximately(ow, _owner._rawWidth) || !Mathf.Approximately(oh, _owner._rawHeight)) + { + ow = _owner._rawWidth - ow; + oh = _owner._rawHeight - oh; + + _owner.UpdateGearFromRelations(2, ow, oh); + } + + _owner.relations.handling = null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs.meta new file mode 100644 index 0000000..ccf53d1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/RelationItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 859441fdd74333a498ff048e6b48798b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs new file mode 100644 index 0000000..b56db64 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs @@ -0,0 +1,219 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class Relations + { + GObject _owner; + List _items; + + public GObject handling; + + public Relations(GObject owner) + { + _owner = owner; + _items = new List(); + } + + /// + /// + /// + /// + /// + public void Add(GObject target, RelationType relationType) + { + Add(target, relationType, false); + } + + /// + /// + /// + /// + /// + /// + public void Add(GObject target, RelationType relationType, bool usePercent) + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Add(relationType, usePercent); + return; + } + } + RelationItem newItem = new RelationItem(_owner); + newItem.target = target; + newItem.Add(relationType, usePercent); + _items.Add(newItem); + } + + /// + /// + /// + /// + /// + public void Remove(GObject target, RelationType relationType) + { + int cnt = _items.Count; + int i = 0; + while (i < cnt) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Remove(relationType); + if (item.isEmpty) + { + item.Dispose(); + _items.RemoveAt(i); + cnt--; + continue; + } + else + i++; + } + i++; + } + } + + /// + /// + /// + /// + /// + public bool Contains(GObject target) + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + if (item.target == target) + return true; + } + return false; + } + + /// + /// + /// + /// + public void ClearFor(GObject target) + { + int cnt = _items.Count; + int i = 0; + while (i < cnt) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Dispose(); + _items.RemoveAt(i); + cnt--; + } + else + i++; + } + } + + /// + /// + /// + public void ClearAll() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + item.Dispose(); + } + _items.Clear(); + } + + /// + /// + /// + /// + public void CopyFrom(Relations source) + { + ClearAll(); + + List arr = source._items; + foreach (RelationItem ri in arr) + { + RelationItem item = new RelationItem(_owner); + item.CopyFrom(ri); + _items.Add(item); + } + } + + /// + /// + /// + public void Dispose() + { + ClearAll(); + handling = null; + } + + /// + /// + /// + /// + /// + /// + public void OnOwnerSizeChanged(float dWidth, float dHeight, bool applyPivot) + { + int cnt = _items.Count; + if (cnt == 0) + return; + + for (int i = 0; i < cnt; i++) + _items[i].ApplyOnSelfSizeChanged(dWidth, dHeight, applyPivot); + } + + /// + /// + /// + public bool isEmpty + { + get + { + return _items.Count == 0; + } + } + + public void Setup(ByteBuffer buffer, bool parentToChild) + { + int cnt = buffer.ReadByte(); + GObject target; + for (int i = 0; i < cnt; i++) + { + int targetIndex = buffer.ReadShort(); + if (targetIndex == -1) + target = _owner.parent; + else if (parentToChild) + target = ((GComponent)_owner).GetChildAt(targetIndex); + else + target = _owner.parent.GetChildAt(targetIndex); + + RelationItem newItem = new RelationItem(_owner); + newItem.target = target; + _items.Add(newItem); + + int cnt2 = buffer.ReadByte(); + for (int j = 0; j < cnt2; j++) + { + RelationType rt = (RelationType)buffer.ReadByte(); + bool usePercent = buffer.ReadBool(); + newItem.InternalAdd(rt, usePercent); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs.meta new file mode 100644 index 0000000..9891ee1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Relations.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4376a9406aa478a4b82816818842d737 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs new file mode 100644 index 0000000..e3d9c5f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs @@ -0,0 +1,2367 @@ +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class ScrollPane : EventDispatcher + { + // [Y 修改] + private float m_animTweenTime = 0f; + private float _mouseWheelStep; + + /// + /// 当前被拖拽的滚动面板。同一时间只能有一个在进行此操作。 + /// + public static ScrollPane draggingPane { get; private set; } + + ScrollType _scrollType; + float _scrollStep; + float _decelerationRate; + Margin _scrollBarMargin; + bool _bouncebackEffect; + bool _touchEffect; + bool _scrollBarDisplayAuto; + bool _vScrollNone; + bool _hScrollNone; + bool _needRefresh; + int _refreshBarAxis; + + bool _displayOnLeft; + bool _snapToItem; + internal bool _displayInDemand; + bool _mouseWheelEnabled; + bool _softnessOnTopOrLeftSide; + bool _pageMode; + Vector2 _pageSize; + bool _inertiaDisabled; + bool _maskDisabled; + bool _floating; + bool _dontClipMargin; + + float _xPos; + float _yPos; + + Vector2 _viewSize; + Vector2 _contentSize; + Vector2 _overlapSize; + Vector2 _containerPos; + Vector2 _beginTouchPos; + Vector2 _lastTouchPos; + Vector2 _lastTouchGlobalPos; + Vector2 _velocity; + float _velocityScale; + float _lastMoveTime; + bool _dragged; + bool _isHoldAreaDone; + int _aniFlag; + internal int _loop; + int _headerLockedSize; + int _footerLockedSize; + bool _hover; + + int _tweening; + Vector2 _tweenStart; + Vector2 _tweenChange; + Vector2 _tweenTime; + Vector2 _tweenDuration; + + Action _refreshDelegate; + TimerCallback _tweenUpdateDelegate; + GTweenCallback1 _hideScrollBarDelegate; + + GComponent _owner; + Container _maskContainer; + Container _container; + GScrollBar _hzScrollBar; + GScrollBar _vtScrollBar; + GComponent _header; + GComponent _footer; + Controller _pageController; + + EventListener _onScroll; + EventListener _onScrollEnd; + EventListener _onPullDownRelease; + EventListener _onPullUpRelease; + + + static int _gestureFlag; + + public static float TWEEN_TIME_GO = 0.3f; //调用SetPos(ani)时使用的缓动时间 + public static float TWEEN_TIME_DEFAULT = 0.3f; //惯性滚动的最小缓动时间 + public static float PULL_RATIO = 0.5f; //下拉过顶或者上拉过底时允许超过的距离占显示区域的比例 + + public ScrollPane(GComponent owner) + { + _onScroll = new EventListener(this, "onScroll"); + _onScrollEnd = new EventListener(this, "onScrollEnd"); + + _scrollStep = UIConfig.defaultScrollStep; + //[Y 修改] + _mouseWheelStep = _scrollStep * 2; + + _softnessOnTopOrLeftSide = UIConfig.allowSoftnessOnTopOrLeftSide; + _decelerationRate = UIConfig.defaultScrollDecelerationRate; + _touchEffect = UIConfig.defaultScrollTouchEffect; + _bouncebackEffect = UIConfig.defaultScrollBounceEffect; + _mouseWheelEnabled = true; + _pageSize = Vector2.one; + + _refreshDelegate = Refresh; + _tweenUpdateDelegate = TweenUpdate; + _hideScrollBarDelegate = __barTweenComplete; + + _owner = owner; + + _maskContainer = new Container(); + _owner.rootContainer.AddChild(_maskContainer); + + _container = _owner.container; + _container.SetXY(0, 0); + _maskContainer.AddChild(_container); + + _owner.rootContainer.onMouseWheel.Add(__mouseWheel); + _owner.rootContainer.onTouchBegin.Add(__touchBegin); + _owner.rootContainer.onTouchMove.Add(__touchMove); + _owner.rootContainer.onTouchEnd.Add(__touchEnd); + } + + /// + /// [Y 修改] + /// + public void SetAnimTweenTime(float animTweenTime) + { + m_animTweenTime = animTweenTime; + } + + public void Setup(ByteBuffer buffer) + { + _scrollType = (ScrollType)buffer.ReadByte(); + ScrollBarDisplayType scrollBarDisplay = (ScrollBarDisplayType)buffer.ReadByte(); + int flags = buffer.ReadInt(); + + if (buffer.ReadBool()) + { + _scrollBarMargin.top = buffer.ReadInt(); + _scrollBarMargin.bottom = buffer.ReadInt(); + _scrollBarMargin.left = buffer.ReadInt(); + _scrollBarMargin.right = buffer.ReadInt(); + } + + string vtScrollBarRes = buffer.ReadS(); + string hzScrollBarRes = buffer.ReadS(); + string headerRes = buffer.ReadS(); + string footerRes = buffer.ReadS(); + + _displayOnLeft = (flags & 1) != 0; + _snapToItem = (flags & 2) != 0; + _displayInDemand = (flags & 4) != 0; + _pageMode = (flags & 8) != 0; + if ((flags & 16) != 0) + _touchEffect = true; + else if ((flags & 32) != 0) + _touchEffect = false; + if ((flags & 64) != 0) + _bouncebackEffect = true; + else if ((flags & 128) != 0) + _bouncebackEffect = false; + _inertiaDisabled = (flags & 256) != 0; + _maskDisabled = (flags & 512) != 0; + _floating = (flags & 1024) != 0; + _dontClipMargin = (flags & 2048) != 0; + + if (scrollBarDisplay == ScrollBarDisplayType.Default) + { + if (Application.isMobilePlatform) + scrollBarDisplay = ScrollBarDisplayType.Auto; + else + scrollBarDisplay = UIConfig.defaultScrollBarDisplay; + } + + if (scrollBarDisplay != ScrollBarDisplayType.Hidden) + { + if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) + { + string res = vtScrollBarRes != null ? vtScrollBarRes : UIConfig.verticalScrollBar; + if (!string.IsNullOrEmpty(res)) + { + _vtScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; + if (_vtScrollBar == null) + Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); + else + { + _vtScrollBar.SetScrollPane(this, true); + _owner.rootContainer.AddChild(_vtScrollBar.displayObject); + } + } + } + if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Horizontal) + { + string res = hzScrollBarRes != null ? hzScrollBarRes : UIConfig.horizontalScrollBar; + if (!string.IsNullOrEmpty(res)) + { + _hzScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; + if (_hzScrollBar == null) + Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); + else + { + _hzScrollBar.SetScrollPane(this, false); + _owner.rootContainer.AddChild(_hzScrollBar.displayObject); + } + } + } + + _scrollBarDisplayAuto = scrollBarDisplay == ScrollBarDisplayType.Auto; + if (_scrollBarDisplayAuto) + { + if (_vtScrollBar != null) + _vtScrollBar.displayObject.visible = false; + if (_hzScrollBar != null) + _hzScrollBar.displayObject.visible = false; + + _owner.rootContainer.onRollOver.Add(__rollOver); + _owner.rootContainer.onRollOut.Add(__rollOut); + } + } + else + _mouseWheelEnabled = false; + + if (Application.isPlaying) + { + if (headerRes != null) + { + _header = (GComponent)UIPackage.CreateObjectFromURL(headerRes); + if (_header == null) + Debug.LogWarning("FairyGUI: cannot create scrollPane header from " + headerRes); + } + + if (footerRes != null) + { + _footer = (GComponent)UIPackage.CreateObjectFromURL(footerRes); + if (_footer == null) + Debug.LogWarning("FairyGUI: cannot create scrollPane footer from " + footerRes); + } + + if (_header != null || _footer != null) + _refreshBarAxis = (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) ? 1 : 0; + } + + SetSize(owner.width, owner.height); + } + + /// + /// + /// + public void Dispose() + { + RemoveEventListeners(); + + if (_tweening != 0) + Timers.inst.Remove(_tweenUpdateDelegate); + + if (draggingPane == this) + draggingPane = null; + + _pageController = null; + + if (_hzScrollBar != null) + _hzScrollBar.Dispose(); + if (_vtScrollBar != null) + _vtScrollBar.Dispose(); + if (_header != null) + _header.Dispose(); + if (_footer != null) + _footer.Dispose(); + } + + /// + /// Dispatched when scrolling. + /// 在滚动时派发该事件。 + /// + public EventListener onScroll + { + get { return _onScroll ?? (_onScroll = new EventListener(this, "onScroll")); } + } + + /// + /// 在滚动结束时派发该事件。 + /// + public EventListener onScrollEnd + { + get { return _onScrollEnd ?? (_onScrollEnd = new EventListener(this, "onScrollEnd")); } + } + + /// + /// 向下拉过上边缘后释放则派发该事件。 + /// + public EventListener onPullDownRelease + { + get { return _onPullDownRelease ?? (_onPullDownRelease = new EventListener(this, "onPullDownRelease")); } + } + + /// + /// 向上拉过下边缘后释放则派发该事件。 + /// + public EventListener onPullUpRelease + { + get { return _onPullUpRelease ?? (_onPullUpRelease = new EventListener(this, "onPullUpRelease")); } + } + + /// + /// + /// + public GComponent owner + { + get { return _owner; } + } + + /// + /// + /// + public GScrollBar hzScrollBar + { + get { return _hzScrollBar; } + } + + /// + /// + /// + public GScrollBar vtScrollBar + { + get { return _vtScrollBar; } + } + + /// + /// + /// + public GComponent header + { + get { return _header; } + } + + /// + /// + /// + public GComponent footer + { + get { return _footer; } + } + + /// + /// 滚动到达边缘时是否允许回弹效果。 + /// + public bool bouncebackEffect + { + get { return _bouncebackEffect; } + set { _bouncebackEffect = value; } + } + + /// + /// 是否允许拖拽内容区域进行滚动。 + /// + public bool touchEffect + { + get { return _touchEffect; } + set { _touchEffect = value; } + } + + /// + /// 是否允许惯性滚动。 + /// + public bool inertiaDisabled + { + get { return _inertiaDisabled; } + set { _inertiaDisabled = value; } + } + + /// + /// 是否允许在左/上边缘显示虚化效果。 + /// + public bool softnessOnTopOrLeftSide + { + get { return _softnessOnTopOrLeftSide; } + set { _softnessOnTopOrLeftSide = value; } + } + + /// + /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 + /// + public float scrollStep + { + get { return _scrollStep; } + set + { + _scrollStep = value; + if (_scrollStep == 0) + _scrollStep = UIConfig.defaultScrollStep; + + //[Y 修改] + _mouseWheelStep = _scrollStep * 2; + } + } + + /// + /// 滚动位置是否保持贴近在某个元件的边缘。 + /// + public bool snapToItem + { + get { return _snapToItem; } + set { _snapToItem = value; } + } + + /// + /// 是否页面滚动模式。 + /// + public bool pageMode + { + get { return _pageMode; } + set { _pageMode = value; } + } + + /// + /// + /// + public Controller pageController + { + get { return _pageController; } + set { _pageController = value; } + } + + /// + /// 是否允许使用鼠标滚轮进行滚动。 + /// + public bool mouseWheelEnabled + { + get { return _mouseWheelEnabled; } + set { _mouseWheelEnabled = value; } + } + + /// + /// 当处于惯性滚动时减速的速率。默认值是UIConfig.defaultScrollDecelerationRate。 + /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 + /// + public float decelerationRate + { + get { return _decelerationRate; } + set { _decelerationRate = value; } + } + + /// + /// + public bool isDragged + { + get { return _dragged; } + } + + /// + /// 当前X轴滚动位置百分比,0~1(包含)。 + /// + public float percX + { + get { return _overlapSize.x == 0 ? 0 : _xPos / _overlapSize.x; } + set { SetPercX(value, false); } + } + + /// + /// 设置当前X轴滚动位置百分比,0~1(包含)。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPercX(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + SetPosX(_overlapSize.x * Mathf.Clamp01(value), ani); + } + + /// + /// 当前Y轴滚动位置百分比,0~1(包含)。 + /// + public float percY + { + get { return _overlapSize.y == 0 ? 0 : _yPos / _overlapSize.y; } + set { SetPercY(value, false); } + } + + /// + /// 设置当前Y轴滚动位置百分比,0~1(包含)。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPercY(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + SetPosY(_overlapSize.y * Mathf.Clamp01(value), ani); + } + + /// + /// 当前X轴滚动位置,值范围是viewWidth与contentWidth之差。 + /// + public float posX + { + get { return _xPos; } + set { SetPosX(value, false); } + } + + /// + /// 设置当前X轴滚动位置。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPosX(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + + if (_loop == 1) + LoopCheckingNewPos(ref value, 0); + + value = Mathf.Clamp(value, 0, _overlapSize.x); + if (value != _xPos) + { + _xPos = value; + PosChanged(ani); + } + } + + /// + /// 当前Y轴滚动位置,值范围是viewHeight与contentHeight之差。 + /// + public float posY + { + get { return _yPos; } + set { SetPosY(value, false); } + } + + /// + /// 设置当前Y轴滚动位置。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPosY(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + + if (_loop == 2) + LoopCheckingNewPos(ref value, 1); + + value = Mathf.Clamp(value, 0, _overlapSize.y); + if (value != _yPos) + { + _yPos = value; + PosChanged(ani); + } + } + + /// + /// 返回当前滚动位置是否在最下边。 + /// + public bool isBottomMost + { + get { return _yPos == _overlapSize.y || _overlapSize.y == 0; } + } + + /// + /// 返回当前滚动位置是否在最右边。 + /// + public bool isRightMost + { + get { return _xPos == _overlapSize.x || _overlapSize.x == 0; } + } + + /// + /// 如果处于分页模式,返回当前在X轴的页码。 + /// + public int currentPageX + { + get + { + if (!_pageMode) + return 0; + + int page = Mathf.FloorToInt(_xPos / _pageSize.x); + if (_xPos - page * _pageSize.x > _pageSize.x * 0.5f) + page++; + + return page; + } + set + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.x > 0) + this.SetPosX(value * _pageSize.x, false); + } + } + + /// + /// 如果处于分页模式,可设置X轴的页码。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetCurrentPageX(int value, bool ani) + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.x > 0) + this.SetPosX(value * _pageSize.x, ani); + } + + /// + /// 如果处于分页模式,返回当前在Y轴的页码。 + /// + public int currentPageY + { + get + { + if (!_pageMode) + return 0; + + int page = Mathf.FloorToInt(_yPos / _pageSize.y); + if (_yPos - page * _pageSize.y > _pageSize.y * 0.5f) + page++; + + return page; + } + set + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.y > 0) + this.SetPosY(value * _pageSize.y, false); + } + } + + /// + /// 如果处于分页模式,可设置Y轴的页码。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetCurrentPageY(int value, bool ani) + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.y > 0) + this.SetPosY(value * _pageSize.y, ani); + } + + /// + /// 这个值与PosX不同在于,他反映的是实时位置,而PosX在有缓动过程的情况下只是终值。 + /// + public float scrollingPosX + { + get + { + return Mathf.Clamp(-_container.x, 0, _overlapSize.x); + } + } + + /// + /// 这个值与PosY不同在于,他反映的是实时位置,而PosY在有缓动过程的情况下只是终值。 + /// + public float scrollingPosY + { + get + { + return Mathf.Clamp(-_container.y, 0, _overlapSize.y); + } + } + + /// + /// 显示内容宽度。 + /// + public float contentWidth + { + get + { + return _contentSize.x; + } + } + + /// + /// 显示内容高度。 + /// + public float contentHeight + { + get + { + return _contentSize.y; + } + } + + /// + /// 显示区域宽度。 + /// + public float viewWidth + { + get { return _viewSize.x; } + set + { + value = value + _owner.margin.left + _owner.margin.right; + if (_vtScrollBar != null && !_floating) + value += _vtScrollBar.width; + _owner.width = value; + } + } + + /// + /// 显示区域高度。 + /// + public float viewHeight + { + get { return _viewSize.y; } + set + { + value = value + _owner.margin.top + _owner.margin.bottom; + if (_hzScrollBar != null && !_floating) + value += _hzScrollBar.height; + _owner.height = value; + } + } + + /// + /// + /// + public void ScrollTop() + { + ScrollTop(false); + } + + /// + /// + /// + /// + public void ScrollTop(bool ani) + { + this.SetPercY(0, ani); + } + + /// + /// + /// + public void ScrollBottom() + { + ScrollBottom(false); + } + + /// + /// + /// + /// + public void ScrollBottom(bool ani) + { + this.SetPercY(1, ani); + } + + /// + /// + /// + public void ScrollUp() + { + ScrollUp(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollUp(float ratio, bool ani) + { + if (_pageMode) + SetPosY(_yPos - _pageSize.y * ratio, ani); + else + SetPosY(_yPos - _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollDown() + { + ScrollDown(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollDown(float ratio, bool ani) + { + if (_pageMode) + SetPosY(_yPos + _pageSize.y * ratio, ani); + else + SetPosY(_yPos + _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollLeft() + { + ScrollLeft(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollLeft(float ratio, bool ani) + { + if (_pageMode) + SetPosX(_xPos - _pageSize.x * ratio, ani); + else + SetPosX(_xPos - _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollRight() + { + ScrollRight(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollRight(float ratio, bool ani) + { + if (_pageMode) + SetPosX(_xPos + _pageSize.x * ratio, ani); + else + SetPosX(_xPos + _scrollStep * ratio, ani); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + public void ScrollToView(GObject obj) + { + ScrollToView(obj, false); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + /// If moving to target position with animation + public void ScrollToView(GObject obj, bool ani) + { + ScrollToView(obj, ani, false); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + /// If moving to target position with animation + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(GObject obj, bool ani, bool setFirst) + { + _owner.EnsureBoundsCorrect(); + if (_needRefresh) + Refresh(); + + Rect rect = new Rect(obj.x, obj.y, obj.width, obj.height); + if (obj.parent != _owner) + rect = obj.parent.TransformRect(rect, _owner); + ScrollToView(rect, ani, setFirst); + } + + /// + /// + /// + /// Rect in local coordinates + /// If moving to target position with animation + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(Rect rect, bool ani, bool setFirst) + { + _owner.EnsureBoundsCorrect(); + if (_needRefresh) + Refresh(); + + if (_overlapSize.y > 0) + { + float bottom = _yPos + _viewSize.y; + if (setFirst || rect.y <= _yPos || rect.height >= _viewSize.y) + { + //[Y 修改] + //if (rect.yMax >= bottom) //if an item size is large than viewSize, dont scroll + // return; + + if (_pageMode) + this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); + else + SetPosY(rect.y, ani); + } + else if (rect.yMax > bottom) + { + if (_pageMode) + this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); + else if (rect.height <= _viewSize.y / 2) + SetPosY(rect.y + rect.height * 2 - _viewSize.y, ani); + else + SetPosY(rect.y + Mathf.Min(rect.height - _viewSize.y, 0), ani); + } + } + if (_overlapSize.x > 0) + { + float right = _xPos + _viewSize.x; + if (setFirst || rect.x <= _xPos || rect.width >= _viewSize.x) + { + //[Y 修改] + //if (rect.xMax >= right) //if an item size is large than viewSize, dont scroll + // return; + + if (_pageMode) + this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); + SetPosX(rect.x, ani); + } + else if (rect.xMax > right) + { + if (_pageMode) + this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); + else if (rect.width <= _viewSize.x / 2) + SetPosX(rect.x + rect.width * 2 - _viewSize.x, ani); + else + SetPosX(rect.x + Mathf.Min(rect.width - _viewSize.x, 0), ani); + } + } + + if (!ani && _needRefresh) + Refresh(); + } + + /// + /// + /// + /// obj must be the direct child of this container + /// + public bool IsChildInView(GObject obj) + { + if (_overlapSize.y > 0) + { + float dist = obj.y + _container.y; + if (dist <= -obj.height || dist >= _viewSize.y) + return false; + } + if (_overlapSize.x > 0) + { + float dist = obj.x + _container.x; + if (dist <= -obj.width || dist >= _viewSize.x) + return false; + } + + return true; + } + + /// + /// 当滚动面板处于拖拽滚动状态或即将进入拖拽状态时,可以调用此方法停止或禁止本次拖拽。 + /// + public void CancelDragging() + { + Stage.inst.RemoveTouchMonitor(_owner.rootContainer); + + if (draggingPane == this) + draggingPane = null; + + _gestureFlag = 0; + _dragged = false; + } + + /// + /// 设置Header固定显示。如果size为0,则取消固定显示。 + /// + /// Header显示的大小 + public void LockHeader(int size) + { + if (_headerLockedSize == size) + return; + + _headerLockedSize = size; + if (!isDispatching("onPullDownRelease") && _container.xy[_refreshBarAxis] >= 0) + { + _tweenStart = _container.xy; + _tweenChange = Vector2.zero; + _tweenChange[_refreshBarAxis] = _headerLockedSize - _tweenStart[_refreshBarAxis]; + _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + StartTween(2); + } + } + + /// + /// 设置Footer固定显示。如果size为0,则取消固定显示。 + /// + /// + public void LockFooter(int size) + { + if (_footerLockedSize == size) + return; + + _footerLockedSize = size; + if (!isDispatching("onPullUpRelease") && _container.xy[_refreshBarAxis] <= -_overlapSize[_refreshBarAxis]) + { + _tweenStart = _container.xy; + _tweenChange = Vector2.zero; + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + _tweenChange[_refreshBarAxis] = -max - _tweenStart[_refreshBarAxis]; + _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + StartTween(2); + } + } + + internal void OnOwnerSizeChanged() + { + SetSize(_owner.width, _owner.height); + PosChanged(false); + } + + internal void HandleControllerChanged(Controller c) + { + if (_pageController == c) + { + if (_scrollType == ScrollType.Horizontal) + this.SetCurrentPageX(c.selectedIndex, true); + else + this.SetCurrentPageY(c.selectedIndex, true); + } + } + + void UpdatePageController() + { + if (_pageController != null && !_pageController.changing) + { + int index; + if (_scrollType == ScrollType.Horizontal) + index = this.currentPageX; + else + index = this.currentPageY; + if (index < _pageController.pageCount) + { + Controller c = _pageController; + _pageController = null; //防止HandleControllerChanged的调用 + c.selectedIndex = index; + _pageController = c; + } + } + } + + internal void AdjustMaskContainer() + { + float mx, my; + if (_displayOnLeft && _vtScrollBar != null && !_floating) + mx = Mathf.FloorToInt(_owner.margin.left + _vtScrollBar.width); + else + mx = _owner.margin.left; + my = _owner.margin.top; + mx += _owner._alignOffset.x; + my += _owner._alignOffset.y; + + _maskContainer.SetXY(mx, my); + } + + void SetSize(float aWidth, float aHeight) + { + AdjustMaskContainer(); + + if (_hzScrollBar != null) + { + _hzScrollBar.y = aHeight - _hzScrollBar.height; + if (_vtScrollBar != null) + { + _hzScrollBar.width = aWidth - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; + if (_displayOnLeft) + _hzScrollBar.x = _scrollBarMargin.left + _vtScrollBar.width; + else + _hzScrollBar.x = _scrollBarMargin.left; + } + else + { + _hzScrollBar.width = aWidth - _scrollBarMargin.left - _scrollBarMargin.right; + _hzScrollBar.x = _scrollBarMargin.left; + } + } + if (_vtScrollBar != null) + { + if (!_displayOnLeft) + _vtScrollBar.x = aWidth - _vtScrollBar.width; + if (_hzScrollBar != null) + _vtScrollBar.height = aHeight - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + else + _vtScrollBar.height = aHeight - _scrollBarMargin.top - _scrollBarMargin.bottom; + _vtScrollBar.y = _scrollBarMargin.top; + } + + _viewSize.x = aWidth; + _viewSize.y = aHeight; + if (_hzScrollBar != null && !_floating) + _viewSize.y -= _hzScrollBar.height; + if (_vtScrollBar != null && !_floating) + _viewSize.x -= _vtScrollBar.width; + _viewSize.x -= (_owner.margin.left + _owner.margin.right); + _viewSize.y -= (_owner.margin.top + _owner.margin.bottom); + + _viewSize.x = Mathf.Max(1, _viewSize.x); + _viewSize.y = Mathf.Max(1, _viewSize.y); + _pageSize.x = _viewSize.x; + _pageSize.y = _viewSize.y; + + HandleSizeChanged(); + } + + internal void SetContentSize(float aWidth, float aHeight) + { + if (Mathf.Approximately(_contentSize.x, aWidth) && Mathf.Approximately(_contentSize.y, aHeight)) + return; + + _contentSize.x = aWidth; + _contentSize.y = aHeight; + HandleSizeChanged(); + } + + /// + /// 内部使用。由虚拟列表调用。在滚动时修改显示内容的大小,需要进行修正,避免滚动跳跃。 + /// + /// + /// + /// + /// + internal void ChangeContentSizeOnScrolling(float deltaWidth, float deltaHeight, float deltaPosX, float deltaPosY) + { + bool isRightmost = _xPos == _overlapSize.x; + bool isBottom = _yPos == _overlapSize.y; + + _contentSize.x += deltaWidth; + _contentSize.y += deltaHeight; + HandleSizeChanged(); + + if (_tweening == 1) + { + //如果原来滚动位置是贴边,加入处理继续贴边。 + if (deltaWidth != 0 && isRightmost && _tweenChange.x < 0) + { + _xPos = _overlapSize.x; + _tweenChange.x = -_xPos - _tweenStart.x; + } + + if (deltaHeight != 0 && isBottom && _tweenChange.y < 0) + { + _yPos = _overlapSize.y; + _tweenChange.y = -_yPos - _tweenStart.y; + } + } + else if (_tweening == 2) + { + //重新调整起始位置,确保能够顺滑滚下去 + if (deltaPosX != 0) + { + _container.x -= deltaPosX; + _tweenStart.x -= deltaPosX; + _xPos = -_container.x; + } + if (deltaPosY != 0) + { + _container.y -= deltaPosY; + _tweenStart.y -= deltaPosY; + _yPos = -_container.y; + } + } + else if (_dragged) + { + if (deltaPosX != 0) + { + _container.x -= deltaPosX; + _containerPos.x -= deltaPosX; + _xPos = -_container.x; + } + if (deltaPosY != 0) + { + _container.y -= deltaPosY; + _containerPos.y -= deltaPosY; + _yPos = -_container.y; + } + } + else + { + //如果原来滚动位置是贴边,加入处理继续贴边。 + if (deltaWidth != 0 && isRightmost) + { + _xPos = _overlapSize.x; + _container.x = -_xPos; + } + + if (deltaHeight != 0 && isBottom) + { + _yPos = _overlapSize.y; + _container.y = -_yPos; + } + } + + if (_pageMode) + UpdatePageController(); + } + + void HandleSizeChanged() + { + if (_displayInDemand) + { + _vScrollNone = _contentSize.y <= _viewSize.y; + _hScrollNone = _contentSize.x <= _viewSize.x; + + if (_vtScrollBar != null && _hzScrollBar != null) + { + if (!_hScrollNone) + _vtScrollBar.height = _owner.height - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + else + _vtScrollBar.height = _owner.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + + if (!_vScrollNone) + _hzScrollBar.width = _owner.width - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; + else + _hzScrollBar.width = _owner.width - _scrollBarMargin.left - _scrollBarMargin.right; + } + } + + if (_vtScrollBar != null) + { + if (_contentSize.y == 0) + _vtScrollBar.SetDisplayPerc(0); + else + _vtScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.y / _contentSize.y)); + } + if (_hzScrollBar != null) + { + if (_contentSize.x == 0) + _hzScrollBar.SetDisplayPerc(0); + else + _hzScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.x / _contentSize.x)); + } + + UpdateScrollBarVisible(); + + if (!_maskDisabled) + { + Rect rect = new Rect(-_owner._alignOffset.x, -_owner._alignOffset.y, _viewSize.x, _viewSize.y); + if (_vScrollNone && _vtScrollBar != null) + rect.width += _vtScrollBar.width; + if (_hScrollNone && _hzScrollBar != null) + rect.height += _hzScrollBar.height; + if (_dontClipMargin) + { + rect.x -= _owner.margin.left; + rect.width += (_owner.margin.left + _owner.margin.right); + rect.y -= _owner.margin.top; + rect.height += (_owner.margin.top + _owner.margin.bottom); + } + + _maskContainer.clipRect = rect; + } + + if (_scrollType == ScrollType.Horizontal || _scrollType == ScrollType.Both) + _overlapSize.x = Mathf.CeilToInt(Math.Max(0, _contentSize.x - _viewSize.x)); + else + _overlapSize.x = 0; + if (_scrollType == ScrollType.Vertical || _scrollType == ScrollType.Both) + _overlapSize.y = Mathf.CeilToInt(Math.Max(0, _contentSize.y - _viewSize.y)); + else + _overlapSize.y = 0; + + //边界检查 + _xPos = Mathf.Clamp(_xPos, 0, _overlapSize.x); + _yPos = Mathf.Clamp(_yPos, 0, _overlapSize.y); + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + if (_refreshBarAxis == 0) + _container.SetXY(Mathf.Clamp(_container.x, -max, _headerLockedSize), Mathf.Clamp(_container.y, -_overlapSize.y, 0)); + else + _container.SetXY(Mathf.Clamp(_container.x, -_overlapSize.x, 0), Mathf.Clamp(_container.y, -max, _headerLockedSize)); + + if (_header != null) + { + if (_refreshBarAxis == 0) + _header.height = _viewSize.y; + else + _header.width = _viewSize.x; + } + + if (_footer != null) + { + if (_refreshBarAxis == 0) + _footer.height = _viewSize.y; + else + _footer.width = _viewSize.x; + } + + UpdateScrollBarPos(); + if (_pageMode) + UpdatePageController(); + } + + private void PosChanged(bool ani) + { + //只要有1处要求不要缓动,那就不缓动 + if (_aniFlag == 0) + _aniFlag = ani ? 1 : -1; + else if (_aniFlag == 1 && !ani) + _aniFlag = -1; + + _needRefresh = true; + + UpdateContext.OnBegin -= _refreshDelegate; + UpdateContext.OnBegin += _refreshDelegate; + } + + private void Refresh() + { + _needRefresh = false; + UpdateContext.OnBegin -= _refreshDelegate; + + if (_owner.displayObject == null || _owner.displayObject.isDisposed) + return; + + if (_pageMode || _snapToItem) + { + Vector2 pos = new Vector2(-_xPos, -_yPos); + AlignPosition(ref pos, false); + _xPos = -pos.x; + _yPos = -pos.y; + } + + Refresh2(); + + _onScroll.Call(); + if (_needRefresh) //在onScroll事件里开发者可能修改位置,这里再刷新一次,避免闪烁 + { + _needRefresh = false; + UpdateContext.OnBegin -= _refreshDelegate; + + Refresh2(); + } + + UpdateScrollBarPos(); + _aniFlag = 0; + } + + void Refresh2() + { + if (_aniFlag == 1 && !_dragged) + { + Vector2 pos = new Vector2(); + + if (_overlapSize.x > 0) + pos.x = -(int)_xPos; + else + { + if (_container.x != 0) + _container.x = 0; + pos.x = 0; + } + if (_overlapSize.y > 0) + pos.y = -(int)_yPos; + else + { + if (_container.y != 0) + _container.y = 0; + pos.y = 0; + } + + if (pos.x != _container.x || pos.y != _container.y) + { + // [Y 修改] + if (m_animTweenTime == 0f) + { + _tweenDuration = new Vector2(TWEEN_TIME_GO, TWEEN_TIME_GO); + } + else + { + _tweenDuration = new Vector2(m_animTweenTime, m_animTweenTime); + } + //_tweenDuration = new Vector2(TWEEN_TIME_GO, TWEEN_TIME_GO); + + _tweenStart = _container.xy; + _tweenChange = pos - _tweenStart; + StartTween(1); + } + else if (_tweening != 0) + KillTween(); + } + else + { + if (_tweening != 0) + KillTween(); + + _container.SetXY((int)-_xPos, (int)-_yPos); + + LoopCheckingCurrent(); + } + + if (_pageMode) + UpdatePageController(); + } + + private void __touchBegin(EventContext context) + { + if (!_touchEffect) + return; + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + Vector2 pt = _owner.GlobalToLocal(evt.position); + + if (_tweening != 0) + { + KillTween(); + Stage.inst.CancelClick(evt.touchId); + + //立刻停止惯性滚动,可能位置不对齐,设定这个标志,使touchEnd时归位 + _dragged = true; + } + else + _dragged = false; + + _containerPos = _container.xy; + _beginTouchPos = _lastTouchPos = pt; + _lastTouchGlobalPos = evt.position; + _isHoldAreaDone = false; + _velocity = Vector2.zero; + _velocityScale = 1; + _lastMoveTime = Time.unscaledTime; + } + + private void __touchMove(EventContext context) + { + if (!_touchEffect || draggingPane != null && draggingPane != this || GObject.draggingObject != null) //已经有其他拖动 + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = _owner.GlobalToLocal(evt.position); + if (float.IsNaN(pt.x)) + return; + + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchScrollSensitivity; + else + sensitivity = 8; + + float diff; + bool sv = false, sh = false; + + if (_scrollType == ScrollType.Vertical) + { + if (!_isHoldAreaDone) + { + //表示正在监测垂直方向的手势 + _gestureFlag |= 1; + + diff = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < sensitivity) + return; + + if ((_gestureFlag & 2) != 0) //已经有水平方向的手势在监测,那么我们用严格的方式检查是不是按垂直方向移动,避免冲突 + { + float diff2 = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < diff2) //不通过则不允许滚动了 + return; + } + } + + sv = true; + } + else if (_scrollType == ScrollType.Horizontal) + { + if (!_isHoldAreaDone) + { + _gestureFlag |= 2; + + diff = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < sensitivity) + return; + + if ((_gestureFlag & 1) != 0) + { + float diff2 = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < diff2) + return; + } + } + + sh = true; + } + else + { + _gestureFlag = 3; + + if (!_isHoldAreaDone) + { + diff = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < sensitivity) + { + diff = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < sensitivity) + return; + } + } + + sv = sh = true; + } + + Vector2 newPos = _containerPos + pt - _beginTouchPos; + newPos.x = (int)newPos.x; + newPos.y = (int)newPos.y; + + if (sv) + { + if (newPos.y > 0) + { + if (!_bouncebackEffect) + _container.y = 0; + else if (_header != null && _header.maxHeight != 0) + _container.y = (int)Mathf.Min(newPos.y * 0.5f, _header.maxHeight); + else + _container.y = (int)Mathf.Min(newPos.y * 0.5f, _viewSize.y * PULL_RATIO); + } + else if (newPos.y < -_overlapSize.y) + { + if (!_bouncebackEffect) + _container.y = -_overlapSize.y; + else if (_footer != null && _footer.maxHeight > 0) + _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_footer.maxHeight) - _overlapSize.y; + else + _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_viewSize.y * PULL_RATIO) - _overlapSize.y; + } + else + _container.y = newPos.y; + } + + if (sh) + { + if (newPos.x > 0) + { + if (!_bouncebackEffect) + _container.x = 0; + else if (_header != null && _header.maxWidth != 0) + _container.x = (int)Mathf.Min(newPos.x * 0.5f, _header.maxWidth); + else + _container.x = (int)Mathf.Min(newPos.x * 0.5f, _viewSize.x * PULL_RATIO); + } + else if (newPos.x < 0 - _overlapSize.x) + { + if (!_bouncebackEffect) + _container.x = -_overlapSize.x; + else if (_footer != null && _footer.maxWidth > 0) + _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_footer.maxWidth) - _overlapSize.x; + else + _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_viewSize.x * PULL_RATIO) - _overlapSize.x; + } + else + _container.x = newPos.x; + } + + //更新速度 + float deltaTime = Time.unscaledDeltaTime; + float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; + if (elapsed > 1) //速度衰减 + _velocity = _velocity * Mathf.Pow(0.833f, elapsed); + Vector2 deltaPosition = pt - _lastTouchPos; + if (!sh) + deltaPosition.x = 0; + if (!sv) + deltaPosition.y = 0; + _velocity = Vector2.Lerp(_velocity, deltaPosition / deltaTime, deltaTime * 10); + + /*速度计算使用的是本地位移,但在后续的惯性滚动判断中需要用到屏幕位移,所以这里要记录一个位移的比例。 + *后续的处理要使用这个比例但不使用坐标转换的方法的原因是,在曲面UI等异形UI中,还无法简单地进行屏幕坐标和本地坐标的转换。 + */ + Vector2 deltaGlobalPosition = _lastTouchGlobalPos - evt.position; + if (deltaPosition.x != 0) + _velocityScale = Mathf.Abs(deltaGlobalPosition.x / deltaPosition.x); + else if (deltaPosition.y != 0) + _velocityScale = Mathf.Abs(deltaGlobalPosition.y / deltaPosition.y); + + _lastTouchPos = pt; + _lastTouchGlobalPos = evt.position; + _lastMoveTime = Time.unscaledTime; + + //同步更新pos值 + if (_overlapSize.x > 0) + _xPos = Mathf.Clamp(-_container.x, 0, _overlapSize.x); + if (_overlapSize.y > 0) + _yPos = Mathf.Clamp(-_container.y, 0, _overlapSize.y); + + //循环滚动特别检查 + if (_loop != 0) + { + newPos = _container.xy; + if (LoopCheckingCurrent()) + _containerPos += _container.xy - newPos; + } + + draggingPane = this; + _isHoldAreaDone = true; + _dragged = true; + + UpdateScrollBarPos(); + UpdateScrollBarVisible(); + if (_pageMode) + UpdatePageController(); + _onScroll.Call(); + } + + private void __touchEnd(EventContext context) + { + if (draggingPane == this) + draggingPane = null; + + _gestureFlag = 0; + + if (!_dragged || !_touchEffect) + { + _dragged = false; + return; + } + + _dragged = false; + _tweenStart = _container.xy; + + Vector2 endPos = _tweenStart; + bool flag = false; + if (_container.x > 0) + { + endPos.x = 0; + flag = true; + } + else if (_container.x < -_overlapSize.x) + { + endPos.x = -_overlapSize.x; + flag = true; + } + if (_container.y > 0) + { + endPos.y = 0; + flag = true; + } + else if (_container.y < -_overlapSize.y) + { + endPos.y = -_overlapSize.y; + flag = true; + } + + if (flag) + { + _tweenChange = endPos - _tweenStart; + if (_tweenChange.x < -UIConfig.touchDragSensitivity || _tweenChange.y < -UIConfig.touchDragSensitivity) + DispatchEvent("onPullDownRelease", null); + else if (_tweenChange.x > UIConfig.touchDragSensitivity || _tweenChange.y > UIConfig.touchDragSensitivity) + DispatchEvent("onPullUpRelease", null); + + if (_headerLockedSize > 0 && endPos[_refreshBarAxis] == 0) + { + endPos[_refreshBarAxis] = _headerLockedSize; + _tweenChange = endPos - _tweenStart; + } + else if (_footerLockedSize > 0 && endPos[_refreshBarAxis] == -_overlapSize[_refreshBarAxis]) + { + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + endPos[_refreshBarAxis] = -max; + _tweenChange = endPos - _tweenStart; + } + + _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + } + else + { + //更新速度 + if (!_inertiaDisabled) + { + float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; + if (elapsed > 1) + _velocity = _velocity * Mathf.Pow(0.833f, elapsed); + + //根据速度计算目标位置和需要时间 + endPos = UpdateTargetAndDuration(_tweenStart); + } + else + _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + Vector2 oldChange = endPos - _tweenStart; + + //调整目标位置 + LoopCheckingTarget(ref endPos); + if (_pageMode || _snapToItem) + AlignPosition(ref endPos, true); + + _tweenChange = endPos - _tweenStart; + if (_tweenChange.x == 0 && _tweenChange.y == 0) + { + UpdateScrollBarVisible(); + return; + } + + //如果目标位置已调整,随之调整需要时间 + if (_pageMode || _snapToItem) + { + FixDuration(0, oldChange.x); + FixDuration(1, oldChange.y); + } + } + + StartTween(2); + } + + private void __mouseWheel(EventContext context) + { + if (!_mouseWheelEnabled) + return; + + InputEvent evt = context.inputEvent; + //[Y 修改] + float delta = evt.mouseWheelDelta; + delta = Mathf.Sign(delta); + if (_overlapSize.x > 0 && _overlapSize.y == 0) + { + if (_pageMode) + SetPosX(_xPos + _pageSize.x * delta, false); + else + SetPosX(_xPos + _mouseWheelStep * delta, false); + } + else + { + if (_pageMode) + SetPosY(_yPos + _pageSize.y * delta, false); + else + SetPosY(_yPos + _mouseWheelStep * delta, false); + } + //float delta = evt.mouseWheelDelta / Stage.devicePixelRatio; + //if (_snapToItem && Mathf.Abs(delta) < 1) + // delta = Mathf.Sign(delta); + //if (_overlapSize.x > 0 && _overlapSize.y == 0) + //{ + // float step = _pageMode ? _pageSize.x : _scrollStep; + // SetPosX(_xPos + step * delta, false); + //} + //else + //{ + // float step = _pageMode ? _pageSize.y : _scrollStep; + // SetPosY(_yPos + step * delta, false); + //} + } + + private void __rollOver() + { + _hover = true; + UpdateScrollBarVisible(); + } + + private void __rollOut() + { + _hover = false; + UpdateScrollBarVisible(); + } + + internal void UpdateClipSoft() + { + Vector2 softness = _owner.clipSoftness; + if (softness.x != 0 || softness.y != 0) + { + _maskContainer.clipSoftness = new Vector4( + (_container.x >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.x, + (_container.y >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.y, + (-_container.x - _overlapSize.x >= 0) ? 0 : softness.x, + (-_container.y - _overlapSize.y >= 0) ? 0 : softness.y); + } + else + _maskContainer.clipSoftness = null; + } + + private void UpdateScrollBarPos() + { + if (_vtScrollBar != null) + _vtScrollBar.setScrollPerc(_overlapSize.y == 0 ? 0 : Mathf.Clamp(-_container.y, 0, _overlapSize.y) / _overlapSize.y); + + if (_hzScrollBar != null) + _hzScrollBar.setScrollPerc(_overlapSize.x == 0 ? 0 : Mathf.Clamp(-_container.x, 0, _overlapSize.x) / _overlapSize.x); + + UpdateClipSoft(); + CheckRefreshBar(); + } + + public void UpdateScrollBarVisible() + { + if (_vtScrollBar != null) + { + if (_viewSize.y <= _vtScrollBar.minSize || _vScrollNone) + _vtScrollBar.displayObject.visible = false; + else + UpdateScrollBarVisible2(_vtScrollBar); + } + + if (_hzScrollBar != null) + { + if (_viewSize.x <= _hzScrollBar.minSize || _hScrollNone) + _hzScrollBar.displayObject.visible = false; + else + UpdateScrollBarVisible2(_hzScrollBar); + } + } + + private void UpdateScrollBarVisible2(GScrollBar bar) + { + if (_scrollBarDisplayAuto) + GTween.Kill(bar, TweenPropType.Alpha, false); + + if (_scrollBarDisplayAuto && !_hover && _tweening == 0 && !_dragged && !bar.gripDragging) + { + if (bar.displayObject.visible) + GTween.To(1, 0, 0.5f).SetDelay(0.5f).OnComplete(_hideScrollBarDelegate).SetTarget(bar, TweenPropType.Alpha); + } + else + { + bar.alpha = 1; + bar.displayObject.visible = true; + } + } + + private void __barTweenComplete(GTweener tweener) + { + GObject bar = (GObject)tweener.target; + bar.alpha = 1; + bar.displayObject.visible = false; + } + + float GetLoopPartSize(float division, int axis) + { + return (_contentSize[axis] + (axis == 0 ? ((GList)_owner).columnGap : ((GList)_owner).lineGap)) / division; + } + + /// + /// 对当前的滚动位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 + /// + /// + bool LoopCheckingCurrent() + { + bool changed = false; + if (_loop == 1 && _overlapSize.x > 0) + { + if (_xPos < 0.001f) + { + _xPos += GetLoopPartSize(2, 0); + changed = true; + } + else if (_xPos >= _overlapSize.x) + { + _xPos -= GetLoopPartSize(2, 0); + changed = true; + } + } + else if (_loop == 2 && _overlapSize.y > 0) + { + if (_yPos < 0.001f) + { + _yPos += GetLoopPartSize(2, 1); + changed = true; + } + else if (_yPos >= _overlapSize.y) + { + _yPos -= GetLoopPartSize(2, 1); + changed = true; + } + } + + if (changed) + _container.SetXY((int)-_xPos, (int)-_yPos); + + return changed; + } + + /// + /// 对目标位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 + /// + /// + void LoopCheckingTarget(ref Vector2 endPos) + { + if (_loop == 1) + LoopCheckingTarget(ref endPos, 0); + + if (_loop == 2) + LoopCheckingTarget(ref endPos, 1); + } + + void LoopCheckingTarget(ref Vector2 endPos, int axis) + { + if (endPos[axis] > 0) + { + float halfSize = GetLoopPartSize(2, axis); + float tmp = _tweenStart[axis] - halfSize; + if (tmp <= 0 && tmp >= -_overlapSize[axis]) + { + endPos[axis] -= halfSize; + _tweenStart[axis] = tmp; + } + } + else if (endPos[axis] < -_overlapSize[axis]) + { + float halfSize = GetLoopPartSize(2, axis); + float tmp = _tweenStart[axis] + halfSize; + if (tmp <= 0 && tmp >= -_overlapSize[axis]) + { + endPos[axis] += halfSize; + _tweenStart[axis] = tmp; + } + } + } + + void LoopCheckingNewPos(ref float value, int axis) + { + if (_overlapSize[axis] == 0) + return; + + float pos = axis == 0 ? _xPos : _yPos; + bool changed = false; + if (value < 0.001f) + { + value += GetLoopPartSize(2, axis); + if (value > pos) + { + float v = GetLoopPartSize(6, axis); + v = Mathf.CeilToInt((value - pos) / v) * v; + pos = Mathf.Clamp(pos + v, 0, _overlapSize[axis]); + changed = true; + } + } + else if (value >= _overlapSize[axis]) + { + value -= GetLoopPartSize(2, axis); + if (value < pos) + { + float v = GetLoopPartSize(6, axis); + v = Mathf.CeilToInt((pos - value) / v) * v; + pos = Mathf.Clamp(pos - v, 0, _overlapSize[axis]); + changed = true; + } + } + + if (changed) + { + if (axis == 0) + _container.x = -(int)pos; + else + _container.y = -(int)pos; + } + } + + /// + /// 从oldPos滚动至pos,调整pos位置对齐页面、对齐item等(如果需要)。 + /// + /// + /// + void AlignPosition(ref Vector2 pos, bool inertialScrolling) + { + if (_pageMode) + { + pos.x = AlignByPage(pos.x, 0, inertialScrolling); + pos.y = AlignByPage(pos.y, 1, inertialScrolling); + } + else if (_snapToItem) + { + float tmpX = -pos.x; + float tmpY = -pos.y; + float xDir = 0; + float yDir = 0; + if (inertialScrolling) + { + xDir = pos.x - _containerPos.x; + yDir = pos.y - _containerPos.y; + } + _owner.GetSnappingPositionWithDir(ref tmpX, ref tmpY, xDir, yDir); + if (pos.x < 0 && pos.x > -_overlapSize.x) + pos.x = -tmpX; + if (pos.y < 0 && pos.y > -_overlapSize.y) + pos.y = -tmpY; + } + } + + /// + /// 从oldPos滚动至pos,调整目标位置到对齐页面。 + /// + /// + /// + /// + /// + float AlignByPage(float pos, int axis, bool inertialScrolling) + { + int page; + + if (pos > 0) + page = 0; + else if (pos < -_overlapSize[axis]) + page = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; + else + { + page = Mathf.FloorToInt(-pos / _pageSize[axis]); + float change = inertialScrolling ? (pos - _containerPos[axis]) : (pos - _container.xy[axis]); + float testPageSize = Mathf.Min(_pageSize[axis], _contentSize[axis] - (page + 1) * _pageSize[axis]); + float delta = -pos - page * _pageSize[axis]; + + //页面吸附策略 + if (Mathf.Abs(change) > _pageSize[axis])//如果滚动距离超过1页,则需要超过页面的一半,才能到更下一页 + { + if (delta > testPageSize * 0.5f) + page++; + } + else //否则只需要页面的1/3,当然,需要考虑到左移和右移的情况 + { + if (delta > testPageSize * (change < 0 ? UIConfig.defaultScrollPagingThreshold : (1 - UIConfig.defaultScrollPagingThreshold))) + page++; + } + + //重新计算终点 + pos = -page * _pageSize[axis]; + if (pos < -_overlapSize[axis]) //最后一页未必有pageSize那么大 + pos = -_overlapSize[axis]; + } + + //惯性滚动模式下,会增加判断尽量不要滚动超过一页 + if (inertialScrolling) + { + float oldPos = _tweenStart[axis]; + int oldPage; + if (oldPos > 0) + oldPage = 0; + else if (oldPos < -_overlapSize[axis]) + oldPage = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; + else + oldPage = Mathf.FloorToInt(-oldPos / _pageSize[axis]); + int startPage = Mathf.FloorToInt(-_containerPos[axis] / _pageSize[axis]); + if (Mathf.Abs(page - startPage) > 1 && Mathf.Abs(oldPage - startPage) <= 1) + { + if (page > startPage) + page = startPage + 1; + else + page = startPage - 1; + pos = -page * _pageSize[axis]; + } + } + + return pos; + } + + /// + /// 根据当前速度,计算滚动的目标位置,以及到达时间。 + /// + /// + /// + Vector2 UpdateTargetAndDuration(Vector2 orignPos) + { + Vector2 ret = Vector2.zero; + ret.x = UpdateTargetAndDuration(orignPos.x, 0); + ret.y = UpdateTargetAndDuration(orignPos.y, 1); + return ret; + } + + float UpdateTargetAndDuration(float pos, int axis) + { + float v = _velocity[axis]; + float duration = 0; + + if (pos > 0) + pos = 0; + else if (pos < -_overlapSize[axis]) + pos = -_overlapSize[axis]; + else + { + //以屏幕像素为基准 + float v2 = Mathf.Abs(v) * _velocityScale; + //在移动设备上,需要对不同分辨率做一个适配,我们的速度判断以1136分辨率为基准 + if (Stage.touchScreen) + v2 *= 1136f / Mathf.Max(Screen.width, Screen.height); + //这里有一些阈值的处理,因为在低速内,不希望产生较大的滚动(甚至不滚动) + float ratio = 0; + if (_pageMode || !Stage.touchScreen) + { + if (v2 > 500) + ratio = Mathf.Pow((v2 - 500) / 500, 2); + } + else + { + if (v2 > 1000) + ratio = Mathf.Pow((v2 - 1000) / 1000, 2); + } + + if (ratio != 0) + { + if (ratio > 1) + ratio = 1; + + v2 *= ratio; + v *= ratio; + _velocity[axis] = v; + + //算法:v*(_decelerationRate的n次幂)= 60,即在n帧后速度降为60(假设每秒60帧)。 + duration = Mathf.Log(60 / v2, _decelerationRate) / 60; + + //计算距离要使用本地速度 + //理论公式貌似滚动的距离不够,改为经验公式 + //float change = (int)((v/ 60 - 1) / (1 - _decelerationRate)); + float change = (int)(v * duration * 0.4f); + pos += change; + } + } + + if (duration < TWEEN_TIME_DEFAULT) + duration = TWEEN_TIME_DEFAULT; + _tweenDuration[axis] = duration; + + return pos; + } + + /// + /// 根据修改后的tweenChange重新计算减速时间。 + /// + void FixDuration(int axis, float oldChange) + { + if (_tweenChange[axis] == 0 || Mathf.Abs(_tweenChange[axis]) >= Mathf.Abs(oldChange)) + return; + + float newDuration = Mathf.Abs(_tweenChange[axis] / oldChange) * _tweenDuration[axis]; + if (newDuration < TWEEN_TIME_DEFAULT) + newDuration = TWEEN_TIME_DEFAULT; + + _tweenDuration[axis] = newDuration; + } + + void StartTween(int type) + { + _tweenTime.Set(0, 0); + _tweening = type; + Timers.inst.AddUpdate(_tweenUpdateDelegate); + + UpdateScrollBarVisible(); + } + + void KillTween() + { + if (_tweening == 1) //取消类型为1的tween需立刻设置到终点 + { + _container.xy = _tweenStart + _tweenChange; + _onScroll.Call(); + } + + _tweening = 0; + Timers.inst.Remove(_tweenUpdateDelegate); + + UpdateScrollBarVisible(); + + _onScrollEnd.Call(); + } + + void CheckRefreshBar() + { + if (_header == null && _footer == null) + return; + + float pos = _container.xy[_refreshBarAxis]; + if (_header != null) + { + if (pos > 0) + { + if (_header.displayObject.parent == null) + _maskContainer.AddChildAt(_header.displayObject, 0); + Vector2 vec; + + vec = _header.size; + vec[_refreshBarAxis] = pos; + _header.size = vec; + } + else + { + if (_header.displayObject.parent != null) + _maskContainer.RemoveChild(_header.displayObject); + } + } + + if (_footer != null) + { + float max = _overlapSize[_refreshBarAxis]; + if (pos < -max || max == 0 && _footerLockedSize > 0) + { + if (_footer.displayObject.parent == null) + _maskContainer.AddChildAt(_footer.displayObject, 0); + + Vector2 vec; + + vec = _footer.xy; + if (max > 0) + vec[_refreshBarAxis] = pos + _contentSize[_refreshBarAxis]; + else + vec[_refreshBarAxis] = Mathf.Max(Mathf.Min(pos + _viewSize[_refreshBarAxis], _viewSize[_refreshBarAxis] - _footerLockedSize), _viewSize[_refreshBarAxis] - _contentSize[_refreshBarAxis]); + _footer.xy = vec; + + vec = _footer.size; + if (max > 0) + vec[_refreshBarAxis] = -max - pos; + else + vec[_refreshBarAxis] = _viewSize[_refreshBarAxis] - _footer.xy[_refreshBarAxis]; + _footer.size = vec; + } + else + { + if (_footer.displayObject.parent != null) + _maskContainer.RemoveChild(_footer.displayObject); + } + } + } + + void TweenUpdate(object param) + { + if (_owner.displayObject == null || _owner.displayObject.isDisposed) + { + Timers.inst.Remove(_tweenUpdateDelegate); + return; + } + + float nx = RunTween(0); + float ny = RunTween(1); + + _container.SetXY(nx, ny); + + if (_tweening == 2) + { + if (_overlapSize.x > 0) + _xPos = Mathf.Clamp(-nx, 0, _overlapSize.x); + if (_overlapSize.y > 0) + _yPos = Mathf.Clamp(-ny, 0, _overlapSize.y); + + if (_pageMode) + UpdatePageController(); + } + + if (_tweenChange.x == 0 && _tweenChange.y == 0) + { + _tweening = 0; + Timers.inst.Remove(_tweenUpdateDelegate); + + LoopCheckingCurrent(); + + UpdateScrollBarPos(); + UpdateScrollBarVisible(); + + _onScroll.Call(); + _onScrollEnd.Call(); + } + else + { + UpdateScrollBarPos(); + _onScroll.Call(); + } + } + + float RunTween(int axis) + { + float newValue; + if (_tweenChange[axis] != 0) + { + _tweenTime[axis] += Time.unscaledDeltaTime; + if (_tweenTime[axis] >= _tweenDuration[axis]) + { + newValue = _tweenStart[axis] + _tweenChange[axis]; + _tweenChange[axis] = 0; + } + else + { + float ratio = EaseFunc(_tweenTime[axis], _tweenDuration[axis]); + newValue = _tweenStart[axis] + (int)(_tweenChange[axis] * ratio); + } + + float threshold1 = 0; + float threshold2 = -_overlapSize[axis]; + if (_headerLockedSize > 0 && _refreshBarAxis == axis) + threshold1 = _headerLockedSize; + if (_footerLockedSize > 0 && _refreshBarAxis == axis) + { + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + threshold2 = -max; + } + + if (_tweening == 2 && _bouncebackEffect) + { + if (newValue > 20 + threshold1 && _tweenChange[axis] > 0 + || newValue > threshold1 && _tweenChange[axis] == 0)//开始回弹 + { + _tweenTime[axis] = 0; + _tweenDuration[axis] = TWEEN_TIME_DEFAULT; + _tweenChange[axis] = -newValue + threshold1; + _tweenStart[axis] = newValue; + } + else if (newValue < threshold2 - 20 && _tweenChange[axis] < 0 + || newValue < threshold2 && _tweenChange[axis] == 0)//开始回弹 + { + _tweenTime[axis] = 0; + _tweenDuration[axis] = TWEEN_TIME_DEFAULT; + _tweenChange[axis] = threshold2 - newValue; + _tweenStart[axis] = newValue; + } + } + else + { + if (newValue > threshold1) + { + newValue = threshold1; + _tweenChange[axis] = 0; + } + else if (newValue < threshold2) + { + newValue = threshold2; + _tweenChange[axis] = 0; + } + } + } + else + newValue = _container.xy[axis]; + + return newValue; + } + + static float EaseFunc(float t, float d) + { + return (t = t / d - 1) * t * t + 1;//cubicOut + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs.meta new file mode 100644 index 0000000..272e91b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/ScrollPane.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e51675ea70043e1488812e46428e83aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs new file mode 100644 index 0000000..549fe50 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs @@ -0,0 +1,1775 @@ +using System; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public delegate void PlayCompleteCallback(); + + /// + /// + /// + public delegate void TransitionHook(); + + /// + /// + /// + public class Transition : ITweenListener + { + /// + /// 动效的名称。在编辑器里设定。 + /// + public string name { get; private set; } + + /// + /// 当你启动了自动合批,动效里有涉及到XY、大小、旋转等的改变,如果你观察到元件的显示深度在播放过程中有错误,可以开启这个选项。 + /// + public bool invalidateBatchingEveryFrame; + + GComponent _owner; + TransitionItem[] _items; + int _totalTimes; + int _totalTasks; + bool _playing; + bool _paused; + float _ownerBaseX; + float _ownerBaseY; + PlayCompleteCallback _onComplete; + int _options; + bool _reversed; + float _totalDuration; + bool _autoPlay; + int _autoPlayTimes; + float _autoPlayDelay; + float _timeScale; + bool _ignoreEngineTimeScale; + float _startTime; + float _endTime; + GTweenCallback _delayedCallDelegate; + GTweenCallback _checkAllDelegate; + GTweenCallback1 _delayedCallDelegate2; + + const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1; + const int OPTION_AUTO_STOP_DISABLED = 2; + const int OPTION_AUTO_STOP_AT_END = 4; + + public Transition(GComponent owner) + { + _owner = owner; + _timeScale = 1; + _ignoreEngineTimeScale = true; + + _delayedCallDelegate = OnDelayedPlay; + _delayedCallDelegate2 = OnDelayedPlayItem; + _checkAllDelegate = CheckAllComplete; + } + + /// + /// + /// + public void Play() + { + _Play(1, 0, 0, -1, null, false); + } + + /// + /// + /// + /// + public void Play(PlayCompleteCallback onComplete) + { + _Play(1, 0, 0, -1, onComplete, false); + } + + /// + /// + /// + /// + /// + /// + public void Play(int times, float delay, PlayCompleteCallback onComplete) + { + _Play(times, delay, 0, -1, onComplete, false); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete) + { + _Play(times, delay, startTime, endTime, onComplete, false); + } + + /// + /// + /// + public void PlayReverse() + { + _Play(1, 0, 0, -1, null, true); + } + + /// + /// + /// + /// + public void PlayReverse(PlayCompleteCallback onComplete) + { + _Play(1, 0, 0, -1, onComplete, true); + } + + /// + /// + /// + /// + /// + /// + public void PlayReverse(int times, float delay, PlayCompleteCallback onComplete) + { + _Play(times, delay, 0, -1, onComplete, true); + } + + /// + /// + /// + /// + public void ChangePlayTimes(int value) + { + _totalTimes = value; + } + + /// + /// 设置动效是否自动播放。 + /// + /// + /// + /// + public void SetAutoPlay(bool autoPlay, int times, float delay) + { + if (_autoPlay != autoPlay) + { + _autoPlay = autoPlay; + _autoPlayTimes = times; + _autoPlayDelay = delay; + if (_autoPlay) + { + if (_owner.onStage) + Play(times, delay, null); + } + else + { + if (!_owner.onStage) + Stop(false, true); + } + } + } + + void _Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete, bool reverse) + { + Stop(true, true); + + _totalTimes = times; + _reversed = reverse; + _startTime = startTime; + _endTime = endTime; + _playing = true; + _paused = false; + _onComplete = onComplete; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + { + if (item.targetId.Length > 0) + item.target = _owner.GetChildById(item.targetId); + else + item.target = _owner; + } + else if (item.target != _owner && item.target.parent != _owner) //maybe removed + item.target = null; + + if (item.target != null && item.type == TransitionActionType.Transition) + { + TValue_Transition value = (TValue_Transition)item.value; + Transition trans = ((GComponent)item.target).GetTransition(value.transName); + if (trans == this) + trans = null; + if (trans != null) + { + if (value.playTimes == 0) //stop + { + int j; + for (j = i - 1; j >= 0; j--) + { + TransitionItem item2 = _items[j]; + if (item2.type == TransitionActionType.Transition) + { + TValue_Transition value2 = (TValue_Transition)item2.value; + if (value2.trans == trans) + { + value2.stopTime = item.time - item2.time; + break; + } + } + } + if (j < 0) + value.stopTime = 0; + else + trans = null; //no need to handle stop anymore + } + else + value.stopTime = -1; + } + value.trans = trans; + } + } + + if (delay == 0) + OnDelayedPlay(); + else + GTween.DelayedCall(delay).SetTarget(this).OnComplete(_delayedCallDelegate); + } + + /// + /// + /// + public void Stop() + { + Stop(true, false); + } + + /// + /// + /// + /// + /// + public void Stop(bool setToComplete, bool processCallback) + { + if (!_playing) + return; + + _playing = false; + _totalTasks = 0; + _totalTimes = 0; + PlayCompleteCallback func = _onComplete; + _onComplete = null; + + GTween.Kill(this);//delay start + + int cnt = _items.Length; + if (_reversed) + { + for (int i = cnt - 1; i >= 0; i--) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + StopItem(item, setToComplete); + } + } + else + { + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + StopItem(item, setToComplete); + } + } + + if (processCallback && func != null) + func(); + + } + + void StopItem(TransitionItem item, bool setToComplete) + { + if (item.displayLockToken != 0) + { + item.target.ReleaseDisplayLock(item.displayLockToken); + item.displayLockToken = 0; + } + + if (item.tweener != null) + { + item.tweener.Kill(setToComplete); + item.tweener = null; + + if (item.type == TransitionActionType.Shake && !setToComplete) //震动必须归位,否则下次就越震越远了。 + { + item.target._gearLocked = true; + item.target.SetXY(item.target.x - ((TValue_Shake)item.value).lastOffset.x, item.target.y - ((TValue_Shake)item.value).lastOffset.y); + item.target._gearLocked = false; + + _owner.InvalidateBatchingState(true); + } + } + + if (item.type == TransitionActionType.Transition) + { + TValue_Transition value = (TValue_Transition)item.value; + if (value.trans != null) + value.trans.Stop(setToComplete, false); + } + } + + /// + /// + /// + /// + public void SetPaused(bool paused) + { + if (!_playing || _paused == paused) + return; + + _paused = paused; + GTweener tweener = GTween.GetTween(this); + if (tweener != null) + tweener.SetPaused(paused); + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.SetPaused(paused); + } + else if (item.type == TransitionActionType.Animation) + { + if (paused) + { + ((TValue_Animation)item.value).flag = ((IAnimationGear)item.target).playing; + ((IAnimationGear)item.target).playing = false; + } + else + ((IAnimationGear)item.target).playing = ((TValue_Animation)item.value).flag; + } + + if (item.tweener != null) + item.tweener.SetPaused(paused); + } + } + + public void Dispose() + { + if (_playing) + GTween.Kill(this);//delay start + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + { + item.tweener.Kill(); + item.tweener = null; + } + + item.target = null; + item.hook = null; + if (item.tweenConfig != null) + item.tweenConfig.endHook = null; + } + + _playing = false; + _onComplete = null; + } + + /// + /// + /// + public bool playing + { + get { return _playing; } + } + + /// + /// transition's total duration, maybe zero when the transition only has one frame + /// + public float totalDuration + { + get { return _totalDuration; } + } + + /// + /// + /// + /// + /// + public void SetValue(string label, params object[] aParams) + { + int cnt = _items.Length; + object value; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + if (item.tweenConfig != null) + value = item.tweenConfig.startValue; + else + value = item.value; + found = true; + } + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + { + value = item.tweenConfig.endValue; + found = true; + } + else + continue; + + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Pivot: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + { + TValue tvalue = (TValue)value; + tvalue.b1 = true; + tvalue.b2 = true; + tvalue.f1 = Convert.ToSingle(aParams[0]); + tvalue.f2 = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.Alpha: + ((TValue)value).f1 = Convert.ToSingle(aParams[0]); + break; + + case TransitionActionType.Rotation: + ((TValue)value).f1 = Convert.ToSingle(aParams[0]); + break; + + case TransitionActionType.Color: + ((TValue)value).color = (Color)aParams[0]; + break; + + case TransitionActionType.Animation: + { + TValue_Animation tvalue = (TValue_Animation)value; + tvalue.frame = Convert.ToInt32(aParams[0]); + if (aParams.Length > 1) + tvalue.playing = Convert.ToBoolean(aParams[1]); + if (aParams.Length > 2) + tvalue.animationName = (string)aParams[2]; + if (aParams.Length > 3) + tvalue.skinName = (string)aParams[3]; + } + break; + + case TransitionActionType.Visible: + ((TValue_Visible)value).visible = Convert.ToBoolean(aParams[0]); + break; + + case TransitionActionType.Sound: + { + TValue_Sound tvalue = (TValue_Sound)value; + tvalue.sound = (string)aParams[0]; + if (aParams.Length > 1) + tvalue.volume = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.Transition: + { + TValue_Transition tvalue = (TValue_Transition)value; + tvalue.transName = (string)aParams[0]; + if (aParams.Length > 1) + tvalue.playTimes = Convert.ToInt32(aParams[1]); + } + break; + + case TransitionActionType.Shake: + { + ((TValue_Shake)value).amplitude = Convert.ToSingle(aParams[0]); + if (aParams.Length > 1) + ((TValue_Shake)value).duration = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.ColorFilter: + { + TValue tvalue = (TValue)value; + tvalue.f1 = Convert.ToSingle(aParams[0]); + tvalue.f2 = Convert.ToSingle(aParams[1]); + tvalue.f3 = Convert.ToSingle(aParams[2]); + tvalue.f4 = Convert.ToSingle(aParams[3]); + } + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + ((TValue_Text)value).text = (string)aParams[0]; + break; + } + } + + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + /// + /// + public void SetHook(string label, TransitionHook callback) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + item.hook = callback; + found = true; + break; + } + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + { + item.tweenConfig.endHook = callback; + found = true; + break; + } + } + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + public void ClearHooks() + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + item.hook = null; + if (item.tweenConfig != null) + item.tweenConfig.endHook = null; + } + } + + /// + /// + /// + /// + /// + public void SetTarget(string label, GObject newTarget) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + item.targetId = (newTarget == _owner || newTarget == null) ? string.Empty : newTarget.id; + if (_playing) + { + if (item.targetId.Length > 0) + item.target = _owner.GetChildById(item.targetId); + else + item.target = _owner; + } + else + item.target = null; + found = true; + } + } + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + /// + /// + public void SetDuration(string label, float value) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweenConfig != null && item.label == label) + { + item.tweenConfig.duration = value; + found = true; + } + } + + if (!found) + throw new Exception("label not exists or not a tween label"); + } + + /// + /// + /// + /// + /// + public float GetLabelTime(string label) + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + return item.time; + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + return item.time + item.tweenConfig.duration; + } + + return float.NaN; + } + + /// + /// + /// + public float timeScale + { + get { return _timeScale; } + set + { + if (_timeScale != value) + { + _timeScale = value; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + item.tweener.SetTimeScale(value); + else if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.timeScale = value; + } + else if (item.type == TransitionActionType.Animation) + { + if (item.target != null) + ((IAnimationGear)item.target).timeScale = value; + } + } + } + } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _ignoreEngineTimeScale; } + set + { + if (_ignoreEngineTimeScale != value) + { + _ignoreEngineTimeScale = value; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + item.tweener.SetIgnoreEngineTimeScale(value); + else if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.ignoreEngineTimeScale = value; + } + else if (item.type == TransitionActionType.Animation) + { + if (item.target != null) + ((IAnimationGear)item.target).ignoreEngineTimeScale = value; + } + } + } + } + } + + internal void UpdateFromRelations(string targetId, float dx, float dy) + { + int cnt = _items.Length; + if (cnt == 0) + return; + + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.type == TransitionActionType.XY && item.targetId == targetId) + { + if (item.tweenConfig != null) + { + if (!item.tweenConfig.startValue.b3) + { + item.tweenConfig.startValue.f1 += dx; + item.tweenConfig.startValue.f2 += dy; + } + if (!item.tweenConfig.endValue.b3) + { + item.tweenConfig.endValue.f1 += dx; + item.tweenConfig.endValue.f2 += dy; + } + } + else + { + if (!((TValue)item.value).b3) + { + ((TValue)item.value).f1 += dx; + ((TValue)item.value).f2 += dy; + } + } + } + } + } + + internal void OnOwnerAddedToStage() + { + if (_autoPlay && !_playing) + Play(_autoPlayTimes, _autoPlayDelay, null); + } + + internal void OnOwnerRemovedFromStage() + { + if ((_options & OPTION_AUTO_STOP_DISABLED) == 0) + Stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false); + } + + void OnDelayedPlay() + { + InternalPlay(); + + _playing = _totalTasks > 0; + if (_playing) + { + if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0) + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target != null && item.target != _owner) + item.displayLockToken = item.target.AddDisplayLock(); + } + } + } + else if (_onComplete != null) + { + PlayCompleteCallback func = _onComplete; + _onComplete = null; + func(); + } + } + + void InternalPlay() + { + _ownerBaseX = _owner.x; + _ownerBaseY = _owner.y; + + _totalTasks = 1; //prevent to complete inside the loop + + bool needSkipAnimations = false; + int cnt = _items.Length; + if (!_reversed) + { + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + if (item.type == TransitionActionType.Animation && _startTime != 0 && item.time <= _startTime) + { + needSkipAnimations = true; + ((TValue_Animation)item.value).flag = false; + } + else + PlayItem(item); + } + } + else + { + for (int i = cnt - 1; i >= 0; i--) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + PlayItem(item); + } + } + + if (needSkipAnimations) + SkipAnimations(); + + _totalTasks--; + } + + void PlayItem(TransitionItem item) + { + float time; + if (item.tweenConfig != null) + { + if (_reversed) + time = (_totalDuration - item.time - item.tweenConfig.duration); + else + time = item.time; + + if (_endTime == -1 || time <= _endTime) + { + TValue startValue; + TValue endValue; + + if (_reversed) + { + startValue = item.tweenConfig.endValue; + endValue = item.tweenConfig.startValue; + } + else + { + startValue = item.tweenConfig.startValue; + endValue = item.tweenConfig.endValue; + } + + ((TValue)item.value).b1 = startValue.b1 || endValue.b1; + ((TValue)item.value).b2 = startValue.b2 || endValue.b2; + + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + item.tweener = GTween.To(startValue.vec2, endValue.vec2, item.tweenConfig.duration); + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + item.tweener = GTween.To(startValue.f1, endValue.f1, item.tweenConfig.duration); + break; + + case TransitionActionType.Color: + item.tweener = GTween.To(startValue.color, endValue.color, item.tweenConfig.duration); + break; + + case TransitionActionType.ColorFilter: + item.tweener = GTween.To(startValue.vec4, endValue.vec4, item.tweenConfig.duration); + break; + } + + item.tweener.SetDelay(time) + .SetEase(item.tweenConfig.easeType, item.tweenConfig.customEase) + .SetRepeat(item.tweenConfig.repeat, item.tweenConfig.yoyo) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .SetListener(this); + + if (_endTime >= 0) + item.tweener.SetBreakpoint(_endTime - time); + + _totalTasks++; + } + } + else if (item.type == TransitionActionType.Shake) + { + TValue_Shake value = (TValue_Shake)item.value; + + if (_reversed) + time = (_totalDuration - item.time - value.duration); + else + time = item.time; + + if (_endTime == -1 || time <= _endTime) + { + value.lastOffset.Set(0, 0); + value.offset.Set(0, 0); + item.tweener = GTween.Shake(Vector3.zero, value.amplitude, value.duration) + .SetDelay(time) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .SetListener(this); + + if (_endTime >= 0) + item.tweener.SetBreakpoint(_endTime - item.time); + + _totalTasks++; + } + } + else + { + if (_reversed) + time = (_totalDuration - item.time); + else + time = item.time; + + if (time <= _startTime) + { + ApplyValue(item); + CallHook(item, false); + } + else if (_endTime == -1 || time <= _endTime) + { + _totalTasks++; + item.tweener = GTween.DelayedCall(time) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .OnComplete(_delayedCallDelegate2); + } + } + + if (item.tweener != null) + item.tweener.Seek(_startTime); + } + + void SkipAnimations() + { + int frame; + float playStartTime; + float playTotalTime; + TValue_Animation value; + IAnimationGear target; + TransitionItem item; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + item = _items[i]; + if (item.type != TransitionActionType.Animation || item.time > _startTime) + continue; + + value = (TValue_Animation)item.value; + if (value.flag) + continue; + + target = (IAnimationGear)item.target; + frame = target.frame; + playStartTime = target.playing ? 0 : -1; + playTotalTime = 0; + + for (int j = i; j < cnt; j++) + { + item = _items[j]; + if (item.type != TransitionActionType.Animation || item.target != target || item.time > _startTime) + continue; + + value = (TValue_Animation)item.value; + value.flag = true; + + if (value.frame != -1) + { + frame = value.frame; + if (value.playing) + playStartTime = item.time; + else + playStartTime = -1; + playTotalTime = 0; + } + else + { + if (value.playing) + { + if (playStartTime < 0) + playStartTime = item.time; + } + else + { + if (playStartTime >= 0) + playTotalTime += (item.time - playStartTime); + playStartTime = -1; + } + } + + CallHook(item, false); + } + + if (playStartTime >= 0) + playTotalTime += (_startTime - playStartTime); + + target.playing = playStartTime >= 0; + target.frame = frame; + if (playTotalTime > 0) + target.Advance(playTotalTime); + } + } + + void OnDelayedPlayItem(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + item.tweener = null; + _totalTasks--; + + ApplyValue(item); + CallHook(item, false); + + CheckAllComplete(); + } + + public void OnTweenStart(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + + if (item.type == TransitionActionType.XY || item.type == TransitionActionType.Size) //位置和大小要到start才最终确认起始值 + { + TValue startValue; + TValue endValue; + + if (_reversed) + { + startValue = item.tweenConfig.endValue; + endValue = item.tweenConfig.startValue; + } + else + { + startValue = item.tweenConfig.startValue; + endValue = item.tweenConfig.endValue; + } + + if (item.type == TransitionActionType.XY) + { + if (item.target != _owner) + { + if (!startValue.b1) + tweener.startValue.x = item.target.x; + else if (startValue.b3) //percent + tweener.startValue.x = startValue.f1 * _owner.width; + + if (!startValue.b2) + tweener.startValue.y = item.target.y; + else if (startValue.b3) //percent + tweener.startValue.y = startValue.f2 * _owner.height; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + else if (endValue.b3) + tweener.endValue.x = endValue.f1 * _owner.width; + + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + else if (endValue.b3) + tweener.endValue.y = endValue.f2 * _owner.height; + } + else + { + if (!startValue.b1) + tweener.startValue.x = item.target.x - _ownerBaseX; + if (!startValue.b2) + tweener.startValue.y = item.target.y - _ownerBaseY; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + } + } + else + { + if (!startValue.b1) + tweener.startValue.x = item.target.width; + if (!startValue.b2) + tweener.startValue.y = item.target.height; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + } + + if (item.tweenConfig.path != null) + { + ((TValue)item.value).b1 = ((TValue)item.value).b2 = true; + tweener.SetPath(item.tweenConfig.path); + } + } + + CallHook(item, false); + } + + public void OnTweenUpdate(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + ((TValue)item.value).vec2 = tweener.value.vec2; + if (item.tweenConfig.path != null) + { + ((TValue)item.value).f1 += tweener.startValue.x; + ((TValue)item.value).f2 += tweener.startValue.y; + } + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + ((TValue)item.value).f1 = tweener.value.x; + break; + + case TransitionActionType.Color: + ((TValue)item.value).color = tweener.value.color; + break; + + case TransitionActionType.ColorFilter: + ((TValue)item.value).vec4 = tweener.value.vec4; + break; + + case TransitionActionType.Shake: + ((TValue_Shake)item.value).offset = tweener.deltaValue.vec2; + break; + } + ApplyValue(item); + } + + public void OnTweenComplete(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + item.tweener = null; + _totalTasks--; + + if (tweener.allCompleted) //当整体播放结束时间在这个tween的中间时不应该调用结尾钩子 + CallHook(item, true); + + CheckAllComplete(); + } + + void OnPlayTransCompleted(TransitionItem item) + { + _totalTasks--; + + CheckAllComplete(); + } + + void CallHook(TransitionItem item, bool tweenEnd) + { + if (tweenEnd) + { + if (item.tweenConfig != null && item.tweenConfig.endHook != null) + item.tweenConfig.endHook(); + } + else + { + if (item.time >= _startTime && item.hook != null) + item.hook(); + } + } + + void CheckAllComplete() + { + if (_playing && _totalTasks == 0) + { + if (_totalTimes < 0) + { + InternalPlay(); + if (_totalTasks == 0) + GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); + } + else + { + _totalTimes--; + if (_totalTimes > 0) + { + InternalPlay(); + if (_totalTasks == 0) + GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); + } + else + { + _playing = false; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target != null && item.displayLockToken != 0) + { + item.target.ReleaseDisplayLock(item.displayLockToken); + item.displayLockToken = 0; + } + } + + if (_onComplete != null) + { + PlayCompleteCallback func = _onComplete; + _onComplete = null; + func(); + } + } + } + } + } + + void ApplyValue(TransitionItem item) + { + item.target._gearLocked = true; + + switch (item.type) + { + case TransitionActionType.XY: + { + TValue value = (TValue)item.value; + if (item.target == _owner) + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1 + _ownerBaseX, value.f2 + _ownerBaseY); + else if (value.b1) + item.target.x = value.f1 + _ownerBaseX; + else + item.target.y = value.f2 + _ownerBaseY; + } + else + { + if (value.b3) //position in percent + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1 * _owner.width, value.f2 * _owner.height); + else if (value.b1) + item.target.x = value.f1 * _owner.width; + else if (value.b2) + item.target.y = value.f2 * _owner.height; + } + else + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1, value.f2); + else if (value.b1) + item.target.x = value.f1; + else if (value.b2) + item.target.y = value.f2; + } + } + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Size: + { + TValue value = (TValue)item.value; + if (!value.b1) + value.f1 = item.target.width; + if (!value.b2) + value.f2 = item.target.height; + item.target.SetSize(value.f1, value.f2); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Pivot: + item.target.SetPivot(((TValue)item.value).f1, ((TValue)item.value).f2, item.target.pivotAsAnchor); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Alpha: + item.target.alpha = ((TValue)item.value).f1; + break; + + case TransitionActionType.Rotation: + item.target.rotation = ((TValue)item.value).f1; + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Scale: + item.target.SetScale(((TValue)item.value).f1, ((TValue)item.value).f2); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Skew: + item.target.skew = ((TValue)item.value).vec2; + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Color: + ((IColorGear)item.target).color = ((TValue)item.value).color; + break; + + case TransitionActionType.Animation: + { + TValue_Animation value = (TValue_Animation)item.value; + if (value.frame >= 0) + ((IAnimationGear)item.target).frame = value.frame; + ((IAnimationGear)item.target).playing = value.playing; + ((IAnimationGear)item.target).timeScale = _timeScale; + ((IAnimationGear)item.target).ignoreEngineTimeScale = _ignoreEngineTimeScale; + if (value.animationName != null) + ((GLoader3D)item.target).animationName = value.animationName; + if (value.skinName != null) + ((GLoader3D)item.target).skinName = value.skinName; + } + break; + + case TransitionActionType.Visible: + item.target.visible = ((TValue_Visible)item.value).visible; + break; + + case TransitionActionType.Shake: + { + TValue_Shake value = (TValue_Shake)item.value; + item.target.SetXY(item.target.x - value.lastOffset.x + value.offset.x, item.target.y - value.lastOffset.y + value.offset.y); + value.lastOffset = value.offset; + + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Transition: + if (_playing) + { + TValue_Transition value = (TValue_Transition)item.value; + if (value.trans != null) + { + _totalTasks++; + + float startTime = _startTime > item.time ? (_startTime - item.time) : 0; + float endTime = _endTime >= 0 ? (_endTime - item.time) : -1; + if (value.stopTime >= 0 && (endTime < 0 || endTime > value.stopTime)) + endTime = value.stopTime; + value.trans.timeScale = _timeScale; + value.trans.ignoreEngineTimeScale = _ignoreEngineTimeScale; + value.trans._Play(value.playTimes, 0, startTime, endTime, value.playCompleteDelegate, _reversed); + } + } + break; + + case TransitionActionType.Sound: + if (_playing && item.time >= _startTime) + { + TValue_Sound value = (TValue_Sound)item.value; + if (value.audioClip == null) + { + if (UIConfig.soundLoader == null || value.sound.StartsWith(UIPackage.URL_PREFIX)) + value.audioClip = UIPackage.GetItemAssetByURL(value.sound) as NAudioClip; + else + value.audioClip = UIConfig.soundLoader(value.sound); + } + + if (value.audioClip != null && value.audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(value.audioClip.nativeClip, value.volume); + } + break; + + case TransitionActionType.ColorFilter: + { + TValue value = (TValue)item.value; + ColorFilter cf = item.target.filter as ColorFilter; + if (cf == null) + { + cf = new ColorFilter(); + item.target.filter = cf; + } + else + cf.Reset(); + + cf.AdjustBrightness(value.f1); + cf.AdjustContrast(value.f2); + cf.AdjustSaturation(value.f3); + cf.AdjustHue(value.f4); + } + break; + + case TransitionActionType.Text: + item.target.text = ((TValue_Text)item.value).text; + break; + + case TransitionActionType.Icon: + item.target.icon = ((TValue_Text)item.value).text; + break; + } + + item.target._gearLocked = false; + } + + public void Setup(ByteBuffer buffer) + { + this.name = buffer.ReadS(); + _options = buffer.ReadInt(); + _autoPlay = buffer.ReadBool(); + _autoPlayTimes = buffer.ReadInt(); + _autoPlayDelay = buffer.ReadFloat(); + + int cnt = buffer.ReadShort(); + _items = new TransitionItem[cnt]; + for (int i = 0; i < cnt; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + TransitionItem item = new TransitionItem((TransitionActionType)buffer.ReadByte()); + _items[i] = item; + + item.time = buffer.ReadFloat(); + int targetId = buffer.ReadShort(); + if (targetId < 0) + item.targetId = string.Empty; + else + item.targetId = _owner.GetChildAt(targetId).id; + item.label = buffer.ReadS(); + + if (buffer.ReadBool()) + { + buffer.Seek(curPos, 1); + + item.tweenConfig = new TweenConfig(); + item.tweenConfig.duration = buffer.ReadFloat(); + if (item.time + item.tweenConfig.duration > _totalDuration) + _totalDuration = item.time + item.tweenConfig.duration; + item.tweenConfig.easeType = (EaseType)buffer.ReadByte(); + item.tweenConfig.repeat = buffer.ReadInt(); + item.tweenConfig.yoyo = buffer.ReadBool(); + item.tweenConfig.endLabel = buffer.ReadS(); + + buffer.Seek(curPos, 2); + + DecodeValue(item, buffer, item.tweenConfig.startValue); + + buffer.Seek(curPos, 3); + + DecodeValue(item, buffer, item.tweenConfig.endValue); + + if (buffer.version >= 2) + { + var pts = buffer.ReadPath(); + if (pts.Count > 0) + { + item.tweenConfig.path = new GPath(); + item.tweenConfig.path.Create(pts); + } + } + + if (buffer.version >= 4 && item.tweenConfig.easeType == EaseType.Custom) + { + var pts = buffer.ReadPath(); + if (pts.Count > 0) + { + item.tweenConfig.customEase = new CustomEase(); + item.tweenConfig.customEase.Create(pts); + } + } + } + else + { + if (item.time > _totalDuration) + _totalDuration = item.time; + + buffer.Seek(curPos, 2); + + DecodeValue(item, buffer, item.value); + } + + buffer.position = curPos + dataLen; + } + } + + void DecodeValue(TransitionItem item, ByteBuffer buffer, object value) + { + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Pivot: + case TransitionActionType.Skew: + { + TValue tvalue = (TValue)value; + tvalue.b1 = buffer.ReadBool(); + tvalue.b2 = buffer.ReadBool(); + tvalue.f1 = buffer.ReadFloat(); + tvalue.f2 = buffer.ReadFloat(); + + if (buffer.version >= 2 && item.type == TransitionActionType.XY) + tvalue.b3 = buffer.ReadBool(); //percent + } + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + ((TValue)value).f1 = buffer.ReadFloat(); + break; + + case TransitionActionType.Scale: + ((TValue)value).f1 = buffer.ReadFloat(); + ((TValue)value).f2 = buffer.ReadFloat(); + break; + + case TransitionActionType.Color: + ((TValue)value).color = buffer.ReadColor(); + break; + + case TransitionActionType.Animation: + ((TValue_Animation)value).playing = buffer.ReadBool(); + ((TValue_Animation)value).frame = buffer.ReadInt(); + if (buffer.version >= 6) + { + ((TValue_Animation)value).animationName = buffer.ReadS(); + ((TValue_Animation)value).skinName = buffer.ReadS(); + } + break; + + case TransitionActionType.Visible: + ((TValue_Visible)value).visible = buffer.ReadBool(); + break; + + case TransitionActionType.Sound: + ((TValue_Sound)value).sound = buffer.ReadS(); + ((TValue_Sound)value).volume = buffer.ReadFloat(); + break; + + case TransitionActionType.Transition: + ((TValue_Transition)value).transName = buffer.ReadS(); + ((TValue_Transition)value).playTimes = buffer.ReadInt(); + ((TValue_Transition)value).playCompleteDelegate = () => { OnPlayTransCompleted(item); }; + break; + + case TransitionActionType.Shake: + ((TValue_Shake)value).amplitude = buffer.ReadFloat(); + ((TValue_Shake)value).duration = buffer.ReadFloat(); + break; + + case TransitionActionType.ColorFilter: + { + TValue tvalue = (TValue)value; + tvalue.f1 = buffer.ReadFloat(); + tvalue.f2 = buffer.ReadFloat(); + tvalue.f3 = buffer.ReadFloat(); + tvalue.f4 = buffer.ReadFloat(); + } + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + ((TValue_Text)value).text = buffer.ReadS(); + break; + } + } + + public void SetCompleteEvent(PlayCompleteCallback onComplete) + { + _onComplete = onComplete; + } + } + + class TransitionItem + { + public float time; + public string targetId; + public TransitionActionType type; + public TweenConfig tweenConfig; + public string label; + public object value; + public TransitionHook hook; + + //running properties + public GTweener tweener; + public GObject target; + public uint displayLockToken; + + public TransitionItem(TransitionActionType type) + { + this.type = type; + + switch (type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Pivot: + case TransitionActionType.Skew: + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + case TransitionActionType.Color: + case TransitionActionType.ColorFilter: + value = new TValue(); + break; + + case TransitionActionType.Animation: + value = new TValue_Animation(); + break; + + case TransitionActionType.Shake: + value = new TValue_Shake(); + break; + + case TransitionActionType.Sound: + value = new TValue_Sound(); + break; + + case TransitionActionType.Transition: + value = new TValue_Transition(); + break; + + case TransitionActionType.Visible: + value = new TValue_Visible(); + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + value = new TValue_Text(); + break; + } + } + } + + class TweenConfig + { + public float duration; + public EaseType easeType; + public CustomEase customEase; + public int repeat; + public bool yoyo; + + public TValue startValue; + public TValue endValue; + + public string endLabel; + public TransitionHook endHook; + + public GPath path; + + public TweenConfig() + { + easeType = EaseType.QuadOut; + startValue = new TValue(); + endValue = new TValue(); + } + } + + class TValue_Visible + { + public bool visible; + } + + class TValue_Animation + { + public int frame; + public bool playing; + public bool flag; + public string animationName; + public string skinName; + } + + class TValue_Sound + { + public string sound; + public float volume; + public NAudioClip audioClip; + } + + class TValue_Transition + { + public string transName; + public int playTimes; + public Transition trans; + public PlayCompleteCallback playCompleteDelegate; + public float stopTime; + } + + class TValue_Shake + { + public float amplitude; + public float duration; + public Vector2 lastOffset; + public Vector2 offset; + } + + class TValue_Text + { + public string text; + } + + class TValue + { + public float f1; + public float f2; + public float f3; + public float f4; + public bool b1; + public bool b2; + public bool b3; + + public TValue() + { + b1 = true; + b2 = true; + } + + public void Copy(TValue source) + { + this.f1 = source.f1; + this.f2 = source.f2; + this.f3 = source.f3; + this.f4 = source.f4; + this.b1 = source.b1; + this.b2 = source.b2; + } + + public Vector2 vec2 + { + get { return new Vector2(f1, f2); } + set + { + f1 = value.x; + f2 = value.y; + } + } + + public Vector4 vec4 + { + get { return new Vector4(f1, f2, f3, f4); } + set + { + f1 = value.x; + f2 = value.y; + f3 = value.z; + f4 = value.w; + } + } + + public Color color + { + get { return new Color(f1, f2, f3, f4); } + set + { + f1 = value.r; + f2 = value.g; + f3 = value.b; + f4 = value.a; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs.meta new file mode 100644 index 0000000..2e760a2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Transition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b4b16745502a0a428467b2981a2a786 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs new file mode 100644 index 0000000..8fc781d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs @@ -0,0 +1,310 @@ +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class TranslationHelper + { + public static Dictionary> strings; + + /// + /// [Y ޸] + /// + public static Dictionary> elementNameStrings; + + /// + /// [Y ޸] + /// + public static bool HasMultiLangData() + { + if (strings == null || strings.Count == 0) + { + return false; + } + return true; + } + + /// + /// [Y ޸] + /// + public static string GetLangTextByName(string urlId, string rawElementName) + { + Dictionary colMzDict; + if (!elementNameStrings.TryGetValue(urlId, out colMzDict)) + { + return null; + } + string text; + if (!colMzDict.TryGetValue(rawElementName, out text)) + { + return null; + } + return text; + } + + public static void LoadFromXML(XML source) + { + // [Y ޸] + if (strings == null) + { + strings = new Dictionary>(); + } + strings.Clear(); + if (elementNameStrings == null) + { + elementNameStrings = new Dictionary>(); + } + elementNameStrings.Clear(); + + XMLList.Enumerator et = source.GetEnumerator("string"); + while (et.MoveNext()) + { + XML cxml = et.Current; + string key = cxml.GetAttribute("name"); + string text = cxml.text; + int i = key.IndexOf("-"); + if (i == -1) + continue; + + string key2 = key.Substring(0, i); + string key3 = key.Substring(i + 1); + Dictionary col; + if (!strings.TryGetValue(key2, out col)) + { + col = new Dictionary(); + strings[key2] = col; + } + col[key3] = text; + + // [Y ޸] + string urlIdKey = key2; + string rawElementName = cxml.GetAttribute("mz"); + Dictionary colMzDict; + if (!elementNameStrings.TryGetValue(urlIdKey, out colMzDict)) + { + colMzDict = new Dictionary(); + elementNameStrings[urlIdKey] = colMzDict; + } + colMzDict[rawElementName] = text; + } + } + + public static void TranslateComponent(PackageItem item) + { + if (TranslationHelper.strings == null) + return; + + Dictionary strings; + if (!TranslationHelper.strings.TryGetValue(item.owner.id + item.id, out strings)) + return; + + string elementId, value; + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 2); + + int childCount = buffer.ReadShort(); + for (int i = 0; i < childCount; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + ObjectType baseType = (ObjectType)buffer.ReadByte(); + ObjectType type = baseType; + buffer.Skip(4); + elementId = buffer.ReadS(); + + if (type == ObjectType.Component) + { + if (buffer.Seek(curPos, 6)) + type = (ObjectType)buffer.ReadByte(); + } + + buffer.Seek(curPos, 1); + + if (strings.TryGetValue(elementId + "-tips", out value)) + buffer.WriteS(value); + + buffer.Seek(curPos, 2); + + int gearCnt = buffer.ReadShort(); + for (int j = 0; j < gearCnt; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + if (buffer.ReadByte() == 6) //gearText + { + buffer.Skip(2);//controller + int valueCnt = buffer.ReadShort(); + for (int k = 0; k < valueCnt; k++) + { + string page = buffer.ReadS(); + if (page != null) + { + if (strings.TryGetValue(elementId + "-texts_" + k, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + if (buffer.ReadBool() && strings.TryGetValue(elementId + "-texts_def", out value)) + buffer.WriteS(value); + } + + buffer.position = nextPos; + } + + if (baseType == ObjectType.Component && buffer.version >= 2) + { + buffer.Seek(curPos, 4); + + buffer.Skip(2); //pageController + + buffer.Skip(4 * buffer.ReadShort()); + + int cpCount = buffer.ReadShort(); + for (int k = 0; k < cpCount; k++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + if (propertyId == 0 && strings.TryGetValue(elementId + "-cp-" + target, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + switch (type) + { + case ObjectType.Text: + case ObjectType.RichText: + case ObjectType.InputText: + { + if (strings.TryGetValue(elementId, out value)) + { + buffer.Seek(curPos, 6); + buffer.WriteS(value); + } + if (strings.TryGetValue(elementId + "-prompt", out value)) + { + buffer.Seek(curPos, 4); + buffer.WriteS(value); + } + break; + } + + case ObjectType.List: + case ObjectType.Tree: + { + buffer.Seek(curPos, 8); + buffer.Skip(2); + int itemCount = buffer.ReadShort(); + for (int j = 0; j < itemCount; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + buffer.Skip(2); //url + if (type == ObjectType.Tree) + buffer.Skip(2); + + //title + if (strings.TryGetValue(elementId + "-" + j, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + //selected title + if (strings.TryGetValue(elementId + "-" + j + "-0", out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + if (buffer.version >= 2) + { + buffer.Skip(6); + buffer.Skip(buffer.ReadShort() * 4);//controllers + + int cpCount = buffer.ReadShort(); + for (int k = 0; k < cpCount; k++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + if (propertyId == 0 && strings.TryGetValue(elementId + "-" + j + "-" + target, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + buffer.position = nextPos; + } + break; + } + + case ObjectType.Label: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + buffer.Skip(2); + if (buffer.ReadBool()) + buffer.Skip(4); + buffer.Skip(4); + if (buffer.ReadBool() && strings.TryGetValue(elementId + "-prompt", out value)) + buffer.WriteS(value); + } + break; + } + + case ObjectType.Button: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + if (strings.TryGetValue(elementId + "-0", out value)) + buffer.WriteS(value); + } + break; + } + + case ObjectType.ComboBox: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + int itemCount = buffer.ReadShort(); + for (int j = 0; j < itemCount; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + if (strings.TryGetValue(elementId + "-" + j, out value)) + buffer.WriteS(value); + + buffer.position = nextPos; + } + + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + } + + break; + } + } + + buffer.position = curPos + dataLen; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs.meta new file mode 100644 index 0000000..34f54bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/TranslationHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3efa1901e4c7ea44d9573c70d21e49f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree.meta new file mode 100644 index 0000000..33bff35 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4e3a2d82c02599a4f926286440678b58 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs new file mode 100644 index 0000000..7dfcd6a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + [Obsolete("Use GTree and GTreeNode instead")] + public class TreeNode + { + /// + /// + /// + public object data; + + /// + /// + /// + public TreeNode parent { get; private set; } + + /// + /// + /// + public TreeView tree { get; private set; } + + /// + /// + /// + public GComponent cell { get; internal set; } + + /// + /// + /// + public int level { get; private set; } + + private List _children; + private bool _expanded; + + /// + /// + /// + /// + public TreeNode(bool hasChild) + { + if (hasChild) + _children = new List(); + } + + /// + /// + /// + public bool expanded + { + get + { + return _expanded; + } + + set + { + if (_children == null) + return; + + if (_expanded != value) + { + _expanded = value; + if (tree != null) + { + if (_expanded) + tree.AfterExpanded(this); + else + tree.AfterCollapsed(this); + } + } + } + } + + /// + /// + /// + public bool isFolder + { + get { return _children != null; } + } + + /// + /// + /// + public string text + { + get + { + if (cell != null) + return cell.text; + else + return null; + } + } + + /// + /// + /// + /// + /// + public TreeNode AddChild(TreeNode child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// + /// + /// + /// + /// + public TreeNode AddChildAt(TreeNode child, int index) + { + if (child == null) + throw new Exception("child is null"); + + int numChildren = _children.Count; + + if (index >= 0 && index <= numChildren) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + if (child.parent != null) + child.parent.RemoveChild(child); + + int cnt = _children.Count; + if (index == cnt) + _children.Add(child); + else + _children.Insert(index, child); + + child.parent = this; + child.level = this.level + 1; + child.SetTree(this.tree); + if (this.cell != null && this.cell.parent != null && _expanded) + tree.AfterInserted(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public TreeNode RemoveChild(TreeNode child) + { + int childIndex = _children.IndexOf(child); + if (childIndex != -1) + { + RemoveChildAt(childIndex); + } + return child; + } + + /// + /// + /// + /// + /// + public TreeNode RemoveChildAt(int index) + { + if (index >= 0 && index < numChildren) + { + TreeNode child = _children[index]; + _children.RemoveAt(index); + + child.parent = null; + if (tree != null) + { + child.SetTree(null); + tree.AfterRemoved(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public void RemoveChildren(int beginIndex = 0, int endIndex = -1) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex); + } + + /// + /// + /// + /// + /// + public TreeNode GetChildAt(int index) + { + if (index >= 0 && index < numChildren) + return _children[index]; + else + throw new Exception("Invalid child index"); + } + + /// + /// + /// + /// + /// + public int GetChildIndex(TreeNode child) + { + return _children.IndexOf(child); + } + + /// + /// + /// + /// + public TreeNode GetPrevSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i <= 0) + return null; + + return parent._children[i - 1]; + } + + /// + /// + /// + /// + public TreeNode GetNextSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i < 0 || i >= parent._children.Count - 1) + return null; + + return parent._children[i + 1]; + } + + /// + /// + /// + /// + /// + public void SetChildIndex(TreeNode child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new Exception("Not a child of this container"); + + int cnt = _children.Count; + if (index < 0) + index = 0; + else if (index > cnt) + index = cnt; + + if (oldIndex == index) + return; + + _children.RemoveAt(oldIndex); + _children.Insert(index, child); + if (this.cell != null && this.cell.parent != null && _expanded) + tree.AfterMoved(child); + } + + /// + /// + /// + /// + /// + public void SwapChildren(TreeNode child1, TreeNode child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// + /// + /// + /// + public void SwapChildrenAt(int index1, int index2) + { + TreeNode child1 = _children[index1]; + TreeNode child2 = _children[index2]; + + SetChildIndex(child1, index2); + SetChildIndex(child2, index1); + } + + /// + /// + /// + public int numChildren + { + get { return (null == _children) ? 0 : _children.Count; } + } + + internal void SetTree(TreeView value) + { + tree = value; + if (tree != null && tree.treeNodeWillExpand != null && _expanded) + tree.treeNodeWillExpand(this, true); + + if (_children != null) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + TreeNode node = _children[i]; + node.level = level + 1; + node.SetTree(value); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs.meta new file mode 100644 index 0000000..89e2ba2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6bfc19586c7b07e4b9193f658c390727 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs new file mode 100644 index 0000000..563b5c5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs @@ -0,0 +1,490 @@ +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + [Obsolete("Use GTree and GTreeNode instead")] + public class TreeView : EventDispatcher + { + /// + /// TreeView使用的List对象 + /// + public GList list { get; private set; } + + /// + /// TreeView的顶层节点,这是个虚拟节点,也就是他不会显示出来。 + /// + public TreeNode root { get; private set; } + + /// + /// TreeView每级的缩进,单位像素。 + /// + public int indent; + + public delegate GComponent TreeNodeCreateCellDelegate(TreeNode node); + public delegate void TreeNodeRenderDelegate(TreeNode node); + public delegate void TreeNodeWillExpandDelegate(TreeNode node, bool expand); + + /// + /// 当TreeNode需要创建对象的显示对象时回调 + /// + public TreeNodeCreateCellDelegate treeNodeCreateCell; + + /// + /// 当TreeNode需要更新时回调 + /// + public TreeNodeRenderDelegate treeNodeRender; + + /// + /// 当TreeNode即将展开或者收缩时回调。可以在回调中动态增加子节点。 + /// + public TreeNodeWillExpandDelegate treeNodeWillExpand; + + /// + /// 点击任意TreeNode时触发 + /// + public EventListener onClickNode { get; private set; } + + /// + /// 右键点击任意TreeNode时触发 + /// + public EventListener onRightClickNode { get; private set; } + + /// + /// + /// + /// + public TreeView(GList list) + { + this.list = list; + list.onClickItem.Add(__clickItem); + list.onRightClickItem.Add(__clickItem); + list.RemoveChildrenToPool(); + + root = new TreeNode(true); + root.SetTree(this); + root.cell = list; + root.expanded = true; + + indent = 30; + + onClickNode = new EventListener(this, "onClickNode"); + onRightClickNode = new EventListener(this, "onRightClickNode"); + } + + /// + /// + /// + /// + public TreeNode GetSelectedNode() + { + if (list.selectedIndex != -1) + return (TreeNode)list.GetChildAt(list.selectedIndex).data; + else + return null; + } + + /// + /// + /// + /// + public List GetSelection() + { + List sels = list.GetSelection(); + int cnt = sels.Count; + List ret = new List(); + for (int i = 0; i < cnt; i++) + { + TreeNode node = (TreeNode)list.GetChildAt(sels[i]).data; + ret.Add(node); + } + return ret; + } + + /// + /// + /// + /// + /// + public void AddSelection(TreeNode node, bool scrollItToView = false) + { + TreeNode parentNode = node.parent; + while (parentNode != null && parentNode != root) + { + parentNode.expanded = true; + parentNode = parentNode.parent; + } + list.AddSelection(list.GetChildIndex(node.cell), scrollItToView); + } + + /// + /// + /// + /// + public void RemoveSelection(TreeNode node) + { + list.RemoveSelection(list.GetChildIndex(node.cell)); + } + + /// + /// + /// + public void ClearSelection() + { + list.ClearSelection(); + } + + /// + /// + /// + /// + /// + public int GetNodeIndex(TreeNode node) + { + return list.GetChildIndex(node.cell); + } + + /// + /// + /// + /// + public void UpdateNode(TreeNode node) + { + if (node.cell == null) + return; + + if (treeNodeRender != null) + treeNodeRender(node); + } + + /// + /// + /// + /// + public void UpdateNodes(List nodes) + { + int cnt = nodes.Count; + for (int i = 0; i < cnt; i++) + { + TreeNode node = nodes[i]; + if (node.cell == null) + return; + + if (treeNodeRender != null) + treeNodeRender(node); + } + } + + /// + /// + /// + /// + public void ExpandAll(TreeNode folderNode) + { + folderNode.expanded = true; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + ExpandAll(node); + } + } + + /// + /// + /// + /// + public void CollapseAll(TreeNode folderNode) + { + if (folderNode != root) + folderNode.expanded = false; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + CollapseAll(node); + } + } + + /// + /// + /// + /// + void CreateCell(TreeNode node) + { + if (treeNodeCreateCell != null) + node.cell = treeNodeCreateCell(node); + else + node.cell = list.itemPool.GetObject(list.defaultItem) as GComponent; + if (node.cell == null) + throw new Exception("Unable to create tree cell"); + node.cell.data = node; + + GObject indentObj = node.cell.GetChild("indent"); + if (indentObj != null) + indentObj.width = (node.level - 1) * indent; + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + { + if (node.isFolder) + { + expandButton.visible = true; + expandButton.onClick.Add(__clickExpandButton); + expandButton.data = node; + expandButton.selected = node.expanded; + } + else + expandButton.visible = false; + } + + if (treeNodeRender != null) + treeNodeRender(node); + } + + /// + /// + /// + /// + internal void AfterInserted(TreeNode node) + { + CreateCell(node); + + int index = GetInsertIndexForNode(node); + list.AddChildAt(node.cell, index); + if (treeNodeRender != null) + treeNodeRender(node); + + if (node.isFolder && node.expanded) + CheckChildren(node, index); + } + + /// + /// + /// + /// + /// + int GetInsertIndexForNode(TreeNode node) + { + TreeNode prevNode = node.GetPrevSibling(); + if (prevNode == null) + prevNode = node.parent; + int insertIndex = list.GetChildIndex(prevNode.cell) + 1; + int myLevel = node.level; + int cnt = list.numChildren; + for (int i = insertIndex; i < cnt; i++) + { + TreeNode testNode = (TreeNode)list.GetChildAt(i).data; + if (testNode.level <= myLevel) + break; + + insertIndex++; + } + + return insertIndex; + } + + /// + /// + /// + /// + internal void AfterRemoved(TreeNode node) + { + RemoveNode(node); + } + + /// + /// + /// + /// + internal void AfterExpanded(TreeNode node) + { + if (node != root && treeNodeWillExpand != null) + treeNodeWillExpand(node, true); + + if (node.cell == null) + return; + + if (node != root) + { + if (treeNodeRender != null) + treeNodeRender(node); + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + expandButton.selected = true; + } + + if (node.cell.parent != null) + CheckChildren(node, list.GetChildIndex(node.cell)); + } + + /// + /// + /// + /// + internal void AfterCollapsed(TreeNode node) + { + if (node != root && treeNodeWillExpand != null) + treeNodeWillExpand(node, false); + + if (node.cell == null) + return; + + if (node != root) + { + if (treeNodeRender != null) + treeNodeRender(node); + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + expandButton.selected = false; + } + + if (node.cell.parent != null) + HideFolderNode(node); + } + + /// + /// + /// + /// + internal void AfterMoved(TreeNode node) + { + if (!node.isFolder) + list.RemoveChild(node.cell); + else + HideFolderNode(node); + + int index = GetInsertIndexForNode(node); + list.AddChildAt(node.cell, index); + + if (node.isFolder && node.expanded) + CheckChildren(node, index); + } + + /// + /// + /// + /// + /// + /// + int CheckChildren(TreeNode folderNode, int index) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + index++; + TreeNode node = folderNode.GetChildAt(i); + if (node.cell == null) + CreateCell(node); + + if (node.cell.parent == null) + list.AddChildAt(node.cell, index); + + if (node.isFolder && node.expanded) + index = CheckChildren(node, index); + } + + return index; + } + + /// + /// + /// + /// + void HideFolderNode(TreeNode folderNode) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.cell != null) + { + if (node.cell.parent != null) + list.RemoveChild(node.cell); + list.itemPool.ReturnObject(node.cell); + node.cell.data = null; + node.cell = null; + } + if (node.isFolder && node.expanded) + HideFolderNode(node); + } + } + + /// + /// + /// + /// + void RemoveNode(TreeNode node) + { + if (node.cell != null) + { + if (node.cell.parent != null) + list.RemoveChild(node.cell); + list.itemPool.ReturnObject(node.cell); + node.cell.data = null; + node.cell = null; + } + + if (node.isFolder) + { + int cnt = node.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node2 = node.GetChildAt(i); + RemoveNode(node2); + } + } + } + + void __clickExpandButton(EventContext context) + { + context.StopPropagation(); + + GButton expandButton = (GButton)context.sender; + TreeNode node = (TreeNode)expandButton.parent.data; + if (list.scrollPane != null) + { + float posY = list.scrollPane.posY; + if (expandButton.selected) + node.expanded = true; + else + node.expanded = false; + list.scrollPane.posY = posY; + list.scrollPane.ScrollToView(node.cell); + } + else + { + if (expandButton.selected) + node.expanded = true; + else + node.expanded = false; + } + } + + void __clickItem(EventContext context) + { + float posY = 0; + if (list.scrollPane != null) + posY = list.scrollPane.posY; + + TreeNode node = (TreeNode)((GObject)context.data).data; + if (context.type == list.onRightClickItem.type) + onRightClickNode.Call(node); + else + onClickNode.Call(node); + + if (list.scrollPane != null) + { + list.scrollPane.posY = posY; + list.scrollPane.ScrollToView(node.cell); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs.meta new file mode 100644 index 0000000..5de0903 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Tree/TreeView.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5a8a82de90eec564d9b40a4192d27f3d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs new file mode 100644 index 0000000..90b8670 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs @@ -0,0 +1,462 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Global configs. These options should be set before any UI construction. + /// + [AddComponentMenu("FairyGUI/UI Config")] + public class UIConfig : MonoBehaviour + { + /// + /// Dynamic Font Support. + /// 4.x: Put the xxx.ttf into /Resources or /Resources/Fonts, and set defaultFont="xxx". + /// 5.x: set defaultFont to system font name(or names joint with comma). e.g. defaultFont="Microsoft YaHei, SimHei" + /// + public static string defaultFont = "Helvetica"; + + [Obsolete("No use anymore")] + public static bool renderingTextBrighterOnDesktop = true; + + /// + /// Resource using in Window.ShowModalWait for locking the window. + /// + public static string windowModalWaiting; + + /// + /// Resource using in GRoot.ShowModalWait for locking the screen. + /// + public static string globalModalWaiting; + + /// + /// When a modal window is in front, the background becomes dark. + /// + public static Color modalLayerColor = new Color(0f, 0f, 0f, 0.4f); + + /// + /// Default button click sound. + /// + public static NAudioClip buttonSound; + + /// + /// Default button click sound volume. + /// + public static float buttonSoundVolumeScale = 1f; + + /// + /// Resource url of horizontal scrollbar + /// + public static string horizontalScrollBar; + + /// + /// Resource url of vertical scrollbar + /// + public static string verticalScrollBar; + + /// + /// Scrolling step in pixels + /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 + /// 鼠标滚轮触发一次滚动的距离设定为defaultScrollStep*2 + /// + public static float defaultScrollStep = 25; + + /// + /// Deceleration ratio of scrollpane when its in touch dragging. + /// 当手指拖动并释放滚动区域后,内容会滑动一定距离后停下,这个速率就是减速的速率。 + /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 + /// 这个是全局设置,也可以通过ScrollPane.decelerationRate进行个性设置。 + /// + public static float defaultScrollDecelerationRate = 0.967f; + + /// + /// Scrollbar display mode. Recommended 'Auto' for mobile and 'Visible' for web. + /// + public static ScrollBarDisplayType defaultScrollBarDisplay = ScrollBarDisplayType.Default; + + /// + /// Allow dragging anywhere in container to scroll. + /// + public static bool defaultScrollTouchEffect = true; + + /// + /// The "rebound" effect in the scolling container. + /// + public static bool defaultScrollBounceEffect = true; + + /// + /// When the scrolling container is set to "snap to the item", the rolling distance threshold of which item is close to is determined. + /// + public static float defaultScrollSnappingThreshold = 0.5f; + + /// + /// When the scrolling container is set to "page mode", it determines the scrolling distance threshold to which page to turn. + /// + public static float defaultScrollPagingThreshold = 0.3f; + + /// + /// Resources url of PopupMenu. + /// + public static string popupMenu; + + /// + /// Resource url of menu seperator. + /// + public static string popupMenu_seperator; + + /// + /// In case of failure of loading content for GLoader, use this sign to indicate an error. + /// + public static string loaderErrorSign; + + /// + /// Resource url of tooltips. + /// + public static string tooltipsWin; + + /// + /// The number of visible items in ComboBox. + /// + public static int defaultComboBoxVisibleItemCount = 10; + + /// + /// Pixel offsets of finger to trigger scrolling + /// + public static int touchScrollSensitivity = 20; + + /// + /// Pixel offsets of finger to trigger dragging + /// + public static int touchDragSensitivity = 10; + + /// + /// Pixel offsets of mouse pointer to trigger dragging. + /// + public static int clickDragSensitivity = 2; + + /// + /// Allow softness on top or left side for scrollpane. + /// + public static bool allowSoftnessOnTopOrLeftSide = true; + + /// + /// When click the window, brings to front automatically. + /// + public static bool bringWindowToFrontOnClick = true; + + /// + /// + /// + public static float inputCaretSize = 1; + + /// + /// + /// + public static Color inputHighlightColor = new Color32(255, 223, 141, 128); + + /// + /// + /// + public static float frameTimeForAsyncUIConstruction = 0.002f; + + /// + /// if RenderTexture using in painting mode has depth support. + /// + public static bool depthSupportForPaintingMode = true; + + /// + /// Indicates whether to draw extra 4 or 8 times to achieve stroke effect for textfield. + /// If it is true, that is the 8 times, otherwise it is the 4 times. + /// + public static bool enhancedTextOutlineEffect = false; + + [Obsolete("No use anymore.")] + public static VertAlignType richTextRowVerticalAlign = VertAlignType.Bottom; + + /// + /// Suggest to enable it on low dpi (e.g. 96dpi) screens. + /// + public static bool makePixelPerfect = false; + + public enum ConfigKey + { + DefaultFont, + ButtonSound, + ButtonSoundVolumeScale, + HorizontalScrollBar, + VerticalScrollBar, + DefaultScrollStep, + DefaultScrollBarDisplay, + DefaultScrollTouchEffect, + DefaultScrollBounceEffect, + TouchScrollSensitivity, + WindowModalWaiting, + GlobalModalWaiting, + PopupMenu, + PopupMenu_seperator, + LoaderErrorSign, + TooltipsWin, + DefaultComboBoxVisibleItemCount, + TouchDragSensitivity, + ClickDragSensitivity, + ModalLayerColor, + RenderingTextBrighterOnDesktop, + AllowSoftnessOnTopOrLeftSide, + InputCaretSize, + InputHighlightColor, + EnhancedTextOutlineEffect, + DepthSupportForPaintingMode, + RichTextRowVerticalAlign, + Branch, + + PleaseSelect = 100 + } + + [Serializable] + public class ConfigValue + { + public bool valid; + public string s; + public int i; + public float f; + public bool b; + public Color c; + + public void Reset() + { + valid = false; + s = null; + i = 0; + f = 0; + b = false; + c = Color.black; + } + } + + public List Items = new List(); + public List PreloadPackages = new List(); + + void Awake() + { + if (Application.isPlaying) + { + foreach (string packagePath in PreloadPackages) + { + UIPackage.AddPackage(packagePath); + } + + Load(); + } + } + + public void Load() + { + int cnt = Items.Count; + for (int i = 0; i < cnt; i++) + { + ConfigValue value = Items[i]; + if (!value.valid) + continue; + + switch ((UIConfig.ConfigKey)i) + { + case ConfigKey.ButtonSound: + if (Application.isPlaying) + UIConfig.buttonSound = UIPackage.GetItemAssetByURL(value.s) as NAudioClip; + break; + + case ConfigKey.ButtonSoundVolumeScale: + UIConfig.buttonSoundVolumeScale = value.f; + break; + + case ConfigKey.ClickDragSensitivity: + UIConfig.clickDragSensitivity = value.i; + break; + + case ConfigKey.DefaultComboBoxVisibleItemCount: + UIConfig.defaultComboBoxVisibleItemCount = value.i; + break; + + case ConfigKey.DefaultFont: + UIConfig.defaultFont = value.s; + break; + + case ConfigKey.DefaultScrollBarDisplay: + UIConfig.defaultScrollBarDisplay = (ScrollBarDisplayType)value.i; + break; + + case ConfigKey.DefaultScrollBounceEffect: + UIConfig.defaultScrollBounceEffect = value.b; + break; + + case ConfigKey.DefaultScrollStep: + UIConfig.defaultScrollStep = value.i; + break; + + case ConfigKey.DefaultScrollTouchEffect: + UIConfig.defaultScrollTouchEffect = value.b; + break; + + case ConfigKey.GlobalModalWaiting: + UIConfig.globalModalWaiting = value.s; + break; + + case ConfigKey.HorizontalScrollBar: + UIConfig.horizontalScrollBar = value.s; + break; + + case ConfigKey.LoaderErrorSign: + UIConfig.loaderErrorSign = value.s; + break; + + case ConfigKey.ModalLayerColor: + UIConfig.modalLayerColor = value.c; + break; + + case ConfigKey.PopupMenu: + UIConfig.popupMenu = value.s; + break; + + case ConfigKey.PopupMenu_seperator: + UIConfig.popupMenu_seperator = value.s; + break; + + case ConfigKey.TooltipsWin: + UIConfig.tooltipsWin = value.s; + break; + + case ConfigKey.TouchDragSensitivity: + UIConfig.touchDragSensitivity = value.i; + break; + + case ConfigKey.TouchScrollSensitivity: + UIConfig.touchScrollSensitivity = value.i; + break; + + case ConfigKey.VerticalScrollBar: + UIConfig.verticalScrollBar = value.s; + break; + + case ConfigKey.WindowModalWaiting: + UIConfig.windowModalWaiting = value.s; + break; + + case ConfigKey.AllowSoftnessOnTopOrLeftSide: + UIConfig.allowSoftnessOnTopOrLeftSide = value.b; + break; + + case ConfigKey.InputCaretSize: + UIConfig.inputCaretSize = value.i; + break; + + case ConfigKey.InputHighlightColor: + UIConfig.inputHighlightColor = value.c; + break; + + case ConfigKey.DepthSupportForPaintingMode: + UIConfig.depthSupportForPaintingMode = value.b; + break; + + case ConfigKey.EnhancedTextOutlineEffect: + UIConfig.enhancedTextOutlineEffect = value.b; + break; + + case ConfigKey.Branch: + UIPackage.branch = value.s; + break; + } + } + } + + public static void SetDefaultValue(ConfigKey key, ConfigValue value) + { + switch (key) + { + case ConfigKey.ButtonSoundVolumeScale: + value.f = 1; + break; + + case ConfigKey.ClickDragSensitivity: + value.i = 2; + break; + + case ConfigKey.DefaultComboBoxVisibleItemCount: + value.i = 10; + break; + + case ConfigKey.DefaultScrollBarDisplay: + value.i = (int)ScrollBarDisplayType.Default; + break; + + case ConfigKey.DefaultScrollBounceEffect: + case ConfigKey.DefaultScrollTouchEffect: + value.b = true; + break; + + case ConfigKey.DefaultScrollStep: + value.i = 25; + break; + + case ConfigKey.ModalLayerColor: + value.c = new Color(0f, 0f, 0f, 0.4f); + break; + + case ConfigKey.RenderingTextBrighterOnDesktop: + value.b = true; + break; + + case ConfigKey.TouchDragSensitivity: + value.i = 10; + break; + + case ConfigKey.TouchScrollSensitivity: + value.i = 20; + break; + + case ConfigKey.InputCaretSize: + value.i = 1; + break; + + case ConfigKey.InputHighlightColor: + value.c = new Color32(255, 223, 141, 128); + break; + + case ConfigKey.DepthSupportForPaintingMode: + value.b = false; + break; + + case ConfigKey.Branch: + value.s = ""; + break; + } + } + + public static void ClearResourceRefs() + { + UIConfig.defaultFont = ""; + UIConfig.buttonSound = null; + UIConfig.globalModalWaiting = null; + UIConfig.horizontalScrollBar = null; + UIConfig.loaderErrorSign = null; + UIConfig.popupMenu = null; + UIConfig.popupMenu_seperator = null; + UIConfig.tooltipsWin = null; + UIConfig.verticalScrollBar = null; + UIConfig.windowModalWaiting = null; + UIPackage.branch = null; + } + + public void ApplyModifiedProperties() + { + EMRenderSupport.Reload(); + } + + public delegate NAudioClip SoundLoader(string url); + + /// + /// + /// + public static SoundLoader soundLoader = null; + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs.meta new file mode 100644 index 0000000..0ad44a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ace51c3cbb5309547a7029cadaaa20ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs new file mode 100644 index 0000000..8ae77d2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs @@ -0,0 +1,217 @@ +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Content Scaler")] + public class UIContentScaler : MonoBehaviour + { + /// + /// + /// + public enum ScaleMode + { + ConstantPixelSize, + ScaleWithScreenSize, + ConstantPhysicalSize + } + + /// + /// + /// + public enum ScreenMatchMode + { + MatchWidthOrHeight, + MatchWidth, + MatchHeight + } + + /// + /// + /// + public ScaleMode scaleMode; + + /// + /// + /// + public ScreenMatchMode screenMatchMode; + + /// + /// + /// + public int designResolutionX; + + /// + /// + /// + public int designResolutionY; + + /// + /// + /// + public int fallbackScreenDPI = 96; + + /// + /// + /// + public int defaultSpriteDPI = 96; + + /// + /// + /// + public float constantScaleFactor = 1; + + /// + /// 当false时,计算比例时会考虑designResolutionX/Y的设置是针对横屏还是竖屏。否则不考虑。 + /// + public bool ignoreOrientation = false; + + [System.NonSerialized] + public static float scaleFactor = 1; + + [System.NonSerialized] + public static int scaleLevel = 0; + + [System.NonSerialized] + bool _changed; + + void OnEnable() + { + if (Application.isPlaying) + { + //播放模式下都是通过Stage自带的UIContentScaler实现调整的,所以这里只是把参数传过去 + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + if (scaler != this) + { + scaler.scaleMode = scaleMode; + if (scaleMode == ScaleMode.ScaleWithScreenSize) + { + scaler.designResolutionX = designResolutionX; + scaler.designResolutionY = designResolutionY; + scaler.screenMatchMode = screenMatchMode; + scaler.ignoreOrientation = ignoreOrientation; + } + else if (scaleMode == ScaleMode.ConstantPhysicalSize) + { + scaler.fallbackScreenDPI = fallbackScreenDPI; + scaler.defaultSpriteDPI = defaultSpriteDPI; + } + else + { + scaler.constantScaleFactor = constantScaleFactor; + } + scaler.ApplyChange(); + GRoot.inst.ApplyContentScaleFactor(); + } + } + else //Screen width/height is not reliable in OnEnable in editmode + _changed = true; + } + + void Update() + { + if (_changed) + { + _changed = false; + ApplyChange(); + } + } + + void OnDestroy() + { + if (!Application.isPlaying) + { + scaleFactor = 1; + scaleLevel = 0; + } + } + + //For UIContentScalerEditor Only, as the Screen.width/height is not correct in OnInspectorGUI + /// + /// + /// + public void ApplyModifiedProperties() + { + _changed = true; + } + + /// + /// + /// + public void ApplyChange() + { + float screenWidth; + float screenHeight; + + if (Application.isPlaying) //In case of multi display, we keep using the display which Stage object resides. + { + screenWidth = Stage.inst.width; + screenHeight = Stage.inst.height; + } + else + { + screenWidth = Screen.width; + screenHeight = Screen.height; + } + if (scaleMode == ScaleMode.ScaleWithScreenSize) + { + if (designResolutionX == 0 || designResolutionY == 0) + return; + + int dx = designResolutionX; + int dy = designResolutionY; + if (!ignoreOrientation && (screenWidth > screenHeight && dx < dy || screenWidth < screenHeight && dx > dy)) + { + //scale should not change when orientation change + int tmp = dx; + dx = dy; + dy = tmp; + } + + if (screenMatchMode == ScreenMatchMode.MatchWidthOrHeight) + { + float s1 = (float)screenWidth / dx; + float s2 = (float)screenHeight / dy; + scaleFactor = Mathf.Min(s1, s2); + } + else if (screenMatchMode == ScreenMatchMode.MatchWidth) + scaleFactor = (float)screenWidth / dx; + else + scaleFactor = (float)screenHeight / dy; + } + else if (scaleMode == ScaleMode.ConstantPhysicalSize) + { + float dpi = Screen.dpi; + if (dpi == 0) + dpi = fallbackScreenDPI; + if (dpi == 0) + dpi = 96; + scaleFactor = dpi / (defaultSpriteDPI == 0 ? 96 : defaultSpriteDPI); + } + else + scaleFactor = constantScaleFactor; + + if (scaleFactor > 10) + scaleFactor = 10; + + UpdateScaleLevel(); + + StageCamera.screenSizeVer++; + } + + void UpdateScaleLevel() + { + if (scaleFactor > 3) + scaleLevel = 3; //x4 + else if (scaleFactor > 2) + scaleLevel = 2; //x3 + else if (scaleFactor > 1) + scaleLevel = 1; //x2 + else + scaleLevel = 0; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs.meta new file mode 100644 index 0000000..90f3a1c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIContentScaler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a723f7fd716aac049aa24e9186f18685 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs new file mode 100644 index 0000000..3a2f954 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public class UIObjectFactory + { + public delegate GComponent GComponentCreator(); + public delegate GLoader GLoaderCreator(); + + static Dictionary packageItemExtensions = new Dictionary(); + static GLoaderCreator loaderCreator; + + /// + /// + /// + /// + /// + public static void SetPackageItemExtension(string url, System.Type type) + { + SetPackageItemExtension(url, () => { return (GComponent)Activator.CreateInstance(type); }); + } + + /// + /// + /// + /// + /// + public static void SetPackageItemExtension(string url, GComponentCreator creator) + { + if (url == null) + throw new Exception("Invaild url: " + url); + + PackageItem pi = UIPackage.GetItemByURL(url); + if (pi != null) + pi.extensionCreator = creator; + + packageItemExtensions[url] = creator; + } + +#if FAIRYGUI_TOLUA + public static void SetExtension(string url, System.Type baseType, LuaFunction extendFunction) + { + SetPackageItemExtension(url, () => + { + GComponent gcom = (GComponent)Activator.CreateInstance(baseType); + + extendFunction.BeginPCall(); + extendFunction.Push(gcom); + extendFunction.PCall(); + gcom.SetLuaPeer(extendFunction.CheckLuaTable()); + extendFunction.EndPCall(); + + return gcom; + }); + } +#endif + + /// + /// + /// + /// + public static void SetLoaderExtension(System.Type type) + { + loaderCreator = () => { return (GLoader)Activator.CreateInstance(type); }; + } + + /// + /// + /// + /// + public static void SetLoaderExtension(GLoaderCreator creator) + { + loaderCreator = creator; + } + + internal static void ResolvePackageItemExtension(PackageItem pi) + { + if (!packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.id + pi.id, out pi.extensionCreator) + && !packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.name + "/" + pi.name, out pi.extensionCreator)) + pi.extensionCreator = null; + } + + public static void Clear() + { + packageItemExtensions.Clear(); + loaderCreator = null; + } + + /// + /// + /// + /// + /// + /// + public static GObject NewObject(PackageItem pi, System.Type userClass = null) + { + GObject obj; + if (pi.type == PackageItemType.Component) + { + if (userClass != null) + { + Stats.LatestObjectCreation++; + obj = (GComponent)Activator.CreateInstance(userClass); + } + else if (pi.extensionCreator != null) + { + Stats.LatestObjectCreation++; + obj = pi.extensionCreator(); + } + else + obj = NewObject(pi.objectType); + } + else + obj = NewObject(pi.objectType); + + if (obj != null) + obj.packageItem = pi; + + return obj; + } + + /// + /// + /// + /// + /// + public static GObject NewObject(ObjectType type) + { + Stats.LatestObjectCreation++; + + switch (type) + { + case ObjectType.Image: + return new GImage(); + + case ObjectType.MovieClip: + return new GMovieClip(); + + case ObjectType.Component: + return new GComponent(); + + case ObjectType.Text: + return new GTextField(); + + case ObjectType.RichText: + return new GRichTextField(); + + case ObjectType.InputText: + return new GTextInput(); + + case ObjectType.Group: + return new GGroup(); + + case ObjectType.List: + return new GList(); + + case ObjectType.Graph: + return new GGraph(); + + case ObjectType.Loader: + if (loaderCreator != null) + return loaderCreator(); + else + return new GLoader(); + + case ObjectType.Button: + return new GButton(); + + case ObjectType.Label: + return new GLabel(); + + case ObjectType.ProgressBar: + return new GProgressBar(); + + case ObjectType.Slider: + return new GSlider(); + + case ObjectType.ScrollBar: + return new GScrollBar(); + + case ObjectType.ComboBox: + return new GComboBox(); + + case ObjectType.Tree: + return new GTree(); + + case ObjectType.Loader3D: + return new GLoader3D(); + + default: + return null; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs.meta new file mode 100644 index 0000000..81ad36b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIObjectFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 461feec05183bbf4f908aa1455325715 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs new file mode 100644 index 0000000..7c80c7f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs @@ -0,0 +1,1711 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using FairyGUI.Utils; +using ScrewsMaster.Editor; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace FairyGUI +{ + /// + /// A UI Package contains a description file and some texture, sound assets. + /// + public class UIPackage + { + /// + /// Unload UIAssetBundle by FairyGUI system. + /// if use AssetBundlesManager set value to false + /// then unload UIAssetBundle by AssetBundlesManager + /// + public static bool unloadBundleByFGUI = true; + + /// + /// The event is triggered when all reference to this package item dropped. + /// + public static event Action onReleaseResource; + + /// + /// Package id. It is generated by the Editor. + /// + public string id { get; private set; } + + /// + /// Package name. + /// + public string name { get; private set; } + + /// + /// Use this callback to provide resources to the package. + /// + /// Resource name without extension. + /// Resource extension. e.g. '.png' '.wav' + /// Resource type. e.g. 'Texture' 'AudioClip' + /// How to destroy this resource. + /// + public delegate object LoadResource(string name, string extension, System.Type type, + out DestroyMethod destroyMethod); + + /// + /// A async load resource callback. After loaded, you should call item.owner.SetItemAsset. + /// + /// Resource name without extension. + /// Resource extension. e.g. '.png' '.wav' + /// Resource type. e.g. 'Texture' 'AudioClip' + /// Resource item object. + /// + public delegate void LoadResourceAsync(string name, string extension, System.Type type, PackageItem item); + + /// + /// + /// + /// + public delegate void CreateObjectCallback(GObject result); + + List _items; + Dictionary _itemsById; + Dictionary _itemsByName; + Dictionary[] _dependencies; + string _assetPath; + string[] _branches; + internal int _branchIndex; + AssetBundle _resBundle; + string _customId; + bool _fromBundle; + + LoadResource _loadFunc; + LoadResourceAsync _loadAsyncFunc; + + class AtlasSprite + { + public PackageItem atlas; + public Rect rect = new Rect(); + public Vector2 offset = new Vector2(); + public Vector2 originalSize = new Vector2(); + public bool rotated; + } + + Dictionary _sprites; + + static Dictionary _packageInstById = new Dictionary(); + static Dictionary _packageInstByName = new Dictionary(); + static List _packageList = new List(); + static string _branch; + static Dictionary _vars = new Dictionary(); + + internal static int _constructing; + + public const string URL_PREFIX = "ui://"; + +#if UNITY_EDITOR + static LoadResource _loadFromAssetsPath = + (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + return AssetDatabase.LoadAssetAtPath(name + extension, type); + }; +#endif + + static LoadResource _loadFromResourcesPath = + (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + // LoadKit.Instance.LoadAsset(); + return Resources.Load(name, type); + }; + + public UIPackage() + { + _items = new List(); + _itemsById = new Dictionary(); + _itemsByName = new Dictionary(); + _sprites = new Dictionary(); + + _branchIndex = -1; + } + + /// + /// + /// + public static string branch + { + get { return _branch; } + set + { + _branch = value; + bool empty = string.IsNullOrEmpty(_branch); + var iter = _packageInstById.GetEnumerator(); + while (iter.MoveNext()) + { + UIPackage pkg = iter.Current.Value; + if (empty) + pkg._branchIndex = -1; + else if (pkg._branches != null) + pkg._branchIndex = Array.IndexOf(pkg._branches, value); + } + + iter.Dispose(); + } + } + + /// + /// + /// + public static string GetVar(string key) + { + string value; + if (_vars.TryGetValue(key, out value)) + return value; + else + return null; + } + + /// + /// + /// + public static void SetVar(string key, string value) + { + if (value == null) + _vars.Remove(key); + else + _vars[key] = value; + } + + /// + /// Return a UIPackage with a certain id. + /// + /// ID of the package. + /// UIPackage + public static UIPackage GetById(string id) + { + UIPackage pkg; + if (_packageInstById.TryGetValue(id, out pkg)) + return pkg; + else + return null; + } + + /// + /// Return a UIPackage with a certain name. + /// + /// Name of the package. + /// UIPackage + public static UIPackage GetByName(string name) + { + UIPackage pkg; + if (_packageInstByName.TryGetValue(name, out pkg)) + return pkg; + else + return null; + } + + /// + /// Add a UI package from assetbundle. + /// + /// A assetbundle. + /// UIPackage + public static UIPackage AddPackage(AssetBundle bundle) + { + return AddPackage(bundle, bundle, null); + } + + /// + /// Add a UI package from two assetbundles. desc and res can be same. + /// + /// A assetbunble contains description file. + /// A assetbundle contains resources. + /// UIPackage + public static UIPackage AddPackage(AssetBundle desc, AssetBundle res) + { + return AddPackage(desc, res, null); + } + + /// + /// Add a UI package from two assetbundles with a optional main asset name. + /// + /// A assetbunble contains description file. + /// A assetbundle contains resources. + /// Main asset name. e.g. Basics_fui + /// UIPackage + public static UIPackage AddPackage(AssetBundle desc, AssetBundle res, string mainAssetName) + { + byte[] source = null; + if (!string.IsNullOrEmpty(mainAssetName)) + { + TextAsset ta = desc.LoadAsset(mainAssetName); + if (ta != null) + source = ta.bytes; + } + else + { + string[] names = desc.GetAllAssetNames(); + string searchPattern = "_fui"; + foreach (string n in names) + { + if (n.IndexOf(searchPattern) != -1) + { + TextAsset ta = desc.LoadAsset(n); + if (ta != null) + { + source = ta.bytes; + mainAssetName = Path.GetFileNameWithoutExtension(n); + break; + } + } + } + } + + if (source == null) + throw new Exception("FairyGUI: no package found in this bundle."); + + if (unloadBundleByFGUI && desc != res) + desc.Unload(true); + + ByteBuffer buffer = new ByteBuffer(source); + + UIPackage pkg = new UIPackage(); + pkg._resBundle = res; + pkg._fromBundle = true; + int pos = mainAssetName.IndexOf("_fui"); + if (pos != -1) + mainAssetName = mainAssetName.Substring(0, pos); + if (!pkg.LoadPackage(buffer, mainAssetName)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /*public static UIPackage AddPackage(byte[] source, string assetName, LoadResource loadFunc) + { + ByteBuffer buffer = new ByteBuffer(source); + + UIPackage pkg = new UIPackage(); + if (!pkg.LoadPackage(buffer, assetName)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + pkg._loadFunc = loadFunc; + + return pkg; + }*/ + + /// + /// Add a UI package from a path relative to Unity Resources path. + /// + /// Path relative to Unity Resources path. + /// UIPackage + public static UIPackage AddPackage(string descFilePath) + { + if (descFilePath.StartsWith("Assets/")) + { +#if UNITY_EDITOR + return AddPackage(descFilePath, _loadFromAssetsPath); +#else + Debug.LogWarning("FairyGUI: failed to load package in '" + descFilePath + "'"); + return null; +#endif + } + else + return AddPackage(descFilePath, _loadFromResourcesPath); + } + + /// + /// 使用自定义的加载方式载入一个包。 + /// + /// 包资源路径。 + /// 载入函数 + /// + public static UIPackage AddPackage(string assetPath, LoadResource loadFunc) + { + if (_packageInstById.ContainsKey(assetPath)) + return _packageInstById[assetPath]; + + DestroyMethod dm; + TextAsset asset = (TextAsset)loadFunc(assetPath + "_fui", ".bytes", typeof(TextAsset), out dm); + if (asset == null) + { + if (Application.isPlaying) + { + // throw new Exception("FairyGUI: Cannot load ui package in '" + assetPath + "'"); + } + else + Debug.LogWarning("FairyGUI: Cannot load ui package in '" + assetPath + "'"); + } + + ByteBuffer buffer = new ByteBuffer(asset.bytes); + + UIPackage pkg = new UIPackage(); + pkg._loadFunc = loadFunc; + pkg._assetPath = assetPath; + if (!pkg.LoadPackage(buffer, assetPath)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageInstById[assetPath] = pkg; + _packageList.Add(pkg); + return pkg; + } + + /// + /// Load Package by custom load method. + /// + /// Description file data + /// Prefix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. + /// Load method + /// + public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResource loadFunc) + { + ByteBuffer buffer = new ByteBuffer(descData); + + UIPackage pkg = new UIPackage(); + pkg._loadFunc = loadFunc; + if (!pkg.LoadPackage(buffer, assetNamePrefix)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /// + /// Load Package async by custom load method. + /// + /// Description file data + /// refix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. + /// Load method + /// + public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResourceAsync loadFunc) + { + ByteBuffer buffer = new ByteBuffer(descData); + + UIPackage pkg = new UIPackage(); + pkg._loadAsyncFunc = loadFunc; + if (!pkg.LoadPackage(buffer, assetNamePrefix)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /// + /// Remove a package. All resources in this package will be disposed. + /// + /// + public static void RemovePackage(string packageIdOrName) + { + UIPackage pkg = null; + if (!_packageInstById.TryGetValue(packageIdOrName, out pkg)) + { + if (!_packageInstByName.TryGetValue(packageIdOrName, out pkg)) + throw new Exception("FairyGUI: '" + packageIdOrName + "' is not a valid package id or name."); + } + + pkg.Dispose(); + _packageInstById.Remove(pkg.id); + if (pkg._customId != null) + _packageInstById.Remove(pkg._customId); + if (pkg._assetPath != null) + _packageInstById.Remove(pkg._assetPath); + _packageInstByName.Remove(pkg.name); + _packageList.Remove(pkg); + } + + /// + /// + /// + public static void RemoveAllPackages() + { + if (_packageInstById.Count > 0) + { + UIPackage[] pkgs = _packageList.ToArray(); + + foreach (UIPackage pkg in pkgs) + { + pkg.Dispose(); + } + } + + _packageList.Clear(); + _packageInstById.Clear(); + _packageInstByName.Clear(); + } + + /// + /// + /// + /// + public static List GetPackages() + { + return _packageList; + } + + /// + /// Create a UI object. + /// + /// Package name. + /// Resource name. + /// A UI object. + public static GObject CreateObject(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.CreateObject(resName); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Package name. + /// Resource name. + /// Custom implementation of this object. + /// A UI object. + public static GObject CreateObject(string pkgName, string resName, System.Type userClass) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.CreateObject(resName, userClass); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Resource url. + /// A UI object. + public static GObject CreateObjectFromURL(string url) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + return pi.owner.CreateObject(pi, null); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Resource url. + /// Custom implementation of this object. + /// A UI object. + public static GObject CreateObjectFromURL(string url, System.Type userClass) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + return pi.owner.CreateObject(pi, userClass); + else + return null; + } + + public static void CreateObjectAsync(string pkgName, string resName, CreateObjectCallback callback) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + pkg.CreateObjectAsync(resName, callback); + else + Debug.LogError("FairyGUI: package not found - " + pkgName); + } + + public static void CreateObjectFromURL(string url, CreateObjectCallback callback) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + AsyncCreationHelper.CreateObject(pi, callback); + else + Debug.LogError("FairyGUI: resource not found - " + url); + } + + /// + /// Get a asset with a certain name. + /// + /// Package name. + /// Resource name. + /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. + public static object GetItemAsset(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.GetItemAsset(resName); + else + return null; + } + + /// + /// Get a asset with a certain name. + /// + /// Resource url. + /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. + public static object GetItemAssetByURL(string url) + { + PackageItem item = GetItemByURL(url); + if (item == null) + return null; + + return item.owner.GetItemAsset(item); + } + + /// + /// Get url of an item in package. + /// + /// Package name. + /// Resource name. + /// Url. + public static string GetItemURL(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg == null) + return null; + + PackageItem pi; + if (!pkg._itemsByName.TryGetValue(resName, out pi)) + return null; + + return URL_PREFIX + pkg.id + pi.id; + } + + public static PackageItem GetItemByURL(string url) + { + if (url == null) + return null; + + int pos1 = url.IndexOf("//"); + if (pos1 == -1) + return null; + + int pos2 = url.IndexOf('/', pos1 + 2); + if (pos2 == -1) + { + if (url.Length > 13) + { + string pkgId = url.Substring(5, 8); + UIPackage pkg = GetById(pkgId); + if (pkg != null) + { + string srcId = url.Substring(13); + return pkg.GetItem(srcId); + } + } + } + else + { + string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + { + string srcName = url.Substring(pos2 + 1); + return pkg.GetItemByName(srcName); + } + } + + return null; + } + + /// + /// 将'ui://包名/组件名'转换为以内部id表达的url格式。如果传入的url本身就是内部id格式,则直接返回。 + /// 同时这个方法还带格式检测,如果传入不正确的url,会返回null。 + /// + /// + /// + public static string NormalizeURL(string url) + { + if (url == null) + return null; + + int pos1 = url.IndexOf("//"); + if (pos1 == -1) + return null; + + int pos2 = url.IndexOf('/', pos1 + 2); + if (pos2 == -1) + return url; + else + { + string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); + string srcName = url.Substring(pos2 + 1); + return GetItemURL(pkgName, srcName); + } + } + + /// + /// Set strings source. + /// + /// + public static void SetStringsSource(XML source) + { + TranslationHelper.LoadFromXML(source); + } + + /// + /// + /// + public string assetPath + { + get { return _assetPath; } + } + + /// + /// Set a custom id for package, then you can use it in GetById. + /// + public string customId + { + get { return _customId; } + set + { + if (_customId != null) + _packageInstById.Remove(_customId); + _customId = value; + if (_customId != null) + _packageInstById[_customId] = this; + } + } + + /// + /// + /// + public AssetBundle resBundle + { + get { return _resBundle; } + } + + /// + /// 获得本包依赖的包的id列表 + /// + public Dictionary[] dependencies + { + get { return _dependencies; } + } + + bool LoadPackage(ByteBuffer buffer, string assetNamePrefix) + { + if (buffer.ReadUint() != 0x46475549) + { + if (Application.isPlaying) + throw new Exception("FairyGUI: old package format found in '" + assetNamePrefix + "'"); + else + { + Debug.LogWarning("FairyGUI: old package format found in '" + assetNamePrefix + "'"); + return false; + } + } + + buffer.version = buffer.ReadInt(); + bool ver2 = buffer.version >= 2; + buffer.ReadBool(); //compressed + id = buffer.ReadString(); + name = buffer.ReadString(); + + UIPackage existingPkg; + if (_packageInstById.TryGetValue(id, out existingPkg)) + { + if (name != existingPkg.name) + Debug.LogWarning("FairyGUI: Package conflicts, '" + name + "' and '" + existingPkg.name + "'"); + +#if UNITY_EDITOR + //maybe multiple pkgs in different folder, pefer the one in resources + if (Application.isEditor) + { + if (existingPkg._loadFunc == _loadFromAssetsPath) //old one is outside resources path + existingPkg.Dispose(); //replace the existing + else if (existingPkg._loadFunc == _loadFromResourcesPath && _loadFunc == _loadFromResourcesPath + && _assetPath.Length < + existingPkg._assetPath + .Length) //both in resources path, pefer short path + existingPkg.Dispose(); //replace the existing + else //keep the existing + return false; + } +#endif + } + + buffer.Skip(20); + int indexTablePos = buffer.position; + int cnt; + + buffer.Seek(indexTablePos, 4); + + cnt = buffer.ReadInt(); + string[] stringTable = new string[cnt]; + for (int i = 0; i < cnt; i++) + stringTable[i] = buffer.ReadString(); + buffer.stringTable = stringTable; + + if (buffer.Seek(indexTablePos, 5)) + { + cnt = buffer.ReadInt(); + for (int i = 0; i < cnt; i++) + { + int index = buffer.ReadUshort(); + int len = buffer.ReadInt(); + stringTable[index] = buffer.ReadString(len); + } + } + + buffer.Seek(indexTablePos, 0); + + cnt = buffer.ReadShort(); + _dependencies = new Dictionary[cnt]; + for (int i = 0; i < cnt; i++) + { + Dictionary kv = new Dictionary(); + kv.Add("id", buffer.ReadS()); + kv.Add("name", buffer.ReadS()); + _dependencies[i] = kv; + } + + bool branchIncluded = false; + if (ver2) + { + cnt = buffer.ReadShort(); + if (cnt > 0) + { + _branches = buffer.ReadSArray(cnt); + if (!string.IsNullOrEmpty(_branch)) + _branchIndex = Array.IndexOf(_branches, _branch); + } + + branchIncluded = cnt > 0; + } + + buffer.Seek(indexTablePos, 1); + + PackageItem pi; + string assetPath; + if (assetNamePrefix.Length > 0) + { + assetPath = Path.GetDirectoryName(assetNamePrefix); + if (assetPath.Length > 0) + assetPath += "/"; + assetNamePrefix = assetNamePrefix + "_"; + } + else + assetPath = string.Empty; + + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadInt(); + nextPos += buffer.position; + + pi = new PackageItem(); + pi.owner = this; + pi.type = (PackageItemType)buffer.ReadByte(); + pi.id = buffer.ReadS(); + pi.name = buffer.ReadS(); + buffer.ReadS(); //path + pi.file = buffer.ReadS(); + pi.exported = buffer.ReadBool(); + pi.width = buffer.ReadInt(); + pi.height = buffer.ReadInt(); + + switch (pi.type) + { + case PackageItemType.Image: + { + pi.objectType = ObjectType.Image; + int scaleOption = buffer.ReadByte(); + if (scaleOption == 1) + { + Rect rect = new Rect(); + rect.x = buffer.ReadInt(); + rect.y = buffer.ReadInt(); + rect.width = buffer.ReadInt(); + rect.height = buffer.ReadInt(); + pi.scale9Grid = rect; + + pi.tileGridIndice = buffer.ReadInt(); + } + else if (scaleOption == 2) + pi.scaleByTile = true; + + buffer.ReadBool(); //smoothing + break; + } + + case PackageItemType.MovieClip: + { + buffer.ReadBool(); //smoothing + pi.objectType = ObjectType.MovieClip; + pi.rawData = buffer.ReadBuffer(); + break; + } + + case PackageItemType.Font: + { + pi.rawData = buffer.ReadBuffer(); + break; + } + + case PackageItemType.Component: + { + int extension = buffer.ReadByte(); + if (extension > 0) + pi.objectType = (ObjectType)extension; + else + pi.objectType = ObjectType.Component; + pi.rawData = buffer.ReadBuffer(); + + UIObjectFactory.ResolvePackageItemExtension(pi); + break; + } + + case PackageItemType.Atlas: + case PackageItemType.Sound: + case PackageItemType.Misc: + { + pi.file = assetNamePrefix + pi.file; + break; + } + + case PackageItemType.Spine: + case PackageItemType.DragoneBones: + { + pi.file = assetPath + pi.file; + pi.skeletonAnchor.x = buffer.ReadFloat(); + pi.skeletonAnchor.y = buffer.ReadFloat(); + break; + } + } + + if (ver2) + { + string str = buffer.ReadS(); //branch + if (str != null) + pi.name = str + "/" + pi.name; + + int branchCnt = buffer.ReadByte(); + if (branchCnt > 0) + { + if (branchIncluded) + pi.branches = buffer.ReadSArray(branchCnt); + else + _itemsById[buffer.ReadS()] = pi; + } + + int highResCnt = buffer.ReadByte(); + if (highResCnt > 0) + pi.highResolution = buffer.ReadSArray(highResCnt); + } + + _items.Add(pi); + _itemsById[pi.id] = pi; + if (pi.name != null) + _itemsByName[pi.name] = pi; + + buffer.position = nextPos; + } + + buffer.Seek(indexTablePos, 2); + + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + string itemId = buffer.ReadS(); + pi = _itemsById[buffer.ReadS()]; + + AtlasSprite sprite = new AtlasSprite(); + sprite.atlas = pi; + sprite.rect.x = buffer.ReadInt(); + sprite.rect.y = buffer.ReadInt(); + sprite.rect.width = buffer.ReadInt(); + sprite.rect.height = buffer.ReadInt(); + sprite.rotated = buffer.ReadBool(); + if (ver2 && buffer.ReadBool()) + { + sprite.offset.x = buffer.ReadInt(); + sprite.offset.y = buffer.ReadInt(); + sprite.originalSize.x = buffer.ReadInt(); + sprite.originalSize.y = buffer.ReadInt(); + } + else if (sprite.rotated) + { + sprite.originalSize.x = sprite.rect.height; + sprite.originalSize.y = sprite.rect.width; + } + else + { + sprite.originalSize.x = sprite.rect.width; + sprite.originalSize.y = sprite.rect.height; + } + + _sprites[itemId] = sprite; + + buffer.position = nextPos; + } + + if (buffer.Seek(indexTablePos, 3)) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadInt(); + nextPos += buffer.position; + + if (_itemsById.TryGetValue(buffer.ReadS(), out pi)) + { + if (pi.type == PackageItemType.Image) + { + pi.pixelHitTestData = new PixelHitTestData(); + pi.pixelHitTestData.Load(buffer); + } + } + + buffer.position = nextPos; + } + } + + if (!Application.isPlaying) + _items.Sort(ComparePackageItem); + + return true; + } + + static int ComparePackageItem(PackageItem p1, PackageItem p2) + { + if (p1.name != null && p2.name != null) + return p1.name.CompareTo(p2.name); + else + return 0; + } + + /// + /// + /// + public void LoadAllAssets() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + GetItemAsset(_items[i]); + } + + /// + /// + /// + public void UnloadAssets() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null) + pi.texture.Unload(); + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null) + pi.audioClip.Unload(); + } + } + + if (unloadBundleByFGUI && + _resBundle != null) + { + _resBundle.Unload(true); + _resBundle = null; + } + } + + /// + /// + /// + public void ReloadAssets() + { + if (_fromBundle) + throw new Exception("FairyGUI: new bundle must be passed to this function"); + + ReloadAssets(null); + } + + /// + /// + /// + public void ReloadAssets(AssetBundle resBundle) + { + _resBundle = resBundle; + _fromBundle = _resBundle != null; + + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null && pi.texture.nativeTexture == null) + LoadAtlas(pi); + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null && pi.audioClip.nativeClip == null) + LoadSound(pi); + } + } + } + + void Dispose() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null) + { + pi.texture.Dispose(); + pi.texture = null; + } + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null) + { + pi.audioClip.Unload(); + pi.audioClip = null; + } + } + } + + _items.Clear(); + + if (unloadBundleByFGUI && + _resBundle != null) + { + _resBundle.Unload(true); + _resBundle = null; + } + } + + /// + /// + /// + /// + /// + public GObject CreateObject(string resName) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return null; + } + + return CreateObject(pi, null); + } + + /// + /// + /// + /// + /// + /// + public GObject CreateObject(string resName, System.Type userClass) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return null; + } + + return CreateObject(pi, userClass); + } + + public void CreateObjectAsync(string resName, CreateObjectCallback callback) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return; + } + + AsyncCreationHelper.CreateObject(pi, callback); + } + + GObject CreateObject(PackageItem item, System.Type userClass) + { + Stats.LatestObjectCreation = 0; + Stats.LatestGraphicsCreation = 0; + + GetItemAsset(item); + + GObject g = UIObjectFactory.NewObject(item, userClass); + if (g == null) + return null; + + _constructing++; + g.ConstructFromResource(); + _constructing--; + + return g; + } + + + /// + /// + /// + /// + /// + public object GetItemAsset(string resName) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: Resource not found - " + resName + " in " + this.name); + return null; + } + + return GetItemAsset(pi); + } + + public List GetItems() + { + return _items; + } + + public PackageItem GetItem(string itemId) + { + PackageItem pi; + if (_itemsById.TryGetValue(itemId, out pi)) + return pi; + else + return null; + } + + public PackageItem GetItemByName(string itemName) + { + PackageItem pi; + if (_itemsByName.TryGetValue(itemName, out pi)) + return pi; + else + return null; + } + + public object GetItemAsset(PackageItem item) + { + switch (item.type) + { + case PackageItemType.Image: + if (item.texture == null) + LoadImage(item); + return item.texture; + + case PackageItemType.Atlas: + if (item.texture == null) + LoadAtlas(item); + return item.texture; + + case PackageItemType.Sound: + if (item.audioClip == null) + LoadSound(item); + return item.audioClip; + + case PackageItemType.Font: + if (item.bitmapFont == null) + LoadFont(item); + + return item.bitmapFont; + + case PackageItemType.MovieClip: + if (item.frames == null) + LoadMovieClip(item); + + return item.frames; + + case PackageItemType.Component: + return item.rawData; + + case PackageItemType.Misc: + return LoadBinary(item); + + case PackageItemType.Spine: + if (item.skeletonAsset == null) + LoadSpine(item); + return item.skeletonAsset; + + case PackageItemType.DragoneBones: + if (item.skeletonAsset == null) + LoadDragonBones(item); + return item.skeletonAsset; + + default: + return null; + } + } + + /// + /// + /// + /// + /// + /// + public void SetItemAsset(PackageItem item, object asset, DestroyMethod destroyMethod) + { + switch (item.type) + { + case PackageItemType.Atlas: + if (item.texture == null) + item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); + item.texture.Reload((Texture)asset, null); + item.texture.destroyMethod = destroyMethod; + break; + + case PackageItemType.Sound: + if (item.audioClip == null) + item.audioClip = new NAudioClip(null); + item.audioClip.Reload((AudioClip)asset); + item.audioClip.destroyMethod = destroyMethod; + break; + + case PackageItemType.Spine: +#if FAIRYGUI_SPINE + item.skeletonAsset = (Spine.Unity.SkeletonDataAsset)asset; +#endif + break; + + case PackageItemType.DragoneBones: +#if FAIRYGUI_DRAGONBONES + item.skeletonAsset = (DragonBones.UnityDragonBonesData)asset; +#endif + break; + } + } + + void LoadAtlas(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + if (_loadAsyncFunc != null) + { + _loadAsyncFunc(fileName, ext, typeof(Texture), item); + if (item.texture == null) + item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); + item.texture.destroyMethod = DestroyMethod.None; + } + else + { + Texture tex = null; + Texture alphaTex = null; + DestroyMethod dm; + + if (_fromBundle) + { + if (_resBundle != null) + tex = _resBundle.LoadAsset(fileName); + else + Debug.LogWarning("FairyGUI: bundle already unloaded."); + + dm = DestroyMethod.None; + } + else + { + tex = (Texture)_loadFunc(fileName, ext, typeof(Texture), out dm); + } + + if (tex == null) + Debug.LogWarning("FairyGUI: texture '" + item.file + "' not found in " + this.name); + + else if (!(tex is Texture2D)) + { + Debug.LogWarning("FairyGUI: settings for '" + item.file + + "' is wrong! Correct values are: (Texture Type=Default, Texture Shape=2D)"); + tex = null; + } + else + { + if (((Texture2D)tex).mipmapCount > 1) + Debug.LogWarning("FairyGUI: settings for '" + item.file + + "' is wrong! Correct values are: (Generate Mip Maps=unchecked)"); + } + + if (tex != null) + { + alphaTex = AssetDataBaseKit.GetAssetstatic("", fileName); + } + + // if (tex != null) + // { + // fileName = fileName + "!a"; + // if (_fromBundle) + // { + // if (_resBundle != null) + // alphaTex = _resBundle.LoadAsset(fileName); + // } + // else + // alphaTex = (Texture2D)_loadFunc(fileName, ext, typeof(Texture2D), out dm); + // } + + if (tex == null) + { + tex = NTexture.CreateEmptyTexture(); + dm = DestroyMethod.Destroy; + } + + if (item.texture == null) + { + item.texture = new NTexture(tex, alphaTex, (float)tex.width / item.width, + (float)tex.height / item.height); + item.texture.onRelease += (NTexture t) => + { + if (onReleaseResource != null) + onReleaseResource(item); + }; + } + else + item.texture.Reload(tex, alphaTex); + + item.texture.destroyMethod = dm; + } + } + + void LoadImage(PackageItem item) + { + AtlasSprite sprite; + if (_sprites.TryGetValue(item.id, out sprite)) + { + NTexture atlas = (NTexture)GetItemAsset(sprite.atlas); + if (atlas.width == sprite.rect.width && atlas.height == sprite.rect.height) + item.texture = atlas; + else + item.texture = new NTexture(atlas, sprite.rect, sprite.rotated, sprite.originalSize, sprite.offset); + } + else + item.texture = NTexture.Empty; + } + + void LoadSound(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + if (_loadAsyncFunc != null) + { + _loadAsyncFunc(fileName, ext, typeof(AudioClip), item); + if (item.audioClip == null) + item.audioClip = new NAudioClip(null); + item.audioClip.destroyMethod = DestroyMethod.None; + } + else + { + AudioClip audioClip = null; + DestroyMethod dm; + + if (_fromBundle) + { + if (_resBundle != null) + audioClip = _resBundle.LoadAsset(fileName); + dm = DestroyMethod.None; + } + else + { + audioClip = (AudioClip)_loadFunc(fileName, ext, typeof(AudioClip), out dm); + } + + if (item.audioClip == null) + item.audioClip = new NAudioClip(audioClip); + else + item.audioClip.Reload(audioClip); + item.audioClip.destroyMethod = dm; + } + } + + byte[] LoadBinary(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + TextAsset ta; + if (_resBundle != null) + { + ta = _resBundle.LoadAsset(fileName); + if (ta != null) + return ta.bytes; + else + return null; + } + else + { + DestroyMethod dm; + object ret = _loadFunc(fileName, ext, typeof(TextAsset), out dm); + if (ret == null) + return null; + if (ret is byte[]) + return (byte[])ret; + else + return ((TextAsset)ret).bytes; + } + } + + void LoadMovieClip(PackageItem item) + { + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 0); + + item.interval = buffer.ReadInt() / 1000f; + item.swing = buffer.ReadBool(); + item.repeatDelay = buffer.ReadInt() / 1000f; + + buffer.Seek(0, 1); + + int frameCount = buffer.ReadShort(); + item.frames = new MovieClip.Frame[frameCount]; + + string spriteId; + MovieClip.Frame frame; + AtlasSprite sprite; + Rect frameRect = new Rect(); + + for (int i = 0; i < frameCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + frame = new MovieClip.Frame(); + frameRect.x = buffer.ReadInt(); + frameRect.y = buffer.ReadInt(); + frameRect.width = buffer.ReadInt(); + frameRect.height = buffer.ReadInt(); + frame.addDelay = buffer.ReadInt() / 1000f; + spriteId = buffer.ReadS(); + + if (spriteId != null && _sprites.TryGetValue(spriteId, out sprite)) + { + frame.texture = new NTexture((NTexture)GetItemAsset(sprite.atlas), sprite.rect, sprite.rotated, + new Vector2(item.width, item.height), frameRect.position); + } + + item.frames[i] = frame; + + buffer.position = nextPos; + } + } + + void LoadFont(PackageItem item) + { + BitmapFont font = new BitmapFont(); + font.name = URL_PREFIX + this.id + item.id; + item.bitmapFont = font; + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 0); + + bool ttf = buffer.ReadBool(); + font.canTint = buffer.ReadBool(); + font.resizable = buffer.ReadBool(); + font.hasChannel = buffer.ReadBool(); + int fontSize = buffer.ReadInt(); + int xadvance = buffer.ReadInt(); + int lineHeight = buffer.ReadInt(); + + float texScaleX = 1; + float texScaleY = 1; + int bgX; + int bgY; + int bgWidth; + int bgHeight; + + NTexture mainTexture = null; + AtlasSprite mainSprite = null; + if (ttf && _sprites.TryGetValue(item.id, out mainSprite)) + { + mainTexture = (NTexture)GetItemAsset(mainSprite.atlas); + texScaleX = mainTexture.root.uvRect.width / mainTexture.width; + texScaleY = mainTexture.root.uvRect.height / mainTexture.height; + } + + buffer.Seek(0, 1); + + BitmapFont.BMGlyph bg; + int cnt = buffer.ReadInt(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + bg = new BitmapFont.BMGlyph(); + char ch = buffer.ReadChar(); + font.AddChar(ch, bg); + + string img = buffer.ReadS(); + int bx = buffer.ReadInt(); + int by = buffer.ReadInt(); + bgX = buffer.ReadInt(); + bgY = buffer.ReadInt(); + bgWidth = buffer.ReadInt(); + bgHeight = buffer.ReadInt(); + bg.advance = buffer.ReadInt(); + bg.channel = buffer.ReadByte(); + //The texture channel where the character image is found (1 = blue, 2 = green, 4 = red, 8 = alpha, 15-all). + if (bg.channel == 1) + bg.channel = 2; + else if (bg.channel == 2) + bg.channel = 1; + else if (bg.channel == 4) + bg.channel = 0; + else if (bg.channel == 8) + bg.channel = 3; + + if (ttf) + { + if (mainSprite.rotated) + { + bg.uv[0] = new Vector2((float)(by + bgHeight + mainSprite.rect.x) * texScaleX, + 1 - (float)(mainSprite.rect.yMax - bx) * texScaleY); + bg.uv[1] = new Vector2(bg.uv[0].x - (float)bgHeight * texScaleX, bg.uv[0].y); + bg.uv[2] = new Vector2(bg.uv[1].x, bg.uv[0].y + (float)bgWidth * texScaleY); + bg.uv[3] = new Vector2(bg.uv[0].x, bg.uv[2].y); + } + else + { + bg.uv[0] = new Vector2((float)(bx + mainSprite.rect.x) * texScaleX, + 1 - (float)(by + bgHeight + mainSprite.rect.y) * texScaleY); + bg.uv[1] = new Vector2(bg.uv[0].x, bg.uv[0].y + (float)bgHeight * texScaleY); + bg.uv[2] = new Vector2(bg.uv[0].x + (float)bgWidth * texScaleX, bg.uv[1].y); + bg.uv[3] = new Vector2(bg.uv[2].x, bg.uv[0].y); + } + + bg.lineHeight = lineHeight; + bg.x = bgX; + bg.y = bgY; + bg.width = bgWidth; + bg.height = bgHeight; + } + else + { + PackageItem charImg; + if (_itemsById.TryGetValue(img, out charImg)) + { + charImg = charImg.getBranch(); + bgWidth = charImg.width; + bgHeight = charImg.height; + charImg = charImg.getHighResolution(); + GetItemAsset(charImg); + charImg.texture.GetUV(bg.uv); + + texScaleX = (float)bgWidth / charImg.width; + texScaleY = (float)bgHeight / charImg.height; + + bg.x = bgX + charImg.texture.offset.x * texScaleX; + bg.y = bgY + charImg.texture.offset.y * texScaleY; + bg.width = charImg.texture.width * texScaleX; + bg.height = charImg.texture.height * texScaleY; + + if (mainTexture == null) + mainTexture = charImg.texture.root; + } + + if (fontSize == 0) + fontSize = bgHeight; + + if (bg.advance == 0) + { + if (xadvance == 0) + bg.advance = bgX + bgWidth; + else + bg.advance = xadvance; + } + + bg.lineHeight = bgY < 0 ? bgHeight : (bgY + bgHeight); + if (bg.lineHeight < fontSize) + bg.lineHeight = fontSize; + } + + buffer.position = nextPos; + } + + font.size = fontSize; + font.mainTexture = mainTexture; + if (!font.hasChannel) + font.shader = ShaderConfig.imageShader; + } + + void LoadSpine(PackageItem item) + { +#if FAIRYGUI_SPINE + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + int index = fileName.LastIndexOf(".skel"); + if (index > 0) + fileName = fileName.Substring(0, index); + + Spine.Unity.SkeletonDataAsset asset; + if (_resBundle != null) + asset = _resBundle.LoadAsset(fileName + "_SkeletonData"); + else + { + DestroyMethod dm; + asset = + (Spine.Unity.SkeletonDataAsset)_loadFunc(fileName + "_SkeletonData", ".asset", typeof(Spine.Unity.SkeletonDataAsset), out dm); + } + if (asset == null) + Debug.LogWarning("FairyGUI: Failed to load " + fileName); + item.skeletonAsset = asset; +#else + Debug.LogWarning("To enable Spine support, add script define symbol: FAIRYGUI_SPINE"); +#endif + } + + void LoadDragonBones(PackageItem item) + { +#if FAIRYGUI_DRAGONBONES + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + int index = fileName.LastIndexOf("_ske"); + if (index > 0) + fileName = fileName.Substring(0, index); + index = fileName.LastIndexOf(".dbbin"); + if (index > 0) + fileName = fileName.Substring(0, index); + + DragonBones.UnityDragonBonesData asset; + if (_resBundle != null) + asset = _resBundle.LoadAsset(fileName + "_Data"); + else + { + DestroyMethod dm; + asset = + (DragonBones.UnityDragonBonesData)_loadFunc(fileName + "_Data", ".asset", typeof(DragonBones.UnityDragonBonesData), out dm); + } + if (asset != null) + { + foreach (var atlas in asset.textureAtlas) + { + if (atlas.material == null) + { + atlas.material = new Material(ShaderConfig.GetShader(ShaderConfig.imageShader)); + atlas.material.mainTexture = atlas.texture; + } + } + item.skeletonAsset = DragonBones.UnityFactory.factory.LoadData(asset); + } + else + Debug.LogWarning("FairyGUI: Failed to load " + fileName); +#else + Debug.LogWarning("To enable DragonBones support, add script define symbol: FAIRYGUI_DRAGONBONES"); +#endif + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs.meta new file mode 100644 index 0000000..27da046 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPackage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7177aa7a57b8cc0439fde7785099f11c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs new file mode 100644 index 0000000..9c57b53 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs @@ -0,0 +1,335 @@ +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Painter")] + [RequireComponent(typeof(MeshCollider), typeof(MeshRenderer))] + public class UIPainter : MonoBehaviour, EMRenderTarget + { + /// + /// + /// + public Container container { get; private set; } + + /// + /// + /// + public string packageName; + + /// + /// + /// + public string componentName; + + /// + /// + /// + public int sortingOrder; + + [SerializeField] + string packagePath; + [SerializeField] + Camera renderCamera = null; + [SerializeField] + bool fairyBatching = false; + [SerializeField] + bool touchDisabled = false; + + GComponent _ui; + [NonSerialized] + bool _created; + [NonSerialized] + bool _captured; + [NonSerialized] + Renderer _renderer; + + [NonSerialized] + RenderTexture _texture; + + Action _captureDelegate; + + void OnEnable() + { + if (Application.isPlaying) + { + if (this.container == null) + { + CreateContainer(); + + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + } + } + else + { + EMRenderSupport.Add(this); + } + } + + void OnDisable() + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + } + + void OnGUI() + { + if (!Application.isPlaying) + EM_BeforeUpdate(); + } + + void Start() + { + useGUILayout = false; + + if (!_created && Application.isPlaying) + CreateUI(); + } + + void OnDestroy() + { + if (Application.isPlaying) + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + container.Dispose(); + container = null; + } + else + { + EMRenderSupport.Remove(this); + } + + DestroyTexture(); + } + + void CreateContainer() + { + this.container = new Container("UIPainter"); + this.container.renderMode = RenderMode.WorldSpace; + this.container.renderCamera = renderCamera; + this.container.touchable = !touchDisabled; + this.container.fairyBatching = fairyBatching; + this.container._panelOrder = sortingOrder; + this.container.hitArea = new MeshColliderHitTest(this.gameObject.GetComponent()); + SetSortingOrder(this.sortingOrder, true); + this.container.layer = CaptureCamera.hiddenLayer; + } + + /// + /// Change the sorting order of the panel in runtime. + /// + /// sorting order value + /// false if you dont want the default sorting behavior. + public void SetSortingOrder(int value, bool apply) + { + this.sortingOrder = value; + container._panelOrder = value; + + if (apply) + Stage.inst.ApplyPanelOrder(container); + } + + /// + /// + /// + public GComponent ui + { + get + { + if (!_created && Application.isPlaying) + CreateUI(); + + return _ui; + } + } + + /// + /// + /// + public void CreateUI() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + DestroyTexture(); + } + + _created = true; + + if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) + return; + + _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); + if (_ui != null) + { + this.container.AddChild(_ui.displayObject); + this.container.size = _ui.size; + _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(_ui.width), Mathf.RoundToInt(_ui.height), UIConfig.depthSupportForPaintingMode); + _renderer = this.GetComponent(); + if (_renderer != null) + { + _renderer.sharedMaterial.mainTexture = _texture; + _captureDelegate = Capture; + if (_renderer.sharedMaterial.renderQueue == 3000) //Set in transpare queue only + { + this.container.onUpdate += () => + { + UpdateContext.OnEnd += _captureDelegate; + }; + } + } + } + else + Debug.LogError("Create " + componentName + "@" + packageName + " failed!"); + } + + void Capture() + { + CaptureCamera.Capture(this.container, _texture, this.container.size.y, Vector2.zero); + if (_renderer != null) + _renderer.sortingOrder = container.renderingOrder; + } + + void DestroyTexture() + { + if (_texture != null) + { + if (Application.isPlaying) + RenderTexture.Destroy(_texture); + else + RenderTexture.DestroyImmediate(_texture); + _texture = null; + + if (_renderer != null) + _renderer.sharedMaterial.mainTexture = null; + } + } + + #region edit mode functions + + void CaptureInEditMode() + { + if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) + return; + + _captured = true; + + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + GComponent view = (GComponent)UIPackage.CreateObject(packageName, componentName); + + if (view != null) + { + DestroyTexture(); + + _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(view.width), Mathf.RoundToInt(view.height), false); + + Container root = (Container)view.displayObject; + root.layer = CaptureCamera.layer; + root.gameObject.hideFlags = HideFlags.None; + root.gameObject.SetActive(true); + + GameObject cameraObject = new GameObject("Temp Capture Camera"); + Camera camera = cameraObject.AddComponent(); + camera.depth = 0; + camera.cullingMask = 1 << CaptureCamera.layer; + camera.clearFlags = CameraClearFlags.Depth; + camera.orthographic = true; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + camera.enabled = false; + camera.targetTexture = _texture; + + float halfHeight = (float)_texture.height / 2; + camera.orthographicSize = halfHeight; + cameraObject.transform.localPosition = root.cachedTransform.TransformPoint(halfHeight * camera.aspect, -halfHeight, 0); + + UpdateContext context = new UpdateContext(); + //run two times + context.Begin(); + view.displayObject.Update(context); + context.End(); + + context.Begin(); + view.displayObject.Update(context); + context.End(); + + RenderTexture old = RenderTexture.active; + RenderTexture.active = _texture; + GL.Clear(true, true, Color.clear); + camera.Render(); + RenderTexture.active = old; + + camera.targetTexture = null; + view.Dispose(); + GameObject.DestroyImmediate(cameraObject); + + if (_renderer != null) + _renderer.sharedMaterial.mainTexture = _texture; + } + } + + public void ApplyModifiedProperties(bool sortingOrderChanged) + { + if (sortingOrderChanged) + { + if (Application.isPlaying) + SetSortingOrder(sortingOrder, true); + else + EMRenderSupport.orderChanged = true; + } + } + + public void OnUpdateSource(object[] data) + { + if (Application.isPlaying) + return; + + this.packageName = (string)data[0]; + this.packagePath = (string)data[1]; + this.componentName = (string)data[2]; + + if ((bool)data[3]) + _captured = false; + } + + public int EM_sortingOrder + { + get { return sortingOrder; } + } + + public void EM_BeforeUpdate() + { + if (_renderer == null) + _renderer = this.GetComponent(); + if (_renderer != null && _renderer.sharedMaterial.mainTexture != _texture) + _renderer.sharedMaterial.mainTexture = _texture; + + if (packageName != null && componentName != null && !_captured) + CaptureInEditMode(); + } + + public void EM_Update(UpdateContext context) + { + if (_renderer != null) + _renderer.sortingOrder = context.renderingOrder++; + } + + public void EM_Reload() + { + _captured = false; + } + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs.meta new file mode 100644 index 0000000..135c716 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPainter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ca66c39de4dce2499306801170a139f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs new file mode 100644 index 0000000..62c4b70 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs @@ -0,0 +1,622 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public enum FitScreen + { + None, + FitSize, + FitWidthAndSetMiddle, + FitHeightAndSetCenter + } + + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Panel")] + public class UIPanel : MonoBehaviour, EMRenderTarget + { + /// + /// + /// + public Container container { get; private set; } + + /// + /// + /// + public string packageName; + + /// + /// + /// + public string componentName; + + /// + /// + /// + public FitScreen fitScreen; + + /// + /// + /// + public int sortingOrder; + + [SerializeField] + string packagePath; + [SerializeField] + RenderMode renderMode = RenderMode.ScreenSpaceOverlay; + [SerializeField] + Camera renderCamera = null; + [SerializeField] + Vector3 position; + [SerializeField] + Vector3 scale = new Vector3(1, 1, 1); + [SerializeField] + Vector3 rotation = new Vector3(0, 0, 0); + [SerializeField] + bool fairyBatching = false; + [SerializeField] + bool touchDisabled = false; + [SerializeField] + Vector2 cachedUISize; + [SerializeField] + HitTestMode hitTestMode = HitTestMode.Default; + [SerializeField] + bool setNativeChildrenOrder = false; + + [System.NonSerialized] + int screenSizeVer; + [System.NonSerialized] + Rect uiBounds; //Track bounds even when UI is not created, edit mode + + GComponent _ui; + [NonSerialized] + bool _created; + + List _renders; + + void OnEnable() + { + if (Application.isPlaying) + { + if (this.container == null) + { + CreateContainer(); + + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + } + } + else + { + //不在播放状态时我们不在OnEnable创建,因为Prefab也会调用OnEnable,延迟到Update里创建(Prefab不调用Update) + //每次播放前都会disable/enable一次。。。 + if (container != null)//如果不为null,可能是因为Prefab revert, 而不是因为Assembly reload, + OnDestroy(); + + EMRenderSupport.Add(this); + screenSizeVer = 0; + uiBounds.position = position; + uiBounds.size = cachedUISize; + if (uiBounds.size == Vector2.zero) + uiBounds.size = new Vector2(30, 30); + } + } + + void OnDisable() + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + } + + void Start() + { + if (!_created && Application.isPlaying) + CreateUI_PlayMode(); + } + + void Update() + { + if (screenSizeVer != StageCamera.screenSizeVer) + HandleScreenSizeChanged(); + } + + void OnDestroy() + { + if (container != null) + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + container.Dispose(); + container = null; + } + + _renders = null; + } + + void CreateContainer() + { + if (!Application.isPlaying) + { + Transform t = this.transform; + int cnt = t.childCount; + while (cnt > 0) + { + GameObject go = t.GetChild(cnt - 1).gameObject; + if (go.name == "UI(AutoGenerated)") + { +#if (UNITY_2018_3_OR_NEWER && UNITY_EDITOR) + if (PrefabUtility.IsPartOfPrefabInstance(go)) + PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject), PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); +#endif + UnityEngine.Object.DestroyImmediate(go); + } + cnt--; + } + } + + this.container = new Container(this.gameObject); + this.container.renderMode = renderMode; + this.container.renderCamera = renderCamera; + this.container.touchable = !touchDisabled; + this.container._panelOrder = sortingOrder; + this.container.fairyBatching = fairyBatching; + if (Application.isPlaying) + { + SetSortingOrder(this.sortingOrder, true); + if (this.hitTestMode == HitTestMode.Raycast) + { + ColliderHitTest hitArea = new ColliderHitTest(); + hitArea.collider = this.gameObject.AddComponent(); + this.container.hitArea = hitArea; + } + + if (setNativeChildrenOrder) + { + CacheNativeChildrenRenderers(); + + this.container.onUpdate += () => + { + int cnt = _renders.Count; + int sv = UpdateContext.current.renderingOrder++; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if (r != null) + _renders[i].sortingOrder = sv; + } + }; + } + } + } + + /// + /// + /// + public GComponent ui + { + get + { + if (!_created && Application.isPlaying) + { + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + + CreateUI_PlayMode(); + } + + return _ui; + } + } + + /// + /// + /// + public void CreateUI() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + CreateUI_PlayMode(); + } + + /// + /// Change the sorting order of the panel in runtime. + /// + /// sorting order value + /// false if you dont want the default sorting behavior. e.g. call Stage.SortWorldSpacePanelsByZOrder later. + public void SetSortingOrder(int value, bool apply) + { + this.sortingOrder = value; + container._panelOrder = value; + + if (apply) + Stage.inst.ApplyPanelOrder(container); + } + + /// + /// + /// + /// + public void SetHitTestMode(HitTestMode value) + { + if (this.hitTestMode != value) + { + this.hitTestMode = value; + BoxCollider collider = this.gameObject.GetComponent(); + if (this.hitTestMode == HitTestMode.Raycast) + { + if (collider == null) + collider = this.gameObject.AddComponent(); + ColliderHitTest hitArea = new ColliderHitTest(); + hitArea.collider = collider; + this.container.hitArea = hitArea; + if (_ui != null) + UpdateHitArea(); + } + else + { + this.container.hitArea = null; + if (collider != null) + Component.Destroy(collider); + } + } + } + + /// + /// + /// + public void CacheNativeChildrenRenderers() + { + if (_renders == null) + _renders = new List(); + else + _renders.Clear(); + + Transform t = this.container.cachedTransform; + int cnt = t.childCount; + for (int i = 0; i < cnt; i++) + { + GameObject go = t.GetChild(i).gameObject; + if (go.name != "GComponent") + _renders.AddRange(go.GetComponentsInChildren(true)); + } + + cnt = _renders.Count; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if ((r is SkinnedMeshRenderer) || (r is MeshRenderer)) + { + //Set the object rendering in Transparent Queue as UI objects + if (r.sharedMaterial != null) + r.sharedMaterial.renderQueue = 3000; + } + } + } + + void CreateUI_PlayMode() + { + _created = true; + + if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) + return; + + _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); + if (_ui != null) + { + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + if (this.container.hitArea != null) + { + UpdateHitArea(); + _ui.onSizeChanged.Add(UpdateHitArea); + _ui.onPositionChanged.Add(UpdateHitArea); + } + this.container.AddChildAt(_ui.displayObject, 0); + + HandleScreenSizeChanged(); + } + else + Debug.LogError("Create " + packageName + "/" + componentName + " failed!"); + } + + void UpdateHitArea() + { + ColliderHitTest hitArea = this.container.hitArea as ColliderHitTest; + if (hitArea != null) + { + ((BoxCollider)hitArea.collider).center = new Vector3(_ui.xMin + _ui.width / 2, -_ui.yMin - _ui.height / 2); + ((BoxCollider)hitArea.collider).size = _ui.size; + } + } + + void CreateUI_EditMode() + { + if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) + return; + + + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + GObject obj = UIPackage.CreateObject(packageName, componentName); + if (obj != null && !(obj is GComponent)) + { + obj.Dispose(); + Debug.LogWarning("Not a GComponnet: " + packageName + "/" + componentName); + return; + } + _ui = (GComponent)obj; + + if (_ui != null) + { + _ui.displayObject.gameObject.hideFlags |= HideFlags.HideInHierarchy; + _ui.gameObjectName = "UI(AutoGenerated)"; + + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + this.container.AddChildAt(_ui.displayObject, 0); + + cachedUISize = _ui.size; + uiBounds.size = cachedUISize; + HandleScreenSizeChanged(); + } + } + + void HandleScreenSizeChanged() + { + if (!Application.isPlaying) + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + + screenSizeVer = StageCamera.screenSizeVer; + + int width = Screen.width; + int height = Screen.height; + if (this.container != null) + { + Camera cam = container.GetRenderCamera(); + if (cam.targetDisplay != 0 && cam.targetDisplay < Display.displays.Length) + { + width = Display.displays[cam.targetDisplay].renderingWidth; + height = Display.displays[cam.targetDisplay].renderingHeight; + } + + if (this.container.renderMode != RenderMode.WorldSpace) + { + StageCamera sc = cam.GetComponent(); + if (sc == null) + sc = StageCamera.main.GetComponent(); + this.container.scale = new Vector2(sc.unitsPerPixel * UIContentScaler.scaleFactor, sc.unitsPerPixel * UIContentScaler.scaleFactor); + } + } + + width = Mathf.CeilToInt(width / UIContentScaler.scaleFactor); + height = Mathf.CeilToInt(height / UIContentScaler.scaleFactor); + if (_ui != null) + { + switch (fitScreen) + { + case FitScreen.FitSize: + _ui.SetSize(width, height); + _ui.SetXY(0, 0, true); + break; + + case FitScreen.FitWidthAndSetMiddle: + _ui.SetSize(width, _ui.sourceHeight); + _ui.SetXY(0, (int)((height - _ui.sourceHeight) / 2), true); + break; + + case FitScreen.FitHeightAndSetCenter: + _ui.SetSize(_ui.sourceWidth, height); + _ui.SetXY((int)((width - _ui.sourceWidth) / 2), 0, true); + break; + } + + UpdateHitArea(); + } + else + { + switch (fitScreen) + { + case FitScreen.FitSize: + uiBounds.position = new Vector2(0, 0); + uiBounds.size = new Vector2(width, height); + break; + + case FitScreen.FitWidthAndSetMiddle: + uiBounds.position = new Vector2(0, (int)((height - cachedUISize.y) / 2)); + uiBounds.size = new Vector2(width, cachedUISize.y); + break; + + case FitScreen.FitHeightAndSetCenter: + uiBounds.position = new Vector2((int)((width - cachedUISize.x) / 2), 0); + uiBounds.size = new Vector2(cachedUISize.x, height); + break; + } + } + } + + #region edit mode functions + + void OnUpdateSource(object[] data) + { + if (Application.isPlaying) + return; + + this.packageName = (string)data[0]; + this.packagePath = (string)data[1]; + this.componentName = (string)data[2]; + + if ((bool)data[3]) + { + if (container == null) + return; + + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + } + } + + public void ApplyModifiedProperties(bool sortingOrderChanged, bool fitScreenChanged) + { + if (container != null) + { + container.renderMode = renderMode; + container.renderCamera = renderCamera; + if (sortingOrderChanged) + { + container._panelOrder = sortingOrder; + if (Application.isPlaying) + SetSortingOrder(sortingOrder, true); + else + EMRenderSupport.orderChanged = true; + } + container.fairyBatching = fairyBatching; + } + + if (_ui != null) + { + if (fitScreen == FitScreen.None) + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + } + if (fitScreen == FitScreen.None) + uiBounds.position = position; + screenSizeVer = 0;//force HandleScreenSizeChanged be called + + if (fitScreenChanged && this.fitScreen == FitScreen.None) + { + if (_ui != null) + _ui.SetSize(_ui.sourceWidth, _ui.sourceHeight); + uiBounds.size = cachedUISize; + } + } + + public void MoveUI(Vector3 delta) + { + if (fitScreen != FitScreen.None) + return; + + this.position += delta; + if (_ui != null) + _ui.position = position; + uiBounds.position = position; + } + + public Vector3 GetUIWorldPosition() + { + if (_ui != null) + return _ui.displayObject.cachedTransform.position; + else + return this.container.cachedTransform.TransformPoint(uiBounds.position); + } + + void OnDrawGizmos() + { + if (Application.isPlaying || this.container == null) + return; + + Vector3 pos, size; + if (_ui != null) + { + Gizmos.matrix = _ui.displayObject.cachedTransform.localToWorldMatrix; + pos = new Vector3(_ui.width / 2, -_ui.height / 2, 0); + size = new Vector3(_ui.width, _ui.height, 0); + } + else + { + Gizmos.matrix = this.container.cachedTransform.localToWorldMatrix; + pos = new Vector3(uiBounds.x + uiBounds.width / 2, -uiBounds.y - uiBounds.height / 2, 0); + size = new Vector3(uiBounds.width, uiBounds.height, 0); + } + + Gizmos.color = new Color(0, 0, 0, 0); + Gizmos.DrawCube(pos, size); + + Gizmos.color = Color.white; + Gizmos.DrawWireCube(pos, size); + } + + public int EM_sortingOrder + { + get { return sortingOrder; } + } + + public void EM_BeforeUpdate() + { + if (container == null) + CreateContainer(); + + if (packageName != null && componentName != null && _ui == null) + CreateUI_EditMode(); + + if (screenSizeVer != StageCamera.screenSizeVer) + HandleScreenSizeChanged(); + } + + public void EM_Update(UpdateContext context) + { + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + + container.Update(context); + + if (setNativeChildrenOrder) + { + CacheNativeChildrenRenderers(); + + int cnt = _renders.Count; + int sv = context.renderingOrder++; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if (r != null) + r.sortingOrder = sv; + } + } + } + + public void EM_Reload() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + } + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs.meta new file mode 100644 index 0000000..83d7a9f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/UIPanel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 024553ecf96a65649b929ee08c9214fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs new file mode 100644 index 0000000..493a432 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs @@ -0,0 +1,554 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Window class. + /// 窗口使用前首先要设置窗口中需要显示的内容,这通常是在编辑器里制作好的,可以直接使用Window.contentPane进行设置。 + /// 建议把设置contentPane等初始化操作放置到Window.onInit方法中。 + /// 另外,FairyGUI还提供了一套机制用于窗口动态创建。动态创建是指初始时仅指定窗口需要使用的资源,等窗口需要显示时才实际开始构建窗口的内容。 + /// 首先需要在窗口的构造函数中调用Window.addUISource。这个方法需要一个IUISource类型的参数,而IUISource是一个接口, + /// 用户需要自行实现载入相关UI包的逻辑。当窗口第一次显示之前,IUISource的加载方法将会被调用,并等待载入完成后才返回执行Window.OnInit,然后窗口才会显示。 + /// + /// 如果你需要窗口显示时播放动画效果,那么覆盖doShowAnimation编写你的动画代码,并且在动画结束后调用onShown。覆盖onShown编写其他需要在窗口显示时处理的业务逻辑。 + /// 如果你需要窗口隐藏时播放动画效果,那么覆盖doHideAnimation编写你的动画代码,并且在动画结束时调用Window.hideImmediately(注意不是直接调用onHide!)。覆盖onHide编写其他需要在窗口隐藏时处理的业务逻辑。 + /// + public class Window : GComponent + { + /// + /// + /// + public bool bringToFontOnClick; + + GComponent _frame; + GComponent _contentPane; + GObject _modalWaitPane; + GObject _closeButton; + GObject _dragArea; + GObject _contentArea; + bool _modal; + + List _uiSources; + bool _inited; + bool _loading; + + protected int _requestingCmd; + +#if FAIRYGUI_PUERTS + public Action __onInit; + public Action __onShown; + public Action __onHide; + public Action __doShowAnimation; + public Action __doHideAnimation; +#endif + + public Window() + : base() + { + _uiSources = new List(); + this.tabStopChildren = true; + bringToFontOnClick = UIConfig.bringWindowToFrontOnClick; + + displayObject.onAddedToStage.Add(__addedToStage); + displayObject.onRemovedFromStage.Add(__removeFromStage); + displayObject.onTouchBegin.AddCapture(__touchBegin); + + this.gameObjectName = "Window"; + SetHome(GRoot.inst); + } + + /// + /// Set a UISource to this window. It must call before the window is shown. When the window is first time to show, + /// UISource.Load is called. Only after all UISource is loaded, the window will continue to init. + /// 为窗口添加一个源。这个方法建议在构造函数调用。当窗口第一次显示前,UISource的Load方法将被调用,然后只有所有的UISource + /// 都ready后,窗口才会继续初始化和显示。 + /// + /// + public void AddUISource(IUISource source) + { + _uiSources.Add(source); + } + + /// + /// + /// + public GComponent contentPane + { + set + { + if (_contentPane != value) + { + if (_contentPane != null) + RemoveChild(_contentPane); + _contentPane = value; + if (_contentPane != null) + { + this.gameObjectName = "Window - " + _contentPane.gameObjectName; + _contentPane.gameObjectName = "ContentPane"; + + AddChild(_contentPane); + this.SetSize(_contentPane.width, _contentPane.height); + _contentPane.AddRelation(this, RelationType.Size); + _contentPane.fairyBatching = true; + _frame = _contentPane.GetChild("frame") as GComponent; + if (_frame != null) + { + this.closeButton = _frame.GetChild("closeButton"); + this.dragArea = _frame.GetChild("dragArea"); + this.contentArea = _frame.GetChild("contentArea"); + } + } + else + { + _frame = null; + this.gameObjectName = "Window"; + } + } + } + get + { + return _contentPane; + } + } + + /// + /// + /// + public GComponent frame + { + get { return _frame; } + } + + /// + /// + /// + public GObject closeButton + { + get { return _closeButton; } + set + { + if (_closeButton != null) + _closeButton.onClick.Remove(closeEventHandler); + _closeButton = value; + if (_closeButton != null) + _closeButton.onClick.Add(closeEventHandler); + } + } + + /// + /// + /// + public GObject dragArea + { + get { return _dragArea; } + set + { + if (_dragArea != value) + { + if (_dragArea != null) + { + _dragArea.draggable = false; + _dragArea.onDragStart.Remove(__dragStart); + } + + _dragArea = value; + if (_dragArea != null) + { + GGraph graph = _dragArea as GGraph; + if (graph != null && graph.shape.isEmpty) + graph.DrawRect(_dragArea.width, _dragArea.height, 0, Color.clear, Color.clear); + _dragArea.draggable = true; + _dragArea.onDragStart.Add(__dragStart); + } + } + } + } + + /// + /// + /// + public GObject contentArea + { + get { return _contentArea; } + set { _contentArea = value; } + } + + /// + /// + /// + public GObject modalWaitingPane + { + get { return _modalWaitPane; } + } + + /// + /// + /// + public void Show() + { + GRoot.inst.ShowWindow(this); + } + + /// + /// + /// + /// + public void ShowOn(GRoot r) + { + r.ShowWindow(this); + } + + /// + /// + /// + public void Hide() + { + if (this.isShowing) + DoHideAnimation(); + } + + /// + /// Hide window immediately, no OnHide will be called. + /// + public void HideImmediately() + { + this.root.HideWindowImmediately(this); + } + + /// + /// Make the window be center of the screen. + /// + /// + /// Add relations to ensure keeping center on screen size changed. + public void CenterOn(GRoot r, bool restraint) + { + this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2)); + if (restraint) + { + this.AddRelation(r, RelationType.Center_Center); + this.AddRelation(r, RelationType.Middle_Middle); + } + } + + /// + /// Switch show and hide status. + /// + public void ToggleStatus() + { + if (isTop) + Hide(); + else + Show(); + } + + /// + /// + /// + public bool isShowing + { + get { return parent != null; } + } + + /// + /// + /// + public bool isTop + { + get { return parent != null && parent.GetChildIndex(this) == parent.numChildren - 1; } + } + + /// + /// + /// + public bool modal + { + get { return _modal; } + set { _modal = value; } + } + + /// + /// + /// + public void BringToFront() + { + this.root.BringToFront(this); + } + + /// + /// + /// + public void ShowModalWait() + { + ShowModalWait(0); + } + + /// + /// Display a modal waiting sign in the front. + /// 显示一个等待标志在最前面。等待标志的资源可以通过UIConfig.windowModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 + /// 还可以设定一个requestingCmd作为等待的命令字,在CloseModalWait里传入相同的命令字ModalWait将结束,否则CloseModalWait无效。 + /// + /// + public void ShowModalWait(int requestingCmd) + { + if (requestingCmd != 0) + _requestingCmd = requestingCmd; + + if (UIConfig.windowModalWaiting != null) + { + if (_modalWaitPane == null) + { + _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.windowModalWaiting); + _modalWaitPane.SetHome(this); + } + + LayoutModalWaitPane(); + + AddChild(_modalWaitPane); + } + } + + virtual protected void LayoutModalWaitPane() + { + if (_contentArea != null) + { + Vector2 pt = _frame.LocalToGlobal(Vector2.zero); + pt = this.GlobalToLocal(pt); + _modalWaitPane.SetXY((int)pt.x + _contentArea.x, (int)pt.y + _contentArea.y); + _modalWaitPane.SetSize(_contentArea.width, _contentArea.height); + } + else + _modalWaitPane.SetSize(this.width, this.height); + } + + /// + /// + /// + /// + public bool CloseModalWait() + { + return CloseModalWait(0); + } + + /// + /// Close modal waiting. If rquestingCmd is equal to the value you transfer in ShowModalWait, mowal wait will be closed. + /// Otherwise, this function has no effect. + /// 关闭模式等待。如果requestingCmd和ShowModalWait传入的不相同,则这个函数没有任何动作,立即返回。 + /// + /// + /// + public bool CloseModalWait(int requestingCmd) + { + if (requestingCmd != 0) + { + if (_requestingCmd != requestingCmd) + return false; + } + _requestingCmd = 0; + + if (_modalWaitPane != null && _modalWaitPane.parent != null) + RemoveChild(_modalWaitPane); + + return true; + } + + /// + /// + /// + public bool modalWaiting + { + get { return (_modalWaitPane != null) && _modalWaitPane.inContainer; } + } + + /// + /// + /// + public void Init() + { + if (_inited || _loading) + return; + + if (_uiSources.Count > 0) + { + _loading = false; + int cnt = _uiSources.Count; + for (int i = 0; i < cnt; i++) + { + IUISource lib = _uiSources[i]; + if (!lib.loaded) + { + lib.Load(__uiLoadComplete); + _loading = true; + } + } + + if (!_loading) + _init(); + } + else + _init(); + } + + /// + /// + /// + virtual protected void OnInit() + { +#if FAIRYGUI_TOLUA + CallLua("OnInit"); +#endif +#if FAIRYGUI_PUERTS + if (__onInit != null) + __onInit(); +#endif + } + + /// + /// + /// + virtual protected void OnShown() + { +#if FAIRYGUI_TOLUA + CallLua("OnShown"); +#endif +#if FAIRYGUI_PUERTS + if (__onShown != null) + __onShown(); +#endif + } + + /// + /// + /// + virtual protected void OnHide() + { +#if FAIRYGUI_TOLUA + CallLua("OnHide"); +#endif +#if FAIRYGUI_PUERTS + if (__onHide != null) + __onHide(); +#endif + } + + /// + /// + /// + virtual protected void DoShowAnimation() + { +#if FAIRYGUI_TOLUA + if (!CallLua("DoShowAnimation")) + OnShown(); +#elif FAIRYGUI_PUERTS + if (__doShowAnimation != null) + __doShowAnimation(); + else + OnShown(); +#else + OnShown(); +#endif + } + + /// + /// + /// + virtual protected void DoHideAnimation() + { +#if FAIRYGUI_TOLUA + if (!CallLua("DoHideAnimation")) + HideImmediately(); +#elif FAIRYGUI_PUERTS + if (__doHideAnimation != null) + __doHideAnimation(); + else + HideImmediately(); +#else + HideImmediately(); +#endif + } + + void __uiLoadComplete() + { + int cnt = _uiSources.Count; + for (int i = 0; i < cnt; i++) + { + IUISource lib = _uiSources[i]; + if (!lib.loaded) + return; + } + + _loading = false; + _init(); + } + + void _init() + { + _inited = true; + OnInit(); + + if (this.isShowing) + DoShowAnimation(); + } + + override public void Dispose() + { + if (_modalWaitPane != null && _modalWaitPane.parent == null) + _modalWaitPane.Dispose(); + + + //正在加载资源的异步过程中发生意外关闭 应该取消正在加载的load + if (_loading) + { + for (int i = 0; i < _uiSources.Count; ++i) + { + _uiSources[i].Cancel(); + } + } + + +#if FAIRYGUI_PUERTS + __onInit = null; + __onShown = null; + __onHide = null; + __doShowAnimation = null; + __doHideAnimation = null; +#endif + + base.Dispose(); + } + + virtual protected void closeEventHandler(EventContext context) + { + Hide(); + } + + void __addedToStage() + { + if (!_inited) + Init(); + else + DoShowAnimation(); + } + + void __removeFromStage() + { + CloseModalWait(); + OnHide(); + } + + private void __touchBegin(EventContext context) + { + if (this.isShowing && bringToFontOnClick) + { + BringToFront(); + } + } + + private void __dragStart(EventContext context) + { + context.PreventDefault(); + + this.StartDrag((int)context.data); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs.meta new file mode 100644 index 0000000..035155b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/UI/Window.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c454632cb96595b4cbeeee678a5d9f0b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils.meta new file mode 100644 index 0000000..1462d24 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d78e1a4b8ac1336498bfbbe945d16276 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs new file mode 100644 index 0000000..5ef8ba8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs @@ -0,0 +1,455 @@ +using System; +using System.Text; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class ByteBuffer + { + /// + /// + /// + public bool littleEndian; + + /// + /// + /// + public string[] stringTable; + + /// + /// + /// + public int version; + + int _pointer; + int _offset; + int _length; + byte[] _data; + + static byte[] temp = new byte[8]; + + /// + /// + /// + /// + /// + /// + public ByteBuffer(byte[] data, int offset = 0, int length = -1) + { + _data = data; + _pointer = 0; + _offset = offset; + if (length < 0) + _length = data.Length - offset; + else + _length = length; + littleEndian = false; + } + + /// + /// + /// + public int position + { + get { return _pointer; } + set { _pointer = value; } + } + + /// + /// + /// + public int length + { + get { return _length; } + } + + /// + /// + /// + public bool bytesAvailable + { + get { return _pointer < _length; } + } + + /// + /// + /// + public byte[] buffer + { + get { return _data; } + set + { + _data = value; + _pointer = 0; + _offset = 0; + _length = _data.Length; + } + } + + /// + /// + /// + /// + /// + public int Skip(int count) + { + _pointer += count; + return _pointer; + } + + /// + /// + /// + /// + public byte ReadByte() + { + return _data[_offset + _pointer++]; + } + + /// + /// + /// + /// + /// + /// + /// + public byte[] ReadBytes(byte[] output, int destIndex, int count) + { + if (count > _length - _pointer) + throw new ArgumentOutOfRangeException(); + + Array.Copy(_data, _offset + _pointer, output, destIndex, count); + _pointer += count; + return output; + } + + /// + /// + /// + /// + /// + public byte[] ReadBytes(int count) + { + if (count > _length - _pointer) + throw new ArgumentOutOfRangeException(); + + byte[] result = new byte[count]; + Array.Copy(_data, _offset + _pointer, result, 0, count); + _pointer += count; + return result; + } + + /// + /// + /// + /// + public ByteBuffer ReadBuffer() + { + int count = ReadInt(); + ByteBuffer ba = new ByteBuffer(_data, _pointer, count); + ba.stringTable = stringTable; + ba.version = version; + _pointer += count; + return ba; + } + + /// + /// + /// + /// + public char ReadChar() + { + return (char)ReadShort(); + } + + /// + /// + /// + /// + public bool ReadBool() + { + bool result = _data[_offset + _pointer] == 1; + _pointer++; + return result; + } + + /// + /// + /// + /// + public short ReadShort() + { + int startIndex = _offset + _pointer; + _pointer += 2; + if (littleEndian) + return (short)(_data[startIndex] | (_data[startIndex + 1] << 8)); + else + return (short)((_data[startIndex] << 8) | _data[startIndex + 1]); + } + + /// + /// + /// + /// + public ushort ReadUshort() + { + return (ushort)ReadShort(); + } + + /// + /// + /// + /// + public int ReadInt() + { + int startIndex = _offset + _pointer; + _pointer += 4; + if (littleEndian) + return (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); + else + return (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); + } + + /// + /// + /// + /// + public uint ReadUint() + { + return (uint)ReadInt(); + } + + /// + /// + /// + /// + public float ReadFloat() + { + int startIndex = _offset + _pointer; + _pointer += 4; + if (littleEndian == BitConverter.IsLittleEndian) + return BitConverter.ToSingle(_data, startIndex); + else + { + temp[3] = _data[startIndex]; + temp[2] = _data[startIndex + 1]; + temp[1] = _data[startIndex + 2]; + temp[0] = _data[startIndex + 3]; + return BitConverter.ToSingle(temp, 0); + } + } + + /// + /// + /// + /// + public long ReadLong() + { + int startIndex = _offset + _pointer; + _pointer += 8; + if (littleEndian) + { + int i1 = (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); + int i2 = (_data[startIndex + 4]) | (_data[startIndex + 5] << 8) | (_data[startIndex + 6] << 16) | (_data[startIndex + 7] << 24); + return (uint)i1 | ((long)i2 << 32); + } + else + { + int i1 = (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); + int i2 = (_data[startIndex + 4] << 24) | (_data[startIndex + 5] << 16) | (_data[startIndex + 6] << 8) | (_data[startIndex + 7]); + return (uint)i2 | ((long)i1 << 32); + } + } + + /// + /// + /// + /// + public double ReadDouble() + { + int startIndex = _offset + _pointer; + _pointer += 8; + if (littleEndian == BitConverter.IsLittleEndian) + return BitConverter.ToDouble(_data, startIndex); + else + { + temp[7] = _data[startIndex]; + temp[6] = _data[startIndex + 1]; + temp[5] = _data[startIndex + 2]; + temp[4] = _data[startIndex + 3]; + temp[3] = _data[startIndex + 4]; + temp[2] = _data[startIndex + 5]; + temp[1] = _data[startIndex + 6]; + temp[0] = _data[startIndex + 7]; + return BitConverter.ToSingle(temp, 0); + } + } + + /// + /// + /// + /// + public string ReadString() + { + ushort len = ReadUshort(); + string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); + _pointer += len; + return result; + } + + /// + /// + /// + /// + /// + public string ReadString(int len) + { + string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); + _pointer += len; + return result; + } + + /// + /// + /// + /// + public string ReadS() + { + int index = ReadUshort(); + if (index == 65534) //null + return null; + else if (index == 65533) + return string.Empty; + else + return stringTable[index]; + } + + /// + /// + /// + /// + /// + public string[] ReadSArray(int cnt) + { + string[] ret = new string[cnt]; + for (int i = 0; i < cnt; i++) + ret[i] = ReadS(); + + return ret; + } + + private static List helperPoints = new List(); + + /// + /// + /// + /// + public List ReadPath() + { + helperPoints.Clear(); + + int len = ReadInt(); + if (len == 0) + return helperPoints; + + for (int i = 0; i < len; i++) + { + GPathPoint.CurveType curveType = (GPathPoint.CurveType)ReadByte(); + switch (curveType) + { + case GPathPoint.CurveType.Bezier: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0))); + break; + + case GPathPoint.CurveType.CubicBezier: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0))); + break; + + default: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), curveType)); + break; + } + } + + return helperPoints; + } + + /// + /// + /// + /// + public void WriteS(string value) + { + int index = ReadUshort(); + if (index != 65534 && index != 65533) + stringTable[index] = value; + } + + /// + /// + /// + /// + public Color ReadColor() + { + int startIndex = _offset + _pointer; + byte r = _data[startIndex]; + byte g = _data[startIndex + 1]; + byte b = _data[startIndex + 2]; + byte a = _data[startIndex + 3]; + _pointer += 4; + + return new Color32(r, g, b, a); + } + + /// + /// + /// + /// + /// + /// + public bool Seek(int indexTablePos, int blockIndex) + { + int tmp = _pointer; + _pointer = indexTablePos; + int segCount = _data[_offset + _pointer++]; + if (blockIndex < segCount) + { + bool useShort = _data[_offset + _pointer++] == 1; + int newPos; + if (useShort) + { + _pointer += 2 * blockIndex; + newPos = ReadShort(); + } + else + { + _pointer += 4 * blockIndex; + newPos = ReadInt(); + } + + if (newPos > 0) + { + _pointer = indexTablePos + newPos; + return true; + } + else + { + _pointer = tmp; + return false; + } + } + else + { + _pointer = tmp; + return false; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs.meta new file mode 100644 index 0000000..d816b01 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ByteBuffer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f72828fa75e491f4d95f92a46b01956a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html.meta new file mode 100644 index 0000000..31872d9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: da6063debdf749748bac0a0029b709e5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs new file mode 100644 index 0000000..0f64c14 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs @@ -0,0 +1,102 @@ +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlButton : IHtmlObject + { + public GComponent button { get; private set; } + + public const string CLICK_EVENT = "OnHtmlButtonClick"; + + public static string resource; + + RichTextField _owner; + HtmlElement _element; + EventCallback1 _clickHandler; + + public HtmlButton() + { + if (resource != null) + { + button = UIPackage.CreateObjectFromURL(resource).asCom; + _clickHandler = (EventContext context) => + { + _owner.DispatchEvent(CLICK_EVENT, context.data, this); + }; + } + else + Debug.LogWarning("FairyGUI: Set HtmlButton.resource first"); + } + + public DisplayObject displayObject + { + get { return button != null ? button.displayObject : null; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return button != null ? button.width : 0; } + } + + public float height + { + get { return button != null ? button.height : 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + if (button == null) + return; + + button.onClick.Add(_clickHandler); + int width = element.GetInt("width", button.sourceWidth); + int height = element.GetInt("height", button.sourceHeight); + button.SetSize(width, height); + button.text = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (button != null) + button.SetXY(x, y); + } + + public void Add() + { + if (button != null) + _owner.AddChild(button.displayObject); + } + + public void Remove() + { + if (button != null && button.displayObject.parent != null) + _owner.RemoveChild(button.displayObject); + } + + public void Release() + { + if (button != null) + button.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + if (button != null) + button.Dispose(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs.meta new file mode 100644 index 0000000..654a488 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlButton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 268c2d7ad77b66449b4e0e39a6d0ca15 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs new file mode 100644 index 0000000..034c861 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs @@ -0,0 +1,207 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public enum HtmlElementType + { + Text, + Link, + Image, + Input, + Select, + Object, + + //internal + LinkEnd, + } + + /// + /// + /// + public class HtmlElement + { + public HtmlElementType type; + public string name; + public string text; + public TextFormat format; + public int charIndex; + + public IHtmlObject htmlObject; + public int status; //1 hidden 2 clipped 4 added + public int space; + public Vector2 position; + + Hashtable attributes; + + public HtmlElement() + { + format = new TextFormat(); + } + + public object Get(string attrName) + { + if (attributes == null) + return null; + + return attributes[attrName]; + } + + public void Set(string attrName, object attrValue) + { + if (attributes == null) + attributes = new Hashtable(); + + attributes[attrName] = attrValue; + } + + public string GetString(string attrName) + { + return GetString(attrName, null); + } + + public string GetString(string attrName, string defValue) + { + if (attributes == null) + return defValue; + + object ret = attributes[attrName]; + if (ret != null) + return ret.ToString(); + else + return defValue; + } + + public int GetInt(string attrName) + { + return GetInt(attrName, 0); + } + + public int GetInt(string attrName, int defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + if (value[value.Length - 1] == '%') + { + int ret; + if (int.TryParse(value.Substring(0, value.Length - 1), out ret)) + return Mathf.CeilToInt(ret / 100.0f * defValue); + else + return defValue; + } + else + { + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + } + + public float GetFloat(string attrName) + { + return GetFloat(attrName, 0); + } + + public float GetFloat(string attrName, float defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public bool GetBool(string attrName) + { + return GetBool(attrName, false); + } + + public bool GetBool(string attrName, bool defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public Color GetColor(string attrName, Color defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + return ToolSet.ConvertFromHtmlColor(value); + } + + public void FetchAttributes() + { + attributes = XMLIterator.GetAttributes(attributes); + } + + + public bool isEntity + { + get { return type == HtmlElementType.Image || type == HtmlElementType.Select || type == HtmlElementType.Input || type == HtmlElementType.Object; } + } + + #region Pool Support + + static Stack elementPool = new Stack(); + + public static HtmlElement GetElement(HtmlElementType type) + { + HtmlElement ret; + if (elementPool.Count > 0) + ret = elementPool.Pop(); + else + ret = new HtmlElement(); + ret.type = type; + + if (type != HtmlElementType.Text && ret.attributes == null) + ret.attributes = new Hashtable(); + + return ret; + } + + public static void ReturnElement(HtmlElement element) + { + element.name = null; + element.text = null; + element.htmlObject = null; + element.status = 0; + if (element.attributes != null) + element.attributes.Clear(); + elementPool.Push(element); + } + + public static void ReturnElements(List elements) + { + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + ReturnElement(element); + } + elements.Clear(); + } + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs.meta new file mode 100644 index 0000000..da5843d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlElement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d92c6025bf750145af0e456a7fd3f33 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs new file mode 100644 index 0000000..d5dbcf3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs @@ -0,0 +1,122 @@ +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlImage : IHtmlObject + { + public GLoader loader { get; private set; } + + RichTextField _owner; + HtmlElement _element; + bool _externalTexture; + + public HtmlImage() + { + loader = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); + loader.gameObjectName = "HtmlImage"; + loader.fill = FillType.ScaleFree; + loader.touchable = false; + } + + public DisplayObject displayObject + { + get { return loader.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return loader.width; } + } + + public float height + { + get { return loader.height; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + int sourceWidth = 0; + int sourceHeight = 0; + NTexture texture = owner.htmlPageContext.GetImageTexture(this); + if (texture != null) + { + sourceWidth = texture.width; + sourceHeight = texture.height; + + loader.texture = texture; + _externalTexture = true; + } + else + { + string src = element.GetString("src"); + if (src != null) + { + PackageItem pi = UIPackage.GetItemByURL(src); + if (pi != null) + { + sourceWidth = pi.width; + sourceHeight = pi.height; + } + } + + loader.url = src; + _externalTexture = false; + } + + int width = element.GetInt("width", sourceWidth); + int height = element.GetInt("height", sourceHeight); + + if (width == 0) + width = 5; + if (height == 0) + height = 10; + loader.SetSize(width, height); + } + + public void SetPosition(float x, float y) + { + loader.SetXY(x, y); + } + + public void Add() + { + _owner.AddChild(loader.displayObject); + } + + public void Remove() + { + if (loader.displayObject.parent != null) + _owner.RemoveChild(loader.displayObject); + } + + public void Release() + { + loader.RemoveEventListeners(); + if (_externalTexture) + { + _owner.htmlPageContext.FreeImageTexture(this, loader.texture); + _externalTexture = false; + } + + loader.url = null; + _owner = null; + _element = null; + } + + public void Dispose() + { + if (_externalTexture) + _owner.htmlPageContext.FreeImageTexture(this, loader.texture); + loader.Dispose(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs.meta new file mode 100644 index 0000000..5ab2f9b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlImage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81871e13cb458ab4da28358d5634e082 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs new file mode 100644 index 0000000..84e3b24 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs @@ -0,0 +1,117 @@ +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlInput : IHtmlObject + { + public GTextInput textInput { get; private set; } + + RichTextField _owner; + HtmlElement _element; + bool _hidden; + + public static int defaultBorderSize = 2; + public static Color defaultBorderColor = ToolSet.ColorFromRGB(0xA9A9A9); + public static Color defaultBackgroundColor = Color.clear; + + public HtmlInput() + { + textInput = (GTextInput)UIObjectFactory.NewObject(ObjectType.InputText); + textInput.gameObjectName = "HtmlInput"; + textInput.verticalAlign = VertAlignType.Middle; + } + + public DisplayObject displayObject + { + get { return textInput.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return _hidden ? 0 : textInput.width; } + } + + public float height + { + get { return _hidden ? 0 : textInput.height; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + string type = element.GetString("type"); + if (type != null) + type = type.ToLower(); + + _hidden = type == "hidden"; + if (!_hidden) + { + int width = element.GetInt("width", 0); + int height = element.GetInt("height", 0); + int borderSize = element.GetInt("border", defaultBorderSize); + Color borderColor = element.GetColor("border-color", defaultBorderColor); + Color backgroundColor = element.GetColor("background-color", defaultBackgroundColor); + + if (width == 0) + { + width = element.space; + if (width > _owner.width / 2 || width < 100) + width = (int)_owner.width / 2; + } + if (height == 0) + height = element.format.size + 10; + + textInput.textFormat = element.format; + textInput.displayAsPassword = type == "password"; + textInput.maxLength = element.GetInt("maxlength", int.MaxValue); + textInput.border = borderSize; + textInput.borderColor = borderColor; + textInput.backgroundColor = backgroundColor; + textInput.SetSize(width, height); + } + textInput.text = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (!_hidden) + textInput.SetXY(x, y); + } + + public void Add() + { + if (!_hidden) + _owner.AddChild(textInput.displayObject); + } + + public void Remove() + { + if (!_hidden && textInput.displayObject.parent != null) + _owner.RemoveChild(textInput.displayObject); + } + + public void Release() + { + textInput.RemoveEventListeners(); + textInput.text = null; + + _owner = null; + _element = null; + } + + public void Dispose() + { + textInput.Dispose(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs.meta new file mode 100644 index 0000000..b56bee6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlInput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1c8ffa51408aef45839b1d00198b819 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs new file mode 100644 index 0000000..461e03c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs @@ -0,0 +1,113 @@ + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlLink : IHtmlObject + { + RichTextField _owner; + HtmlElement _element; + SelectionShape _shape; + + EventCallback1 _clickHandler; + EventCallback1 _rolloverHandler; + EventCallback0 _rolloutHandler; + + public HtmlLink() + { + _shape = new SelectionShape(); + _shape.gameObject.name = "HtmlLink"; + _shape.cursor = "text-link"; + + _clickHandler = (EventContext context) => + { + _owner.BubbleEvent("onClickLink", _element.GetString("href")); + }; + _rolloverHandler = (EventContext context) => + { + if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) + _shape.color = _owner.htmlParseOptions.linkHoverBgColor; + }; + _rolloutHandler = () => + { + if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) + _shape.color = _owner.htmlParseOptions.linkBgColor; + }; + } + + public DisplayObject displayObject + { + get { return _shape; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return 0; } + } + + public float height + { + get { return 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + _shape.onClick.Add(_clickHandler); + _shape.onRollOver.Add(_rolloverHandler); + _shape.onRollOut.Add(_rolloutHandler); + _shape.color = _owner.htmlParseOptions.linkBgColor; + } + + public void SetArea(int startLine, float startCharX, int endLine, float endCharX) + { + if (startLine == endLine && startCharX > endCharX) + { + float tmp = startCharX; + startCharX = endCharX; + endCharX = tmp; + } + _shape.rects.Clear(); + _owner.textField.GetLinesShape(startLine, startCharX, endLine, endCharX, true, _shape.rects); + _shape.Refresh(); + } + + public void SetPosition(float x, float y) + { + _shape.SetXY(x, y); + } + + public void Add() + { + //add below _shape + _owner.AddChildAt(_shape, 0); + } + + public void Remove() + { + if (_shape.parent != null) + _owner.RemoveChild(_shape); + } + + public void Release() + { + _shape.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + _shape.Dispose(); + _shape = null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs.meta new file mode 100644 index 0000000..b06ccd7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlLink.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2132a66ecae9cc4c99c6fbe37051723 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs new file mode 100644 index 0000000..f80d6b1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs @@ -0,0 +1,150 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlPageContext : IHtmlPageContext + { + Stack _imagePool; + Stack _inputPool; + Stack _buttonPool; + Stack _selectPool; + Stack _linkPool; + + public static HtmlPageContext inst = new HtmlPageContext(); + + static Transform _poolManager; + + public HtmlPageContext() + { + _imagePool = new Stack(); + _inputPool = new Stack(); + _buttonPool = new Stack(); + _selectPool = new Stack(); + _linkPool = new Stack(); + + if (Application.isPlaying && _poolManager == null) + _poolManager = Stage.inst.CreatePoolManager("HtmlObjectPool"); + } + + virtual public IHtmlObject CreateObject(RichTextField owner, HtmlElement element) + { + IHtmlObject ret = null; + bool fromPool = false; + if (element.type == HtmlElementType.Image) + { + if (_imagePool.Count > 0 && _poolManager != null) + { + ret = _imagePool.Pop(); + fromPool = true; + } + else + ret = new HtmlImage(); + } + else if (element.type == HtmlElementType.Link) + { + if (_linkPool.Count > 0 && _poolManager != null) + { + ret = _linkPool.Pop(); + fromPool = true; + } + else + ret = new HtmlLink(); + } + else if (element.type == HtmlElementType.Input) + { + string type = element.GetString("type"); + if (type != null) + type = type.ToLower(); + if (type == "button" || type == "submit") + { + if (_buttonPool.Count > 0 && _poolManager != null) + { + ret = _buttonPool.Pop(); + fromPool = true; + } + else + ret = new HtmlButton(); + } + else + { + if (_inputPool.Count > 0 && _poolManager != null) + { + ret = _inputPool.Pop(); + fromPool = true; + } + else + ret = new HtmlInput(); + } + } + else if (element.type == HtmlElementType.Select) + { + if (_selectPool.Count > 0 && _poolManager != null) + { + ret = _selectPool.Pop(); + fromPool = true; + } + else + ret = new HtmlSelect(); + } + + //Debug.Log("from=" + fromPool); + if (ret != null) + { + //可能已经被GameObject tree deleted了,不再使用 + if (fromPool && ret.displayObject != null && ret.displayObject.isDisposed) + { + ret.Dispose(); + return CreateObject(owner, element); + + } + ret.Create(owner, element); + if (ret.displayObject != null) + ret.displayObject.home = owner.cachedTransform; + } + + return ret; + } + + virtual public void FreeObject(IHtmlObject obj) + { + if (_poolManager == null) + { + obj.Dispose(); + return; + } + + //可能已经被GameObject tree deleted了,不再回收 + if (obj.displayObject != null && obj.displayObject.isDisposed) + { + obj.Dispose(); + return; + } + + obj.Release(); + if (obj is HtmlImage) + _imagePool.Push(obj); + else if (obj is HtmlInput) + _inputPool.Push(obj); + else if (obj is HtmlButton) + _buttonPool.Push(obj); + else if (obj is HtmlLink) + _linkPool.Push(obj); + + if (obj.displayObject != null) + obj.displayObject.cachedTransform.SetParent(_poolManager, false); + } + + virtual public NTexture GetImageTexture(HtmlImage image) + { + return null; + } + + virtual public void FreeImageTexture(HtmlImage image, NTexture texture) + { + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs.meta new file mode 100644 index 0000000..18afd1a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlPageContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5454bca8f43f9094ea66614837a2c0be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs new file mode 100644 index 0000000..c4c54c1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs @@ -0,0 +1,63 @@ +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlParseOptions + { + /// + /// + /// + public bool linkUnderline; + + /// + /// + /// + public Color linkColor; + + /// + /// + /// + public Color linkBgColor; + + /// + /// + /// + public Color linkHoverBgColor; + + /// + /// + /// + public bool ignoreWhiteSpace; + + /// + /// + /// + public static bool DefaultLinkUnderline = true; + + /// + /// + /// + public static Color DefaultLinkColor = new Color32(0x3A, 0x67, 0xCC, 0xFF); + + /// + /// + /// + public static Color DefaultLinkBgColor = Color.clear; + + /// + /// + /// + public static Color DefaultLinkHoverBgColor = Color.clear; + + public HtmlParseOptions() + { + linkUnderline = DefaultLinkUnderline; + linkColor = DefaultLinkColor; + linkBgColor = DefaultLinkBgColor; + linkHoverBgColor = DefaultLinkHoverBgColor; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs.meta new file mode 100644 index 0000000..0f7a766 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParseOptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e3e6e98345b46a43a4181a0790d4f30 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs new file mode 100644 index 0000000..481f1b2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs @@ -0,0 +1,385 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlParser + { + public static HtmlParser inst = new HtmlParser(); + + protected class TextFormat2 : TextFormat + { + public bool colorChanged; + } + + protected List _textFormatStack; + protected int _textFormatStackTop; + protected TextFormat2 _format; + protected List _elements; + protected HtmlParseOptions _defaultOptions; + + static List sHelperList1 = new List(); + static List sHelperList2 = new List(); + + public HtmlParser() + { + _textFormatStack = new List(); + _format = new TextFormat2(); + _defaultOptions = new HtmlParseOptions(); + } + + virtual public void Parse(string aSource, TextFormat defaultFormat, List elements, HtmlParseOptions parseOptions) + { + if (parseOptions == null) + parseOptions = _defaultOptions; + + _elements = elements; + _textFormatStackTop = 0; + _format.CopyFrom(defaultFormat); + _format.colorChanged = false; + int skipText = 0; + bool ignoreWhiteSpace = parseOptions.ignoreWhiteSpace; + bool skipNextCR = false; + string text; + + XMLIterator.Begin(aSource, true); + while (XMLIterator.NextTag()) + { + if (skipText == 0) + { + text = XMLIterator.GetText(ignoreWhiteSpace); + if (text.Length > 0) + { + if (skipNextCR && text[0] == '\n') + text = text.Substring(1); + AppendText(text); + } + } + + skipNextCR = false; + switch (XMLIterator.tagName) + { + case "b": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.bold = true; + } + else + PopTextFormat(); + break; + + case "i": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.italic = true; + } + else + PopTextFormat(); + break; + + case "u": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.underline = true; + } + else + PopTextFormat(); + break; + + case "strike": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.strikethrough = true; + } + else + PopTextFormat(); + break; + + case "sub": + { + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.specialStyle = TextFormat.SpecialStyle.Subscript; + } + else + PopTextFormat(); + } + break; + + case "sup": + { + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.specialStyle = TextFormat.SpecialStyle.Superscript; + } + else + PopTextFormat(); + } + break; + + case "font": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + + _format.size = XMLIterator.GetAttributeInt("size", _format.size); + string color = XMLIterator.GetAttribute("color"); + if (color != null) + { + string[] parts = color.Split(','); + if (parts.Length == 1) + { + _format.color = ToolSet.ConvertFromHtmlColor(color); + _format.gradientColor = null; + _format.colorChanged = true; + } + else + { + if (_format.gradientColor == null) + _format.gradientColor = new Color32[4]; + _format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]); + _format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]); + if (parts.Length > 2) + { + _format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]); + if (parts.Length > 3) + _format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]); + else + _format.gradientColor[3] = _format.gradientColor[2]; + } + else + { + _format.gradientColor[2] = _format.gradientColor[0]; + _format.gradientColor[3] = _format.gradientColor[1]; + } + } + } + } + else if (XMLIterator.tagType == XMLTagType.End) + PopTextFormat(); + break; + + case "br": + AppendText("\n"); + break; + + case "img": + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.align = _format.align; + _elements.Add(element); + } + break; + + case "a": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + + _format.underline = _format.underline || parseOptions.linkUnderline; + if (!_format.colorChanged && parseOptions.linkColor.a != 0) + _format.color = parseOptions.linkColor; + + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.align = _format.align; + _elements.Add(element); + } + else if (XMLIterator.tagType == XMLTagType.End) + { + PopTextFormat(); + + HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd); + _elements.Add(element); + } + break; + + case "input": + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.CopyFrom(_format); + _elements.Add(element); + } + break; + + case "select": + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select); + element.FetchAttributes(); + if (XMLIterator.tagType == XMLTagType.Start) + { + sHelperList1.Clear(); + sHelperList2.Clear(); + while (XMLIterator.NextTag()) + { + if (XMLIterator.tagName == "select") + break; + + if (XMLIterator.tagName == "option") + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty)); + else + sHelperList1.Add(XMLIterator.GetText()); + } + } + element.Set("items", sHelperList1.ToArray()); + element.Set("values", sHelperList2.ToArray()); + } + element.name = element.GetString("name"); + element.format.CopyFrom(_format); + _elements.Add(element); + } + } + break; + + case "p": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + string align = XMLIterator.GetAttribute("align"); + switch (align) + { + case "center": + _format.align = AlignType.Center; + break; + case "right": + _format.align = AlignType.Right; + break; + } + if (!IsNewLine()) + AppendText("\n"); + } + else if (XMLIterator.tagType == XMLTagType.End) + { + AppendText("\n"); + skipNextCR = true; + + PopTextFormat(); + } + break; + + case "ui": + case "div": + case "li": + if (XMLIterator.tagType == XMLTagType.Start) + { + if (!IsNewLine()) + AppendText("\n"); + } + else + { + AppendText("\n"); + skipNextCR = true; + } + break; + + case "html": + case "body": + //full html + ignoreWhiteSpace = true; + break; + + case "head": + case "style": + case "script": + case "form": + if (XMLIterator.tagType == XMLTagType.Start) + skipText++; + else if (XMLIterator.tagType == XMLTagType.End) + skipText--; + break; + } + } + + if (skipText == 0) + { + text = XMLIterator.GetText(ignoreWhiteSpace); + if (text.Length > 0) + { + if (skipNextCR && text[0] == '\n') + text = text.Substring(1); + AppendText(text); + } + } + + _elements = null; + } + + protected void PushTextFormat() + { + TextFormat2 tf; + if (_textFormatStack.Count <= _textFormatStackTop) + { + tf = new TextFormat2(); + _textFormatStack.Add(tf); + } + else + tf = _textFormatStack[_textFormatStackTop]; + tf.CopyFrom(_format); + tf.colorChanged = _format.colorChanged; + _textFormatStackTop++; + } + + protected void PopTextFormat() + { + if (_textFormatStackTop > 0) + { + TextFormat2 tf = _textFormatStack[_textFormatStackTop - 1]; + _format.CopyFrom(tf); + _format.colorChanged = tf.colorChanged; + _textFormatStackTop--; + } + } + + protected bool IsNewLine() + { + if (_elements.Count > 0) + { + HtmlElement element = _elements[_elements.Count - 1]; + if (element != null && element.type == HtmlElementType.Text) + return element.text.EndsWith("\n"); + else + return false; + } + + return true; + } + + protected void AppendText(string text) + { + HtmlElement element; + if (_elements.Count > 0) + { + element = _elements[_elements.Count - 1]; + if (element.type == HtmlElementType.Text && element.format.EqualStyle(_format)) + { + element.text += text; + return; + } + } + + element = HtmlElement.GetElement(HtmlElementType.Text); + element.text = text; + element.format.CopyFrom(_format); + _elements.Add(element); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs.meta new file mode 100644 index 0000000..6082edf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ddf5eb218ff0cf438894e2ceb54f494 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs new file mode 100644 index 0000000..a0bf79b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs @@ -0,0 +1,105 @@ +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlSelect : IHtmlObject + { + public GComboBox comboBox { get; private set; } + + public const string CHANGED_EVENT = "OnHtmlSelectChanged"; + + public static string resource; + + RichTextField _owner; + HtmlElement _element; + EventCallback0 _changeHandler; + + public HtmlSelect() + { + if (resource != null) + { + comboBox = UIPackage.CreateObjectFromURL(resource).asComboBox; + _changeHandler = () => + { + _owner.DispatchEvent(CHANGED_EVENT, null, this); + }; + } + else + Debug.LogWarning("FairyGUI: Set HtmlSelect.resource first"); + } + + public DisplayObject displayObject + { + get { return comboBox.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return comboBox != null ? comboBox.width : 0; } + } + + public float height + { + get { return comboBox != null ? comboBox.height : 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + if (comboBox == null) + return; + + comboBox.onChanged.Add(_changeHandler); + + int width = element.GetInt("width", comboBox.sourceWidth); + int height = element.GetInt("height", comboBox.sourceHeight); + comboBox.SetSize(width, height); + comboBox.items = (string[])element.Get("items"); + comboBox.values = (string[])element.Get("values"); + comboBox.value = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (comboBox != null) + comboBox.SetXY(x, y); + } + + public void Add() + { + if (comboBox != null) + _owner.AddChild(comboBox.displayObject); + } + + public void Remove() + { + if (comboBox != null && comboBox.displayObject.parent != null) + _owner.RemoveChild(comboBox.displayObject); + } + + public void Release() + { + if (comboBox != null) + comboBox.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + if (comboBox != null) + comboBox.Dispose(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs.meta new file mode 100644 index 0000000..4efeaf4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/HtmlSelect.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a9047de8f5e36634b9cb9d7270dfb1e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs new file mode 100644 index 0000000..ebbe41f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs @@ -0,0 +1,20 @@ +namespace FairyGUI.Utils +{ + /// + /// Create->SetPosition->(Add<->Remove)->Release->Dispose + /// + public interface IHtmlObject + { + float width { get; } + float height { get; } + DisplayObject displayObject { get; } + HtmlElement element { get; } + + void Create(RichTextField owner, HtmlElement element); + void SetPosition(float x, float y); + void Add(); + void Remove(); + void Release(); + void Dispose(); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs.meta new file mode 100644 index 0000000..ddf3089 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d5a416822d3ee0a4d80e32f6a03ba56f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs new file mode 100644 index 0000000..b876437 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs @@ -0,0 +1,15 @@ + +namespace FairyGUI.Utils +{ + /// + /// + /// + public interface IHtmlPageContext + { + IHtmlObject CreateObject(RichTextField owner, HtmlElement element); + void FreeObject(IHtmlObject obj); + + NTexture GetImageTexture(HtmlImage image); + void FreeImageTexture(HtmlImage image, NTexture texture); + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs.meta new file mode 100644 index 0000000..99f4785 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Html/IHtmlPageContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0f24771f8977b674aa4fbf86f45e2105 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs new file mode 100644 index 0000000..d5e1825 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs @@ -0,0 +1,283 @@ +using System.Collections.Generic; +using System.Collections; +using UnityEngine; + +namespace FairyGUI +{ + public delegate void TimerCallback(object param); + + /// + /// + /// + public class Timers + { + public static int repeat; + public static float time; + + public static bool catchCallbackExceptions = false; + + Dictionary _items; + Dictionary _toAdd; + List _toRemove; + List _pool; + + TimersEngine _engine; + GameObject gameObject; + + private static Timers _inst; + + public static Timers inst + { + get + { + if (_inst == null) + _inst = new Timers(); + return _inst; + } + } + + public Timers() + { + _inst = this; + gameObject = new GameObject("[FairyGUI.Timers]"); + gameObject.hideFlags = HideFlags.HideInHierarchy; + gameObject.SetActive(true); + if (Application.isPlaying) + { + Object.DontDestroyOnLoad(gameObject); + } + + _engine = gameObject.AddComponent(); + + _items = new Dictionary(); + _toAdd = new Dictionary(); + _toRemove = new List(); + _pool = new List(100); + } + + public void Add(float interval, int repeat, TimerCallback callback) + { + Add(interval, repeat, callback, null); + } + + /** + * @interval in seconds + * @repeat 0 indicate loop infinitely, otherwise the run count + **/ + public void Add(float interval, int repeat, TimerCallback callback, object callbackParam) + { + if (callback == null) + { + Debug.LogWarning("timer callback is null, " + interval + "," + repeat); + return; + } + + Anymous_T t; + if (_items.TryGetValue(callback, out t)) + { + t.set(interval, repeat, callback, callbackParam); + t.elapsed = 0; + t.deleted = false; + return; + } + + if (_toAdd.TryGetValue(callback, out t)) + { + t.set(interval, repeat, callback, callbackParam); + return; + } + + t = GetFromPool(); + t.interval = interval; + t.repeat = repeat; + t.callback = callback; + t.param = callbackParam; + _toAdd[callback] = t; + } + + public void CallLater(TimerCallback callback) + { + Add(0.001f, 1, callback); + } + + public void CallLater(TimerCallback callback, object callbackParam) + { + Add(0.001f, 1, callback, callbackParam); + } + + public void AddUpdate(TimerCallback callback) + { + Add(0.001f, 0, callback); + } + + public void AddUpdate(TimerCallback callback, object callbackParam) + { + Add(0.001f, 0, callback, callbackParam); + } + + public void StartCoroutine(IEnumerator routine) + { + _engine.StartCoroutine(routine); + } + + public bool Exists(TimerCallback callback) + { + if (_toAdd.ContainsKey(callback)) + return true; + + Anymous_T at; + if (_items.TryGetValue(callback, out at)) + return !at.deleted; + + return false; + } + + public void Remove(TimerCallback callback) + { + Anymous_T t; + if (_toAdd.TryGetValue(callback, out t)) + { + _toAdd.Remove(callback); + ReturnToPool(t); + } + + if (_items.TryGetValue(callback, out t)) + t.deleted = true; + } + + private Anymous_T GetFromPool() + { + Anymous_T t; + int cnt = _pool.Count; + if (cnt > 0) + { + t = _pool[cnt - 1]; + _pool.RemoveAt(cnt - 1); + t.deleted = false; + t.elapsed = 0; + } + else + t = new Anymous_T(); + + return t; + } + + private void ReturnToPool(Anymous_T t) + { + t.callback = null; + _pool.Add(t); + } + + public void Update() + { + float dt = Time.unscaledDeltaTime; + Dictionary.Enumerator iter; + + if (_items.Count > 0) + { + iter = _items.GetEnumerator(); + while (iter.MoveNext()) + { + Anymous_T i = iter.Current.Value; + if (i.deleted) + { + _toRemove.Add(i); + continue; + } + + i.elapsed += dt; + if (i.elapsed < i.interval) + continue; + + i.elapsed -= i.interval; + if (i.elapsed < 0 || i.elapsed > 0.03f) + i.elapsed = 0; + + if (i.repeat > 0) + { + i.repeat--; + if (i.repeat == 0) + { + i.deleted = true; + _toRemove.Add(i); + } + } + + repeat = i.repeat; + if (i.callback != null) + { + if (catchCallbackExceptions) + { + try + { + i.callback(i.param); + } + catch (System.Exception e) + { + i.deleted = true; + Debug.LogWarning("FairyGUI: timer(internal=" + i.interval + ", repeat=" + i.repeat + + ") callback error > " + e.Message); + } + } + else + i.callback(i.param); + } + } + + iter.Dispose(); + } + + int len = _toRemove.Count; + if (len > 0) + { + for (int k = 0; k < len; k++) + { + Anymous_T i = _toRemove[k]; + if (i.deleted && i.callback != null) + { + _items.Remove(i.callback); + ReturnToPool(i); + } + } + + _toRemove.Clear(); + } + + if (_toAdd.Count > 0) + { + iter = _toAdd.GetEnumerator(); + while (iter.MoveNext()) + _items.Add(iter.Current.Key, iter.Current.Value); + iter.Dispose(); + _toAdd.Clear(); + } + } + } + + class Anymous_T + { + public float interval; + public int repeat; + public TimerCallback callback; + public object param; + + public float elapsed; + public bool deleted; + + public void set(float interval, int repeat, TimerCallback callback, object param) + { + this.interval = interval; + this.repeat = repeat; + this.callback = callback; + this.param = param; + } + } + + class TimersEngine : MonoBehaviour + { + void Update() + { + Timers.inst.Update(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs.meta new file mode 100644 index 0000000..f386422 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/Timers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae007a032c404234b875df43f3129117 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs new file mode 100644 index 0000000..453baef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs @@ -0,0 +1,157 @@ +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public static class ToolSet + { + public static Color ConvertFromHtmlColor(string str) + { + if (str.Length < 7 || str[0] != '#') + return Color.black; + + if (str.Length == 9) + { + //optimize:avoid using Convert.ToByte and Substring + //return new Color32(Convert.ToByte(str.Substring(3, 2), 16), Convert.ToByte(str.Substring(5, 2), 16), + // Convert.ToByte(str.Substring(7, 2), 16), Convert.ToByte(str.Substring(1, 2), 16)); + + return new Color32((byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), + (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), + (byte)(CharToHex(str[7]) * 16 + CharToHex(str[8])), + (byte)(CharToHex(str[1]) * 16 + CharToHex(str[2]))); + } + else + { + //return new Color32(Convert.ToByte(str.Substring(1, 2), 16), Convert.ToByte(str.Substring(3, 2), 16), + //Convert.ToByte(str.Substring(5, 2), 16), 255); + + return new Color32((byte)(CharToHex(str[1]) * 16 + CharToHex(str[2])), + (byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), + (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), + 255); + } + } + + public static Color ColorFromRGB(int value) + { + return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, 1); + } + + public static Color ColorFromRGBA(uint value) + { + return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, ((value >> 24) & 0xFF) / 255f); + } + + public static int CharToHex(char c) + { + if (c >= '0' && c <= '9') + return (int)c - 48; + if (c >= 'A' && c <= 'F') + return 10 + (int)c - 65; + else if (c >= 'a' && c <= 'f') + return 10 + (int)c - 97; + else + return 0; + } + + public static Rect Intersection(ref Rect rect1, ref Rect rect2) + { + if (rect1.width == 0 || rect1.height == 0 || rect2.width == 0 || rect2.height == 0) + return new Rect(0, 0, 0, 0); + + float left = rect1.xMin > rect2.xMin ? rect1.xMin : rect2.xMin; + float right = rect1.xMax < rect2.xMax ? rect1.xMax : rect2.xMax; + float top = rect1.yMin > rect2.yMin ? rect1.yMin : rect2.yMin; + float bottom = rect1.yMax < rect2.yMax ? rect1.yMax : rect2.yMax; + + if (left > right || top > bottom) + return new Rect(0, 0, 0, 0); + else + return Rect.MinMaxRect(left, top, right, bottom); + } + + public static Rect Union(ref Rect rect1, ref Rect rect2) + { + if (rect2.width == 0 || rect2.height == 0) + return rect1; + + if (rect1.width == 0 || rect1.height == 0) + return rect2; + + float x = Mathf.Min(rect1.x, rect2.x); + float y = Mathf.Min(rect1.y, rect2.y); + return new Rect(x, y, Mathf.Max(rect1.xMax, rect2.xMax) - x, Mathf.Max(rect1.yMax, rect2.yMax) - y); + } + + /// + /// [Y ޸] + /// + public static void SetParent(Transform t, Transform parent) + { + if ((object)t.parent == (object)parent) + return; + +#if (UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_3_OR_NEWER) + t.SetParent(parent, false); +#else + Vector3 p = t.localPosition; + Vector3 s = t.localScale; + Quaternion q = t.localRotation; + t.parent = parent; + t.localPosition = p; + t.localScale = s; + t.localRotation = q; +#endif + } + + public static void SkewMatrix(ref Matrix4x4 matrix, float skewX, float skewY) + { + skewX = -skewX * Mathf.Deg2Rad; + skewY = -skewY * Mathf.Deg2Rad; + float sinX = Mathf.Sin(skewX); + float cosX = Mathf.Cos(skewX); + float sinY = Mathf.Sin(skewY); + float cosY = Mathf.Cos(skewY); + + float m00 = matrix.m00 * cosY - matrix.m10 * sinX; + float m10 = matrix.m00 * sinY + matrix.m10 * cosX; + float m01 = matrix.m01 * cosY - matrix.m11 * sinX; + float m11 = matrix.m01 * sinY + matrix.m11 * cosX; + float m02 = matrix.m02 * cosY - matrix.m12 * sinX; + float m12 = matrix.m02 * sinY + matrix.m12 * cosX; + + matrix.m00 = m00; + matrix.m10 = m10; + matrix.m01 = m01; + matrix.m11 = m11; + matrix.m02 = m02; + matrix.m12 = m12; + } + + public static void RotateUV(Vector2[] uv, ref Rect baseUVRect) + { + int vertCount = uv.Length; + float xMin = Mathf.Min(baseUVRect.xMin, baseUVRect.xMax); + float yMin = baseUVRect.yMin; + float yMax = baseUVRect.yMax; + if (yMin > yMax) + { + yMin = yMax; + yMax = baseUVRect.yMin; + } + + float tmp; + for (int i = 0; i < vertCount; i++) + { + Vector2 m = uv[i]; + tmp = m.y; + m.y = yMin + m.x - xMin; + m.x = xMin + yMax - tmp; + uv[i] = m; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs.meta new file mode 100644 index 0000000..7bfb8f8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ToolSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54357cad16a6ccb4ea698f76bb43527c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs new file mode 100644 index 0000000..b9ebd9b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs @@ -0,0 +1,226 @@ +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class UBBParser + { + public static UBBParser inst = new UBBParser(); + + string _text; + int _readPos; + + public TagHandler defaultTagHandler; + public Dictionary handlers; + + public int defaultImgWidth = 0; + public int defaultImgHeight = 0; + + public delegate string TagHandler(string tagName, bool end, string attr); + + public UBBParser() + { + handlers = new Dictionary(); + handlers["url"] = onTag_URL; + handlers["img"] = onTag_IMG; + handlers["b"] = onTag_Simple; + handlers["i"] = onTag_Simple; + handlers["u"] = onTag_Simple; + handlers["sup"] = onTag_Simple; + handlers["sub"] = onTag_Simple; + handlers["color"] = onTag_COLOR; + handlers["font"] = onTag_FONT; + handlers["size"] = onTag_SIZE; + handlers["align"] = onTag_ALIGN; + handlers["strike"] = onTag_Simple; + } + + protected string onTag_URL(string tagName, bool end, string attr) + { + if (!end) + { + if (attr != null) + return ""; + else + { + string href = GetTagText(false); + return ""; + } + } + else + return ""; + } + + protected string onTag_IMG(string tagName, bool end, string attr) + { + if (!end) + { + string src = GetTagText(true); + if (src == null || src.Length == 0) + return null; + + if (defaultImgWidth != 0) + return ""; + else + return ""; + } + else + return null; + } + + protected string onTag_Simple(string tagName, bool end, string attr) + { + return end ? ("") : ("<" + tagName + ">"); + } + + protected string onTag_COLOR(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_FONT(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_SIZE(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_ALIGN(string tagName, bool end, string attr) + { + if (!end) + return "

"; + else + return "

"; + } + + public string GetTagText(bool remove) + { + int pos1 = _readPos; + int pos2; + StringBuilder buffer = null; + while ((pos2 = _text.IndexOf('[', pos1)) != -1) + { + if (buffer == null) + buffer = new StringBuilder(); + + if (_text[pos2 - 1] == '\\') + { + buffer.Append(_text, pos1, pos2 - pos1 - 1); + buffer.Append('['); + pos1 = pos2 + 1; + } + else + { + buffer.Append(_text, pos1, pos2 - pos1); + break; + } + } + if (pos2 == -1) + return null; + + if (remove) + _readPos = pos2; + + return buffer.ToString(); + } + + public string Parse(string text) + { + _text = text; + int pos1 = 0, pos2, pos3; + bool end; + string tag, attr; + string repl; + StringBuilder buffer = null; + TagHandler func; + while ((pos2 = _text.IndexOf('[', pos1)) != -1) + { + if (buffer == null) + buffer = new StringBuilder(); + + if (pos2 > 0 && _text[pos2 - 1] == '\\') + { + buffer.Append(_text, pos1, pos2 - pos1 - 1); + buffer.Append('['); + pos1 = pos2 + 1; + continue; + } + + buffer.Append(_text, pos1, pos2 - pos1); + pos1 = pos2; + pos2 = _text.IndexOf(']', pos1); + if (pos2 == -1) + break; + + if (pos2 == pos1 + 1) + { + buffer.Append(_text, pos1, 2); + pos1 = pos2 + 1; + continue; + } + + end = _text[pos1 + 1] == '/'; + pos3 = end ? pos1 + 2 : pos1 + 1; + tag = _text.Substring(pos3, pos2 - pos3); + _readPos = pos2 + 1; + attr = null; + repl = null; + pos3 = tag.IndexOf('='); + if (pos3 != -1) + { + attr = tag.Substring(pos3 + 1); + tag = tag.Substring(0, pos3); + } + tag = tag.ToLower(); + if (handlers.TryGetValue(tag, out func)) + { + repl = func(tag, end, attr); + if (repl != null) + buffer.Append(repl); + } + else if (defaultTagHandler != null) + { + repl = defaultTagHandler(tag, end, attr); + if (repl != null) + buffer.Append(repl); + else + buffer.Append(_text, pos1, pos2 - pos1 + 1); + } + else + { + buffer.Append(_text, pos1, pos2 - pos1 + 1); + } + pos1 = _readPos; + } + + if (buffer == null) + { + _text = null; + return text; + } + else + { + if (pos1 < _text.Length) + buffer.Append(_text, pos1, _text.Length - pos1); + + _text = null; + return buffer.ToString(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs.meta new file mode 100644 index 0000000..b983021 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/UBBParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 916709794f601f949962dffdb251b946 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs new file mode 100644 index 0000000..788b7c6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs @@ -0,0 +1,427 @@ +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// A simplest and readonly XML class + /// + public class XML + { + public string name; + public string text; + + Dictionary _attributes; + XMLList _children; + + public static XML Create(string tag) + { + XML xml = new XML(); + xml.name = tag; + return xml; + } + + public XML(string XmlString) + { + Parse(XmlString); + } + + private XML() + { + } + + public Dictionary attributes + { + get + { + if (_attributes == null) + _attributes = new Dictionary(); + return _attributes; + } + } + + public bool HasAttribute(string attrName) + { + if (_attributes == null) + return false; + + return _attributes.ContainsKey(attrName); + } + + public string GetAttribute(string attrName) + { + return GetAttribute(attrName, null); + } + + public string GetAttribute(string attrName, string defValue) + { + if (_attributes == null) + return defValue; + + string ret; + if (_attributes.TryGetValue(attrName, out ret)) + return ret; + else + return defValue; + } + + public int GetAttributeInt(string attrName) + { + return GetAttributeInt(attrName, 0); + } + + public int GetAttributeInt(string attrName, int defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public float GetAttributeFloat(string attrName) + { + return GetAttributeFloat(attrName, 0); + } + + public float GetAttributeFloat(string attrName, float defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public bool GetAttributeBool(string attrName) + { + return GetAttributeBool(attrName, false); + } + + public bool GetAttributeBool(string attrName, bool defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public string[] GetAttributeArray(string attrName) + { + string value = GetAttribute(attrName); + if (value != null) + { + if (value.Length == 0) + return new string[] { }; + else + return value.Split(','); + } + else + return null; + } + + public string[] GetAttributeArray(string attrName, char seperator) + { + string value = GetAttribute(attrName); + if (value != null) + { + if (value.Length == 0) + return new string[] { }; + else + return value.Split(seperator); + } + else + return null; + } + + public Color GetAttributeColor(string attrName, Color defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + return ToolSet.ConvertFromHtmlColor(value); + } + + public Vector2 GetAttributeVector(string attrName) + { + string value = GetAttribute(attrName); + if (value != null) + { + string[] arr = value.Split(','); + return new Vector2(float.Parse(arr[0]), float.Parse(arr[1])); + } + else + return Vector2.zero; + } + + public void SetAttribute(string attrName, string attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue; + } + + public void SetAttribute(string attrName, bool attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue ? "true" : "false"; + } + + public void SetAttribute(string attrName, int attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue.ToString(); + } + + public void SetAttribute(string attrName, float attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = string.Format("{0:#.####}", attrValue); + } + + public void RemoveAttribute(string attrName) + { + if (_attributes != null) + _attributes.Remove(attrName); + } + + public XML GetNode(string selector) + { + if (_children == null) + return null; + else + return _children.Find(selector); + } + + public XMLList elements + { + get + { + if (_children == null) + _children = new XMLList(); + return _children; + } + } + + public XMLList Elements() + { + if (_children == null) + _children = new XMLList(); + return _children; + } + + public XMLList Elements(string selector) + { + if (_children == null) + _children = new XMLList(); + return _children.Filter(selector); + } + + public XMLList.Enumerator GetEnumerator() + { + if (_children == null) + return new XMLList.Enumerator(null, null); + else + return new XMLList.Enumerator(_children.rawList, null); + } + + public XMLList.Enumerator GetEnumerator(string selector) + { + if (_children == null) + return new XMLList.Enumerator(null, selector); + else + return new XMLList.Enumerator(_children.rawList, selector); + } + + public void AppendChild(XML child) + { + this.elements.Add(child); + } + + public void RemoveChild(XML child) + { + if (_children == null) + return; + + this._children.rawList.Remove(child); + } + + public void RemoveChildren(string selector) + { + if (_children == null) + return; + + if (string.IsNullOrEmpty(selector)) + _children.Clear(); + else + _children.RemoveAll(selector); + } + + static Stack sNodeStack = new Stack(); + public void Parse(string aSource) + { + Reset(); + + XML lastOpenNode = null; + sNodeStack.Clear(); + + XMLIterator.Begin(aSource); + while (XMLIterator.NextTag()) + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + XML childNode; + if (lastOpenNode != null) + childNode = new XML(); + else + { + if (this.name != null) + { + Reset(); + throw new Exception("Invalid xml format - no root node."); + } + childNode = this; + } + + childNode.name = XMLIterator.tagName; + childNode._attributes = XMLIterator.GetAttributes(childNode._attributes); + + if (lastOpenNode != null) + { + if (XMLIterator.tagType != XMLTagType.Void) + sNodeStack.Push(lastOpenNode); + if (lastOpenNode._children == null) + lastOpenNode._children = new XMLList(); + lastOpenNode._children.Add(childNode); + } + if (XMLIterator.tagType != XMLTagType.Void) + lastOpenNode = childNode; + } + else if (XMLIterator.tagType == XMLTagType.End) + { + if (lastOpenNode == null || lastOpenNode.name != XMLIterator.tagName) + { + Reset(); + throw new Exception("Invalid xml format - <" + XMLIterator.tagName + "> dismatched."); + } + + if (lastOpenNode._children == null || lastOpenNode._children.Count == 0) + { + lastOpenNode.text = XMLIterator.GetText(); + } + + if (sNodeStack.Count > 0) + lastOpenNode = sNodeStack.Pop(); + else + lastOpenNode = null; + } + } + } + + public void Reset() + { + if (_attributes != null) + _attributes.Clear(); + if (_children != null) + _children.Clear(); + this.text = null; + } + + public string ToXMLString(bool includeHeader) + { + StringBuilder sb = new StringBuilder(); + if (includeHeader) + sb.Append("\n"); + ToXMLString(sb, 0); + return sb.ToString(); + } + + void ToXMLString(StringBuilder sb, int tabs) + { + if (tabs > 0) + sb.Append(' ', tabs * 2); + + if (name == "!") + { + sb.Append(""); + return; + } + + sb.Append('<').Append(name); + if (_attributes != null) + { + foreach (KeyValuePair kv in _attributes) + { + sb.Append(' '); + sb.Append(kv.Key).Append('=').Append('\"'); + int c = sb.Length; + sb.Append(kv.Value); + XMLUtils.EncodeString(sb, c, true); + sb.Append("\""); + } + } + + int numChildren = _children != null ? _children.Count : 0; + + if (string.IsNullOrEmpty(text) && numChildren == 0) + sb.Append("/>"); + else + { + sb.Append('>'); + + if (!string.IsNullOrEmpty(text)) + { + int c = sb.Length; + sb.Append(text); + XMLUtils.EncodeString(sb, c); + } + + if (numChildren > 0) + { + sb.Append('\n'); + int ctabs = tabs + 1; + for (int i = 0; i < numChildren; i++) + { + _children[i].ToXMLString(sb, ctabs); + sb.Append('\n'); + } + + if (tabs > 0) + sb.Append(' ', tabs * 2); + } + + sb.Append(""); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs.meta new file mode 100644 index 0000000..7d85994 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XML.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8375f35e0c0dbc4429287ee8578f3cf1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs new file mode 100644 index 0000000..e7bfdc7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs @@ -0,0 +1,485 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI.Utils +{ + public enum XMLTagType + { + Start, + End, + Void, + CDATA, + Comment, + Instruction + } + + /// + /// + /// + public class XMLIterator + { + public static string tagName; + public static XMLTagType tagType; + public static string lastTagName; + + static string source; + static int sourceLen; + static int parsePos; + static int tagPos; + static int tagLength; + static int lastTagEnd; + static bool attrParsed; + static bool lowerCaseName; + static StringBuilder buffer = new StringBuilder(); + static Dictionary attributes = new Dictionary(); + + const string CDATA_START = ""; + const string COMMENT_START = ""; + + public static void Begin(string source, bool lowerCaseName = false) + { + XMLIterator.source = source; + XMLIterator.lowerCaseName = lowerCaseName; + sourceLen = source.Length; + parsePos = 0; + lastTagEnd = 0; + tagPos = 0; + tagLength = 0; + tagName = null; + } + + public static bool NextTag() + { + int pos; + char c; + tagType = XMLTagType.Start; + buffer.Length = 0; + lastTagEnd = parsePos; + attrParsed = false; + lastTagName = tagName; + + while ((pos = source.IndexOf('<', parsePos)) != -1) + { + parsePos = pos; + pos++; + + if (pos == sourceLen) + break; + + c = source[pos]; + if (c == '!') + { + if (sourceLen > pos + 7 && source.Substring(pos - 1, 9) == CDATA_START) + { + pos = source.IndexOf(CDATA_END, pos); + tagType = XMLTagType.CDATA; + tagName = string.Empty; + tagPos = parsePos; + if (pos == -1) + tagLength = sourceLen - parsePos; + else + tagLength = pos + 3 - parsePos; + parsePos += tagLength; + return true; + } + else if (sourceLen > pos + 2 && source.Substring(pos - 1, 4) == COMMENT_START) + { + pos = source.IndexOf(COMMENT_END, pos); + tagType = XMLTagType.Comment; + tagName = string.Empty; + tagPos = parsePos; + if (pos == -1) + tagLength = sourceLen - parsePos; + else + tagLength = pos + 3 - parsePos; + parsePos += tagLength; + return true; + } + else + { + pos++; + tagType = XMLTagType.Instruction; + } + } + else if (c == '/') + { + pos++; + tagType = XMLTagType.End; + } + else if (c == '?') + { + pos++; + tagType = XMLTagType.Instruction; + } + + for (; pos < sourceLen; pos++) + { + c = source[pos]; + if (Char.IsWhiteSpace(c) || c == '>' || c == '/') + break; + } + if (pos == sourceLen) + break; + + buffer.Append(source, parsePos + 1, pos - parsePos - 1); + if (buffer.Length > 0 && buffer[0] == '/') + buffer.Remove(0, 1); + + bool singleQuoted = false, doubleQuoted = false; + int possibleEnd = -1; + for (; pos < sourceLen; pos++) + { + c = source[pos]; + if (c == '"') + { + if (!singleQuoted) + doubleQuoted = !doubleQuoted; + } + else if (c == '\'') + { + if (!doubleQuoted) + singleQuoted = !singleQuoted; + } + + if (c == '>') + { + if (!(singleQuoted || doubleQuoted)) + { + possibleEnd = -1; + break; + } + + possibleEnd = pos; + } + else if (c == '<') + break; + } + if (possibleEnd != -1) + pos = possibleEnd; + + if (pos == sourceLen) + break; + + if (source[pos - 1] == '/') + tagType = XMLTagType.Void; + + tagName = buffer.ToString(); + if (lowerCaseName) + tagName = tagName.ToLower(); + tagPos = parsePos; + tagLength = pos + 1 - parsePos; + parsePos += tagLength; + + return true; + } + + tagPos = sourceLen; + tagLength = 0; + tagName = null; + return false; + } + + public static string GetTagSource() + { + return source.Substring(tagPos, tagLength); + } + + public static string GetRawText(bool trim = false) + { + if (lastTagEnd == tagPos) + return string.Empty; + else if (trim) + { + int i = lastTagEnd; + for (; i < tagPos; i++) + { + char c = source[i]; + if (!char.IsWhiteSpace(c)) + break; + } + + if (i == tagPos) + return string.Empty; + else + return source.Substring(i, tagPos - i).TrimEnd(); + } + else + return source.Substring(lastTagEnd, tagPos - lastTagEnd); + } + + public static string GetText(bool trim = false) + { + if (lastTagEnd == tagPos) + return string.Empty; + else if (trim) + { + int i = lastTagEnd; + for (; i < tagPos; i++) + { + char c = source[i]; + if (!char.IsWhiteSpace(c)) + break; + } + + if (i == tagPos) + return string.Empty; + else + return XMLUtils.DecodeString(source.Substring(i, tagPos - i).TrimEnd()); + } + else + return XMLUtils.DecodeString(source.Substring(lastTagEnd, tagPos - lastTagEnd)); + } + + public static bool HasAttribute(string attrName) + { + if (!attrParsed) + { + attributes.Clear(); + ParseAttributes(attributes); + attrParsed = true; + } + + return attributes.ContainsKey(attrName); + } + + public static string GetAttribute(string attrName) + { + if (!attrParsed) + { + attributes.Clear(); + ParseAttributes(attributes); + attrParsed = true; + } + + string value; + if (attributes.TryGetValue(attrName, out value)) + return value; + else + return null; + } + + public static string GetAttribute(string attrName, string defValue) + { + string ret = GetAttribute(attrName); + if (ret != null) + return ret; + else + return defValue; + } + + public static int GetAttributeInt(string attrName) + { + return GetAttributeInt(attrName, 0); + } + + public static int GetAttributeInt(string attrName, int defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static float GetAttributeFloat(string attrName) + { + return GetAttributeFloat(attrName, 0); + } + + public static float GetAttributeFloat(string attrName, float defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static bool GetAttributeBool(string attrName) + { + return GetAttributeBool(attrName, false); + } + + public static bool GetAttributeBool(string attrName, bool defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static Dictionary GetAttributes(Dictionary result) + { + if (result == null) + result = new Dictionary(); + + if (attrParsed) + { + foreach (KeyValuePair kv in attributes) + result[kv.Key] = kv.Value; + } + else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 + ParseAttributes(result); + + return result; + } + + public static Hashtable GetAttributes(Hashtable result) + { + if (result == null) + result = new Hashtable(); + + if (attrParsed) + { + foreach (KeyValuePair kv in attributes) + result[kv.Key] = kv.Value; + } + else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 + ParseAttributes(result); + + return result; + } + + static void ParseAttributes(IDictionary attrs) + { + string attrName; + int valueStart; + int valueEnd; + bool waitValue = false; + int quoted; + buffer.Length = 0; + int i = tagPos; + int attrEnd = tagPos + tagLength; + + if (i < attrEnd && source[i] == '<') + { + for (; i < attrEnd; i++) + { + char c = source[i]; + if (Char.IsWhiteSpace(c) || c == '>' || c == '/') + break; + } + } + + for (; i < attrEnd; i++) + { + char c = source[i]; + if (c == '=') + { + valueStart = -1; + valueEnd = -1; + quoted = 0; + for (int j = i + 1; j < attrEnd; j++) + { + char c2 = source[j]; + if (Char.IsWhiteSpace(c2)) + { + if (valueStart != -1 && quoted == 0) + { + valueEnd = j - 1; + break; + } + } + else if (c2 == '>') + { + if (quoted == 0) + { + valueEnd = j - 1; + break; + } + } + else if (c2 == '"') + { + if (valueStart != -1) + { + if (quoted != 1) + { + valueEnd = j - 1; + break; + } + } + else + { + quoted = 2; + valueStart = j + 1; + } + } + else if (c2 == '\'') + { + if (valueStart != -1) + { + if (quoted != 2) + { + valueEnd = j - 1; + break; + } + } + else + { + quoted = 1; + valueStart = j + 1; + } + } + else if (valueStart == -1) + { + valueStart = j; + } + } + + if (valueStart != -1 && valueEnd != -1) + { + attrName = buffer.ToString(); + if (lowerCaseName) + attrName = attrName.ToLower(); + buffer.Length = 0; + attrs[attrName] = XMLUtils.DecodeString(source.Substring(valueStart, valueEnd - valueStart + 1)); + i = valueEnd + 1; + } + else + break; + } + else if (!Char.IsWhiteSpace(c)) + { + if (waitValue || c == '/' || c == '>') + { + if (buffer.Length > 0) + { + attrName = buffer.ToString(); + if (lowerCaseName) + attrName = attrName.ToLower(); + attrs[attrName] = string.Empty; + buffer.Length = 0; + } + + waitValue = false; + } + + if (c != '/' && c != '>') + buffer.Append(c); + } + else + { + if (buffer.Length > 0) + waitValue = true; + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs.meta new file mode 100644 index 0000000..b13d256 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLIterator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35c75485c4f537341bbc16207588f75d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs new file mode 100644 index 0000000..73d80d3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs @@ -0,0 +1,143 @@ +using System.Collections.Generic; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class XMLList + { + public List rawList; + + public XMLList() + { + rawList = new List(); + } + + public XMLList(List list) + { + rawList = list; + } + + public void Add(XML xml) + { + rawList.Add(xml); + } + + public void Clear() + { + rawList.Clear(); + } + + public int Count + { + get { return rawList.Count; } + } + + public XML this[int index] + { + get { return rawList[index]; } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(rawList, null); + } + + public Enumerator GetEnumerator(string selector) + { + return new Enumerator(rawList, selector); + } + + static List _tmpList = new List(); + public XMLList Filter(string selector) + { + bool allFit = true; + _tmpList.Clear(); + int cnt = rawList.Count; + for (int i = 0; i < cnt; i++) + { + XML xml = rawList[i]; + if (xml.name == selector) + _tmpList.Add(xml); + else + allFit = false; + } + + if (allFit) + return this; + else + { + XMLList ret = new XMLList(_tmpList); + _tmpList = new List(); + return ret; + } + } + + public XML Find(string selector) + { + int cnt = rawList.Count; + for (int i = 0; i < cnt; i++) + { + XML xml = rawList[i]; + if (xml.name == selector) + return xml; + } + return null; + } + + public void RemoveAll(string selector) + { + rawList.RemoveAll(xml => xml.name == selector); + } + + public struct Enumerator + { + List _source; + string _selector; + int _index; + int _total; + XML _current; + + public Enumerator(List source, string selector) + { + _source = source; + _selector = selector; + _index = -1; + if (_source != null) + _total = _source.Count; + else + _total = 0; + _current = null; + } + + public XML Current + { + get { return _current; } + } + + public bool MoveNext() + { + while (++_index < _total) + { + _current = _source[_index]; + if (_selector == null || _current.name == _selector) + return true; + } + + return false; + } + + public void Erase() + { + _source.RemoveAt(_index); + _total--; + } + + public void Reset() + { + _index = -1; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs.meta new file mode 100644 index 0000000..3ccd2d2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f086b805cd249140987f7f3ec5b4567 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs new file mode 100644 index 0000000..8838cf3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs @@ -0,0 +1,133 @@ +using System; +using System.Text; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class XMLUtils + { + public static string DecodeString(string aSource) + { + int len = aSource.Length; + StringBuilder sb = new StringBuilder(); + int pos1 = 0, pos2 = 0; + + while (true) + { + pos2 = aSource.IndexOf('&', pos1); + if (pos2 == -1) + { + sb.Append(aSource.Substring(pos1)); + break; + } + sb.Append(aSource.Substring(pos1, pos2 - pos1)); + + pos1 = pos2 + 1; + pos2 = pos1; + int end = Math.Min(len, pos2 + 10); + for (; pos2 < end; pos2++) + { + if (aSource[pos2] == ';') + break; + } + if (pos2 < end && pos2 > pos1) + { + string entity = aSource.Substring(pos1, pos2 - pos1); + int u = 0; + if (entity[0] == '#') + { + if (entity.Length > 1) + { + if (entity[1] == 'x') + u = Convert.ToInt16(entity.Substring(2), 16); + else + u = Convert.ToInt16(entity.Substring(1)); + sb.Append((char)u); + pos1 = pos2 + 1; + } + else + sb.Append('&'); + } + else + { + switch (entity) + { + case "amp": + u = 38; + break; + + case "apos": + u = 39; + break; + + case "gt": + u = 62; + break; + + case "lt": + u = 60; + break; + + case "nbsp": + u = 32; + break; + + case "quot": + u = 34; + break; + } + if (u > 0) + { + sb.Append((char)u); + pos1 = pos2 + 1; + } + else + sb.Append('&'); + } + } + else + { + sb.Append('&'); + } + } + + return sb.ToString(); + } + + private static string[] ESCAPES = new string[] { + "&", "&", + "<", "<", + ">", ">", + + "'", "'", + "\"", """, + "\t", " ", + "\n", " ", + "\r", " " + }; + public static void EncodeString(StringBuilder sb, int start, bool isAttribute = false) + { + int count; + int len = isAttribute ? ESCAPES.Length : 6; + for (int i = 0; i < len; i += 2) + { + count = sb.Length - start; + sb.Replace(ESCAPES[i], ESCAPES[i + 1], start, count); + } + } + + public static string EncodeString(string str, bool isAttribute = false) + { + if (string.IsNullOrEmpty(str)) + return ""; + else + { + StringBuilder sb = new StringBuilder(str); + EncodeString(sb, 0); + return sb.ToString(); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs.meta new file mode 100644 index 0000000..b5ea279 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/XMLUtils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11312ca9745d52c4eb8e31630ad5ec7c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs new file mode 100644 index 0000000..6d3cf62 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs @@ -0,0 +1,114 @@ +namespace FairyGUI.Utils +{ + /// + /// 一个简单的Zip文件处理类。不处理解压。 + /// + public class ZipReader + { + /// + /// + /// + public class ZipEntry + { + public string name; + public int compress; + public uint crc; + public int size; + public int sourceSize; + public int offset; + public bool isDirectory; + } + + ByteBuffer _stream; + int _entryCount; + int _pos; + int _index; + + /// + /// + /// + /// + public ZipReader(byte[] data) + { + _stream = new ByteBuffer(data); + _stream.littleEndian = true; + + int pos = _stream.length - 22; + _stream.position = pos + 10; + _entryCount = _stream.ReadShort(); + _stream.position = pos + 16; + _pos = _stream.ReadInt(); + } + + /// + /// + /// + public int entryCount + { + get { return _entryCount; } + } + + /// + /// + /// + /// + public bool GetNextEntry(ZipEntry entry) + { + if (_index >= _entryCount) + return false; + + _stream.position = _pos + 28; + int len = _stream.ReadUshort(); + int len2 = _stream.ReadUshort() + _stream.ReadUshort(); + + _stream.position = _pos + 46; + string name = _stream.ReadString(len); + name = name.Replace("\\", "/"); + + entry.name = name; + if (name[name.Length - 1] == '/') //directory + { + entry.isDirectory = true; + entry.compress = 0; + entry.crc = 0; + entry.size = entry.sourceSize = 0; + entry.offset = 0; + } + else + { + entry.isDirectory = false; + _stream.position = _pos + 10; + entry.compress = _stream.ReadUshort(); + _stream.position = _pos + 16; + entry.crc = _stream.ReadUint(); + entry.size = _stream.ReadInt(); + entry.sourceSize = _stream.ReadInt(); + _stream.position = _pos + 42; + entry.offset = _stream.ReadInt() + 30 + len; + } + + _pos += 46 + len + len2; + _index++; + + return true; + } + + + /// + /// + /// + /// + /// + public byte[] GetEntryData(ZipEntry entry) + { + byte[] data = new byte[entry.size]; + if (entry.size > 0) + { + _stream.position = entry.offset; + _stream.ReadBytes(data, 0, entry.size); + } + + return data; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs.meta new file mode 100644 index 0000000..099d314 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts/Utils/ZipReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8dc25ae9114bda14f998652db54f3af9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup.meta new file mode 100644 index 0000000..6a4cd8d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 71b78b3fa56670a4a9b19be0e30bc316 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs new file mode 100644 index 0000000..9054d99 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs @@ -0,0 +1,61 @@ +/* FairyGUI DLL模式脚本 + +using UnityEngine; + +namespace FairyGUI +{ +#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR + /// + /// 当使用DLL形式的插件时,因为DLL默认是为移动平台编译的,所以不支持复制粘贴。 + /// 将这个脚本放到工程里,并在游戏启动时调用CopyPastePatch.Apply(),可以在PC平台激活复制粘贴功能 + /// + public class CopyPastePatch + { + /// + /// + /// + public static void Apply() + { + InputTextField.onCopy = OnCopy; + InputTextField.onPaste = OnPaste; + } + + /// + /// + /// + /// + /// + public static void OnCopy(InputTextField textField, string value) + { + TextEditor te = new TextEditor(); +#if UNITY_5_3_OR_NEWER + te.text = value; +#else + te.content = new GUIContent(value); +#endif + te.OnFocus(); + te.Copy(); + } + + /// + /// + /// + /// + public static void OnPaste(InputTextField textField) + { + TextEditor te = new TextEditor(); + te.multiline = !textField.textField.singleLine; + te.Paste(); +#if UNITY_5_3_OR_NEWER + string value = te.text; +#else + string value = te.content.text; +#endif + if (!string.IsNullOrEmpty(value)) + textField.ReplaceSelection(value); + } + } +#endif +} + +*/ \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs.meta b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs.meta new file mode 100644 index 0000000..29c16ef --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/Scripts_Backup/CopyPastePatch_DLLModeBackup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b93c246a392b6f4da55f1bb0a871096 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/ver@master_4.3.0_2021.4.3.txt b/Assets/CrazyZoo/Plugins/FairyGUI/ver@master_4.3.0_2021.4.3.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/FairyGUI/ver@master_4.3.0_2021.4.3.txt.meta b/Assets/CrazyZoo/Plugins/FairyGUI/ver@master_4.3.0_2021.4.3.txt.meta new file mode 100644 index 0000000..8adafa3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/FairyGUI/ver@master_4.3.0_2021.4.3.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 594859e69b59ee54e8207258339a559d +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet.meta b/Assets/CrazyZoo/Plugins/JsonDotNet.meta new file mode 100644 index 0000000..ef74c67 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a86a2826351103e43b177f3659d6a35b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies.meta b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies.meta new file mode 100644 index 0000000..59ac16b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 577d9725f58264943855b8ac185531fe +folderAsset: yes +timeCreated: 1466788344 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb new file mode 100644 index 0000000..a02568a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb differ diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb.meta b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb.meta new file mode 100644 index 0000000..558a2cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/Assemblies/NewtonsoftDoc.Json.pdb.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 77d6bc548b327b44696511e5f4b6b5bb +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip b/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip new file mode 100644 index 0000000..23b699a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip differ diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip.meta b/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip.meta new file mode 100644 index 0000000..c846be6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/JsonDotNet201Source.zip.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9a6f8c7c1ea72ce46831c5e1b6150d0c +timeCreated: 1466790933 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml b/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml new file mode 100644 index 0000000..cf188f8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml.meta b/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml.meta new file mode 100644 index 0000000..1e0e273 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/link.xml.meta @@ -0,0 +1,6 @@ +fileFormatVersion: 2 +guid: 06314f49bdda26043963578d60a0a7ee +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/ver@2.0.1.txt b/Assets/CrazyZoo/Plugins/JsonDotNet/ver@2.0.1.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/JsonDotNet/ver@2.0.1.txt.meta b/Assets/CrazyZoo/Plugins/JsonDotNet/ver@2.0.1.txt.meta new file mode 100644 index 0000000..cc994a9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/JsonDotNet/ver@2.0.1.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5346f55835fe8064f9feb8181b5e0676 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/MiniJSON.meta b/Assets/CrazyZoo/Plugins/MiniJSON.meta new file mode 100644 index 0000000..663ce63 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/MiniJSON.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 54c97100689c425bb12203f4106a5598 +timeCreated: 1694663542 \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs b/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs new file mode 100644 index 0000000..0371eaa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs @@ -0,0 +1,549 @@ +/* + * Copyright (c) 2013 Calvin Rien + * + * Based on the JSON parser by Patrick van Bergen + * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html + * + * Simplified it so that it doesn't throw exceptions + * and can be used in Unity iPhone with maximum code stripping. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace MiniJSON { + // Example usage: + // + // using UnityEngine; + // using System.Collections; + // using System.Collections.Generic; + // using MiniJSON; + // + // public class MiniJSONTest : MonoBehaviour { + // void Start () { + // var jsonString = "{ \"array\": [1.44,2,3], " + + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + + // "\"int\": 65536, " + + // "\"float\": 3.1415926, " + + // "\"bool\": true, " + + // "\"null\": null }"; + // + // var dict = Json.Deserialize(jsonString) as Dictionary; + // + // Debug.Log("deserialized: " + dict.GetType()); + // Debug.Log("dict['array'][0]: " + ((List) dict["array"])[0]); + // Debug.Log("dict['string']: " + (string) dict["string"]); + // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles + // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs + // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); + // + // var str = Json.Serialize(dict); + // + // Debug.Log("serialized: " + str); + // } + // } + + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. + /// All numbers are parsed to doubles. + /// + public static class Json { + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false + public static object Deserialize(string json) { + // save the string for debug information + if (json == null) { + return null; + } + + return Parser.Parse(json); + } + + sealed class Parser : IDisposable { + const string WORD_BREAK = "{}[],:\""; + + public static bool IsWordBreak(char c) { + return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1; + } + + enum TOKEN { + NONE, + CURLY_OPEN, + CURLY_CLOSE, + SQUARED_OPEN, + SQUARED_CLOSE, + COLON, + COMMA, + STRING, + NUMBER, + TRUE, + FALSE, + NULL + }; + + StringReader json; + + Parser(string jsonString) { + json = new StringReader(jsonString); + } + + public static object Parse(string jsonString) { + using (var instance = new Parser(jsonString)) { + return instance.ParseValue(); + } + } + + public void Dispose() { + json.Dispose(); + json = null; + } + + Dictionary ParseObject() { + Dictionary table = new Dictionary(); + + // ditch opening brace + json.Read(); + + // { + while (true) { + switch (NextToken) { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.CURLY_CLOSE: + return table; + default: + // name + string name = ParseString(); + if (name == null) { + return null; + } + + // : + if (NextToken != TOKEN.COLON) { + return null; + } + // ditch the colon + json.Read(); + + // value + table[name] = ParseValue(); + break; + } + } + } + + List ParseArray() { + List array = new List(); + + // ditch opening bracket + json.Read(); + + // [ + var parsing = true; + while (parsing) { + TOKEN nextToken = NextToken; + + switch (nextToken) { + case TOKEN.NONE: + return null; + case TOKEN.COMMA: + continue; + case TOKEN.SQUARED_CLOSE: + parsing = false; + break; + default: + object value = ParseByToken(nextToken); + + array.Add(value); + break; + } + } + + return array; + } + + object ParseValue() { + TOKEN nextToken = NextToken; + return ParseByToken(nextToken); + } + + object ParseByToken(TOKEN token) { + switch (token) { + case TOKEN.STRING: + return ParseString(); + case TOKEN.NUMBER: + return ParseNumber(); + case TOKEN.CURLY_OPEN: + return ParseObject(); + case TOKEN.SQUARED_OPEN: + return ParseArray(); + case TOKEN.TRUE: + return true; + case TOKEN.FALSE: + return false; + case TOKEN.NULL: + return null; + default: + return null; + } + } + + string ParseString() { + StringBuilder s = new StringBuilder(); + char c; + + // ditch opening quote + json.Read(); + + bool parsing = true; + while (parsing) { + + if (json.Peek() == -1) { + parsing = false; + break; + } + + c = NextChar; + switch (c) { + case '"': + parsing = false; + break; + case '\\': + if (json.Peek() == -1) { + parsing = false; + break; + } + + c = NextChar; + switch (c) { + case '"': + case '\\': + case '/': + s.Append(c); + break; + case 'b': + s.Append('\b'); + break; + case 'f': + s.Append('\f'); + break; + case 'n': + s.Append('\n'); + break; + case 'r': + s.Append('\r'); + break; + case 't': + s.Append('\t'); + break; + case 'u': + var hex = new char[4]; + + for (int i=0; i< 4; i++) { + hex[i] = NextChar; + } + + s.Append((char) Convert.ToInt32(new string(hex), 16)); + break; + } + break; + default: + s.Append(c); + break; + } + } + + return s.ToString(); + } + + object ParseNumber() { + string number = NextWord; + + if (number.IndexOf('.') == -1 && number.IndexOf('E') == -1 && number.IndexOf('e') == -1) { + long parsedInt; + Int64.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedInt); + return parsedInt; + } + + double parsedDouble; + Double.TryParse(number, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble); + return parsedDouble; + } + + void EatWhitespace() { + while (Char.IsWhiteSpace(PeekChar)) { + json.Read(); + + if (json.Peek() == -1) { + break; + } + } + } + + char PeekChar { + get { + return Convert.ToChar(json.Peek()); + } + } + + char NextChar { + get { + return Convert.ToChar(json.Read()); + } + } + + string NextWord { + get { + StringBuilder word = new StringBuilder(); + + while (!IsWordBreak(PeekChar)) { + word.Append(NextChar); + + if (json.Peek() == -1) { + break; + } + } + + return word.ToString(); + } + } + + TOKEN NextToken { + get { + EatWhitespace(); + + if (json.Peek() == -1) { + return TOKEN.NONE; + } + + switch (PeekChar) { + case '{': + return TOKEN.CURLY_OPEN; + case '}': + json.Read(); + return TOKEN.CURLY_CLOSE; + case '[': + return TOKEN.SQUARED_OPEN; + case ']': + json.Read(); + return TOKEN.SQUARED_CLOSE; + case ',': + json.Read(); + return TOKEN.COMMA; + case '"': + return TOKEN.STRING; + case ':': + return TOKEN.COLON; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN.NUMBER; + } + + switch (NextWord) { + case "false": + return TOKEN.FALSE; + case "true": + return TOKEN.TRUE; + case "null": + return TOKEN.NULL; + } + + return TOKEN.NONE; + } + } + } + + /// + /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string + /// + /// A Dictionary<string, object> / List<object> + /// A JSON encoded string, or null if object 'json' is not serializable + public static string Serialize(object obj) { + return Serializer.Serialize(obj); + } + + sealed class Serializer { + StringBuilder builder; + + Serializer() { + builder = new StringBuilder(); + } + + public static string Serialize(object obj) { + var instance = new Serializer(); + + instance.SerializeValue(obj); + + return instance.builder.ToString(); + } + + void SerializeValue(object value) { + IList asList; + IDictionary asDict; + string asStr; + + if (value == null) { + builder.Append("null"); + } else if ((asStr = value as string) != null) { + SerializeString(asStr); + } else if (value is bool) { + builder.Append((bool) value ? "true" : "false"); + } else if ((asList = value as IList) != null) { + SerializeArray(asList); + } else if ((asDict = value as IDictionary) != null) { + SerializeObject(asDict); + } else if (value is char) { + SerializeString(new string((char) value, 1)); + } else { + SerializeOther(value); + } + } + + void SerializeObject(IDictionary obj) { + bool first = true; + + builder.Append('{'); + + foreach (object e in obj.Keys) { + if (!first) { + builder.Append(','); + } + + SerializeString(e.ToString()); + builder.Append(':'); + + SerializeValue(obj[e]); + + first = false; + } + + builder.Append('}'); + } + + void SerializeArray(IList anArray) { + builder.Append('['); + + bool first = true; + + for (int i=0; i= 32) && (codepoint <= 126)) { + builder.Append(c); + } else { + builder.Append("\\u"); + builder.Append(codepoint.ToString("x4")); + } + break; + } + } + + builder.Append('\"'); + } + + void SerializeOther(object value) { + // NOTE: decimals lose precision during serialization. + // They always have, I'm just letting you know. + // Previously floats and doubles lost precision too. + if (value is float) { + builder.Append(((float) value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } else if (value is int + || value is uint + || value is long + || value is sbyte + || value is byte + || value is short + || value is ushort + || value is ulong) { + builder.Append(value); + } else if (value is double + || value is decimal) { + builder.Append(Convert.ToDouble(value).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } else { + SerializeString(value.ToString()); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs.meta b/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs.meta new file mode 100644 index 0000000..de1b8bf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/MiniJSON/MiniJSON.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e9684183607428e4880bc6287f9ac3ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/MiniJSON/ver@1.0.0.txt b/Assets/CrazyZoo/Plugins/MiniJSON/ver@1.0.0.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/MiniJSON/ver@1.0.0.txt.meta b/Assets/CrazyZoo/Plugins/MiniJSON/ver@1.0.0.txt.meta new file mode 100644 index 0000000..d7fa389 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/MiniJSON/ver@1.0.0.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 21d25d3cc1761d446ab281bfd0e17cdb +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/SharpZipLib.meta b/Assets/CrazyZoo/Plugins/SharpZipLib.meta new file mode 100644 index 0000000..5e5b638 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/SharpZipLib.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ee8095cfd7813ed4aaff90a8683ddd68 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll b/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..fe643eb Binary files /dev/null and b/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll differ diff --git a/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll.meta b/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll.meta new file mode 100644 index 0000000..6ac228e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/SharpZipLib/ICSharpCode.SharpZipLib.dll.meta @@ -0,0 +1,34 @@ +fileFormatVersion: 2 +guid: 021594672e904984b8d48ffe5cfe4f07 +timeCreated: 1510113191 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + Any: + second: + enabled: 1 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/SharpZipLib/ver@1.0.0.txt b/Assets/CrazyZoo/Plugins/SharpZipLib/ver@1.0.0.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/SharpZipLib/ver@1.0.0.txt.meta b/Assets/CrazyZoo/Plugins/SharpZipLib/ver@1.0.0.txt.meta new file mode 100644 index 0000000..89f42fb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/SharpZipLib/ver@1.0.0.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 983137a6fe69b664a8601cf745b26b32 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine.meta b/Assets/CrazyZoo/Plugins/Spine.meta new file mode 100644 index 0000000..6abde9b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f38959fc3b3324d499aa8301b232a94d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md b/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md new file mode 100644 index 0000000..e2ce4d7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md @@ -0,0 +1,875 @@ +# 3.8 + +## AS3 +* **Breaking changes** + * Renamed `Slot#getAttachmentVertices()` to `Slot#getDeform()`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin#addAttachment()` to `Skin#setAttachment()`. + * Removed `VertexAttachment#applyDeform()` and replaced it with `VertexAttachment#deformAttachment`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + * Switched projects from FDT to Visual Studio Code. See updated `README.md` files for instructions. + +* **Additions** + * Added `SkeletonBinary` to load binary `.skel` files. See `MixAndMatchExample.as` in `spine-startling-example`. + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin#getAttachments()`. Returns all attachments in the skin. + * Added `Skin#getAttachments(int slotIndex)`. Returns all attachements in the skin for the given slot index. + * Added `Skin#addSkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin#copySkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * Added `Attachment#copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment#newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + +### Starling +* Added `MixAndMatchExample.as` to demonstrate the new Skin API additions and how to load binary `.skel` files. +* Switched projects from FDT to Visual Studio Code. See updated `README.md` files for instructions. + +## C +* **Breaking changes** + * Renamed `spSlot#attachmentVertices` to `spSlot#deform`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `spSkin_addAttachment()` to `Skin#spSkin_addAttachment()`. + * Removed `spVertexAttachment_applyDeform()` and replaced it with `VertexAttachment#deformAttachment`. The attachment set on this field is used to decide if a `spDeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `spMeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + +* **Additions** + * Added `x` and `y` coordinates for setup pose AABB in `spSkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `spSkin_getAttachments()`. Returns all attachments in the skin. + * Added `spSkin_getAttachments(int slotIndex)`. Returns all attachements in the skin for the given slot index. + * Added `spSkin_addSkin(spSkin* skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `spSkin_copySkin(spSkin* skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `spVertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * All attachments inserted into skins are reference counted. When the last skin referencing an attachment is disposed, the attachment will also be disposed. + * Added `spAttachment_copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `spMeshAttachment_newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + +### Cocos2d-Objc +* Added mix-and-match example to demonstrate the new Skin API. +* Added `IKExample`. +* Added `SkeletonAnimation preUpdateWorldTransformsListener` and `SkeletonAnimation postUpdateWorldTransformsListener`. When set, these callbacks will be invokved before and after the skeleton's `updateWorldTransforms()` method is called. See the `IKExample` how it can be used. + +### SFML +* Added mix-and-match example to demonstrate the new Skin API. +* Added `IKExample`. + +## C++ +* **Breaking Changes** + * Renamed `Slot::getAttachmentVertices()` to `Slot::getDeform()`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin::addAttachment()` to `Skin::setAttachment()`. + * Removed `VertexAttachment::applyDeform()` and replaced it with `VertexAttachment::getDeformAttachment()`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `_inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + +* **Additions** + * `AnimationState` and `TrackEntry` now also accept a subclass of `AnimationStateListenerObject` as a listener for animation events in the overloaded `setListener()` method. + * `SkeletonBinary` and `SkeletonJson` now parse and set all non-essential data like audio path. + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin#getAttachments()`. Returns all attachments in the skin. + * Added `Skin#getAttachments(int slotIndex)`. Returns all attachements in the skin for the given slot index. + * Added `Skin#addSkin(Skin &skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin#copySkin(Skin &skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * All attachments inserted into skins are reference counted. When the last skin referencing an attachment is disposed, the attachment will also be disposed. + * Added `Attachment#copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment#newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + * Exposed `x` and `y` on `SkeletonData` through getters and setters. + +### Cocos2d-x +* Updated to cocos2d-x 3.17.1 +* Added mix-and-match example to demonstrate the new Skin API. +* Exmaple project requires Visual Studio 2019 on Windows +* Added `IKExample`. +* Added `SkeletonAnimation::setPreUpdateWorldTransformsListener()` and `SkeletonAnimation::setPreUpdateWorldTransformsListener()`. When set, these callbacks will be invokved before and after the skeleton's `updateWorldTransforms()` method is called. See the `IKExample` how it can be used. + +### SFML +* Added mix-and-match example to demonstrate the new Skin API. + +### UE4 +* Added `bAutoPlaying` flag to `USpineSkeletonAnimationComponent`. When `false`, the component will not update the internal animation state and skeleton. +* Updated example project to UE 4.22. +* (Re-)Importing Spine assets will perform a version compatibility check and alert users about mismatches in editor mode. +* `USpineSkeletonRendererComponent` allows passing a `USpineSkeletonComponent` to update it. This way, the renderer component can be used without a skeleton component on the same actor. +* Added blueprint-callable methods to `SpineSkeletonComponent` and `SpineSkeletonAnimationComponent` to query and set skins, and enumerate bones, slots, and animations. +* Extended skeleton data editor preview. The preview now shows bones, slots, animations, and skins found in the skeleton data. See this [blog post](http://esotericsoftware.com/blog/Unreal-Engine-4-quality-of-life-improvements). +* Added preview animation and skin fields, allowing you to preview animations and skins right in the editor. See this [blog post](http://esotericsoftware.com/blog/Unreal-Engine-4-quality-of-life-improvements). +* Removed dependency on `RHI`, `RenderCore`, and `ShaderCore`. +* Re-importing atlases and their textures now works consistently in all situations. +* Added mix-and-match example to demonstrate the new Skin API. +* Materials on `SkeletonRendererComponent` are now blueprint read and writeable. This allows setting dynamic material instances at runtime + +## C# ## +* **Breaking changes** + * **Changed `IkConstraintData.Bones` type from `List` to `ExposedList`** for unification reasons. *Note: this modification will most likely not affect user code.* + * Renamed `Slot.AttachmentVertices` to `Slot.Deform`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin.AddAttachment()` to `Skin.SetAttachment()`. + * Removed `FindAttachmentsForSlot(int slotIndex, List attachments)` and `FindNamesForSlot (int slotIndex, List names)` and replaced it with `Skin.GetAttachments(int slotIndex, List attachments)` which returns the combined `SkinEntry` object holding both name and attachment. + * Removed `VertexAttachment.ApplyDeform()` and replaced it with `VertexAttachment.DeformAttachment`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + +* **Additions** + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin.GetAttachments()`. Returns all attachments in the skin. + * Added `Skin.GetAttachments(int slotIndex, List attachments)`. Returns all attachements in the skin for the given slot index. This method replaces `FindAttachmentsForSlot` and `FindNamesForSlot`. + * Added `Skin.AddSkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin.CopySkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * Added `Attachment.Copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment.NewLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + +### Unity + +* **Breaking changes** + * **Officially supported Unity versions are 2017.1-2019.2**. + * **Spine `.asmdef` files are again active by default**. They have previously been deactivated to `.txt` extension which is now no longer necessary. + * **Removed PoseSkeleton() and PoseWithAnimation()** extension methods to prevent issues where animations are not mixed out. Problem was that these methods did not set AnimationState, leaving incorrect state at e.g. attachments enabled at slots when starting subsequent animations. As a replacement you can use `AnimationState.ClearTrack(0);` followed by `var entry = AnimationState.SetAnimation(0, animation, loop); entry.TrackTime = time` to achieve similar behaviour. + * **The `Shadow alpha cutoff` shader parameter is now respecting slot-color alpha** values at all Spine shaders. A fragment's texture color alpha is multiplied with slot-color alpha before the result is tested against the `Shadow alpha cutoff` threshold. + * **Removed redundant `Attachment.GetClone()` and `MeshAttachment.GetLinkedClone()` extension methods**. Use methods `Attachment.Copy` and `MeshAttachment.NewLinkedMesh()` instead. + * **Renamed extension method `Attachment.GetClone(bool cloneMeshesAsLinked)` to `Attachment.GetCopy(bool cloneMeshesAsLinked)`** to follow the naming scheme of the Spine API. + * `SkeletonDataAsset.atlasAssets` is now an array of the base class `AtlasAssetBase` instead of `SpineAtlasAsset`, which provides `IEnumerable<> Materials` instead of `List<> materials`. Replace any access via `atlasAsset.materials[0]` with `atlasAsset.Materials.First()` and add a `using System.Linq;` statement. + * **Changed `MeshAttachment.GetLinkedMesh()` method signatures:** removed optional parameters `bool inheritDeform = true, bool copyOriginalProperties = false`. + * Changed namespace `Spine.Unity.Modules` to `Spine.Unity` and `Spine.Unity.Examples` after restructuring (see section below) in respective classes: + * When receiving namespace related errors, replace using statements of `using Spine.Unity.Modules.AttachmentTools;` with `using Spine.Unity.AttachmentTools;`. You can remove `using Spine.Unity.Modules;` statements when a `using Spine.Unity` statement is already present in the file. + * `AttachmentTools`, `SkeletonPartsRenderer`, `SkeletonRenderSeparator`, `SkeletonRendererCustomMaterials` changed to namespace `Spine.Unity`. + * `SkeletonGhost`, `SkeletonGhostRenderer`, `AtlasRegionAttacher`, `SkeletonGraphicMirror`, `SkeletonRagdoll`, `SkeletonRagdoll2D`, `SkeletonUtilityEyeConstraint`, `SkeletonUtilityGroundConstraint`, `SkeletonUtilityKinematicShadow` changed to namespace `Spine.Unity.Examples`. + * Split `Editor/Utility/SpineEditorUtilities` class into multiple files with partial class qualifier. + * Nested classes `SpineEditorUtilities.AssetUtility` and `SpineEditorUtilities.EditorInstantiation` are now no longer nested. If you receive namespace related errors, replace any occurrance of + * `SpineEditorUtilities.AssetUtility` with `AssetUtility` and + * `SpineEditorUtilities.EditorInstantiation` with `EditorInstantiation`. + * **Timeline Support has been moved to a separate UPM Package** Previously the Spine Timeline integration was located in the `Modules/Timeline` directory and was deactivated by default, making it necessary to activate it via the Spine Preferences. Now the Timeline integration has been moved to an additional UPM package which can be found under `Modules/com.esotericsoftware.spine.timeline`. + * **Installation:** You can download the Unity Package Manager (UPM) package via the [download page](http://esotericsoftware.com/spine-unity-download) or find it in the [spine-runtimes/spine-unity/Modules](https://github.com/EsotericSoftware/spine-runtimes/tree/3.8-beta/spine-unity/Modules) subdirectory on the git repository. You can then either unzip (copy if using git) the package to + a) the `Packages` directory in your project where it will automatically be loaded, or + b) to an arbitrary directory outside the Assets directory and then open Package Manager in Unity, select the `+` icon, choose `Add package from disk..` and point it to the package.json file. + The Project panel should now show an entry `Spine Timeline Extensions` under `Packages`. If the directory is not yet listed, you will need to close and re-open Unity to have it display the directory and its contents. + * `SkeletonMecanim`'s `Layer Mix Mode` enum name `MixMode.SpineStyle` has been renamed to `MixMode.Hard`. This is most likely not set via code and thus unlikely to be a problem. Serialized scenes and prefabs are unaffected. + +* **Additions** + * **Spine Preferences stored in Assets/Editor/SpineSettings.asset** Now Spine uses the new `SettingsProvider` API, storing settings in a SpineSettings.asset file which can be shared with team members. Your old preferences are automatically migrated to the new system. + * Added support for Unity's SpriteMask to `SkeletonAnimation` and `SkeletonMecanim`. All mask interaction modes are supported. See this [blog post](http://esotericsoftware.com/blog/Unity-SpriteMask-and-RectMask2D-support). + * Added support for Unity's RectMask2D to SkeletonGraphics. See this [blog post](http://esotericsoftware.com/blog/Unity-SpriteMask-and-RectMask2D-support). + * Added `Create 2D Hinge Chain` button at `SkeletonUtilityBone` inspector, previously only `Create 3D Hinge Chain` was available. + * **Now supporting Lightweight Render Pipeline (LWRP) through an additional UPM package.** + * **Installation:** You can download the Unity Package Manager (UPM) package via the [download page](http://esotericsoftware.com/spine-unity-download) or find it in the [spine-runtimes/spine-unity/Modules](https://github.com/EsotericSoftware/spine-runtimes/tree/3.8-beta/spine-unity/Modules) subdirectory on the git repository. You can then either unzip (copy if using git) the package to + * a) the `Packages` directory in your project where it will automatically be loaded, or + * b) to an arbitrary directory outside the Assets directory and then open Package Manager in Unity, select the `+` icon, choose `Add package from disk..` and point it to the package.json file. + + > If you are using git and Unity 2019.2 or newer versions and receive an error that dependencies could not be resolved by the package manager (only higher versions of Unity's `Lightweight RP` package are available, e.g. `6.9.0` and up), please copy the prepared package-UNITYVERSION.json file for your Unity version (e.g. `package-2019.2.json`) over the existing package.json file to change the dependency accordingly. Unfortunately Unity's Package Manager does not provide a way to specify a version range for a dependency like "5.7.2 - 6.9.0" yet, so this manual step is necessary for git users. + + The Project panel should now show an entry `Spine Lightweight RP Shaders` under `Packages`. If the directory is not yet listed, you will need to close and re-open Unity to have it display the directory and its contents. + * **Usage:** The package provides two shaders specifically built for the lightweight render pipeline: + * `Lightweight Render Pipeline/Spine/Skeleton`, as a lightweight variant of the `Spine/Skeleton` shader, + * `Lightweight Render Pipeline/Spine/Skeleton Lit`, as a lightweight variant of the `Spine/Skeleton Lit` shader and + * `Lightweight Render Pipeline/Spine/Sprite`, as a lightweight variant of the `Spine/Sprite/Vertex Lit` and `Pixel Lit` shaders, which were not functioning in the lightweight render pipeline. The shaders can be assigned to materials as usual and will respect your settings of the assigned `LightweightRenderPipelineAsset` under `Project Settings - Graphics`. + * **Restrictions** As all Spine shaders, the LWRP shaders **do not support `Premultiply alpha` (PMA) atlas textures in Linear color space**. Please export your atlas textures as `straight alpha` textures with disabled `Premultiply alpha` setting when using Linear color space. You can check the current color space via `Project Settings - Player - Other Settings - Color Space.`. + * **Example:** You can find an example scene in the package under `com.esotericsoftware.spine.lwrp-shaders-3.8/Examples/LWRP Shaders.unity` that demonstrates usage of the LWRP shaders. + * Added `Spine/Skeleton Lit ZWrite` shader. This variant of the `Spine/Skeleton Lit` shader writes to the depth buffer with configurable depth alpha threshold. Apart from that it is identical to `Spine/Skeleton Lit`. + * Additional yield instructions to wait for animation track events `End`, `Complete` and `Interrupt`. + * `WaitForSpineAnimationComplete` now proves an additional `bool includeEndEvent` parameter, defaults to `false` (previous behaviour). + * Added a new `WaitForSpineAnimationEnd` yield instruction. + * Added a new generic `WaitForSpineAnimation` yield instruction which can be configured to wait for any combination of animation track events. It is now used as base class for `WaitForSpineAnimationComplete` and `WaitForSpineAnimationEnd`. + * Additional **Fix Draw Order** parameter at SkeletonRenderer, defaults to `disabled` (previous behaviour). + Applies only when 3+ submeshes are used (2+ materials with alternating order, e.g. "A B A"). + If true, MaterialPropertyBlocks are assigned at each material to prevent aggressive batching of submeshes + by e.g. the LWRP renderer, leading to incorrect draw order (e.g. "A1 B A2" changed to "A1A2 B"). + You can leave this parameter disabled when everything is drawn correctly to save the additional performance cost. + * **Additional Timeline features.** SpineAnimationStateClip now provides a `Speed Multiplier`, a start time offset parameter `Clip In`, support for blending successive animations by overlapping tracks. An additional `Use Blend Duration` parameter *(defaults to true)* allows for automatic synchronisation of MixDuration with the current overlap blend duration. An additional Spine preferences parameter `Use Blend Duration` has been added which can be disabled to default to the previous behaviour before this update. + * Additional `SpriteMask and RectMask2D` example scene added for demonstration of mask setup and interaction. + * `Real physics hinge chains` for both 2D and 3D physics. The [SkeletonUtilityBone](http://esotericsoftware.com/spine-unity#SkeletonUtilityBone) Inspector provides an interface to create 2D and 3D hinge chains. Previously created chains have only been respecting gravity, but not momentum of the skeleton or parent bones. The new physics rig created when pressing `Create 3D Hinge Chain` and `Create 2D Hinge Chain` creates a more complex setup that also works when flipping the skeleton. Note that the chain root node is no longer parented to bones of the skeleton. This is a requirement in Unity to have momentum applied properly - do not reparent the chain root to bones of your skeleton, or you will loose any momentum applied by the skeleton's movement. + * `Outline rendering functionality for all shaders.` Every shader now provides an additional set of `Outline` parameters to enable custom outline rendering. When outline rendering is enabled via the `Material` inspector, it automatically switches the shader to the respective `Spine/Outline` shader variant. Outlines are generated by sampling neighbour pixels, so be sure to add enough transparent padding when exporting your atlas textures to fit the desired outline width. In order to enable outline rendering at a skeleton, it is recommended to first prepare an additional outline material copy and then switch the material of the target skeleton to this material. This prevents unnecessary additional runtime material copies and drawcalls. Material switching can be prepared via a [SkeletonRendererCustomMaterials](http://esotericsoftware.com/spine-unity#SkeletonRendererCustomMaterials) component and then enabled or disabled at runtime. Alternatively, you can also directly modify the `SkeletonRenderer.CustomMaterialOverride` property. + Outline rendering is fully supported on `SkeletonGraphic` shaders as well. + * Added `SkeletonRenderer.EditorSkipSkinSync` scripting API property to be able to set custom skins in editor scripts. Enable this property when overwriting the Skeleton's skin from an editor script. Without setting this parameter, changes will be overwritten by the next inspector update. Only affects Inspector synchronisation of skin with `initialSkinName`, not startup initialization. + * All `Spine/SkeletonGraphic` shaders now provide a parameter `CanvasGroup Compatible` which can be enabled to support `CanvasGroup` alpha blending. For correct results, you should then disable `Pma Vertex Colors` in the `SkeletonGraphic` Inspector, in section `Advanced` (otherwise Slot alpha will be applied twice). + * **Now supporting Universal Render Pipeline (URP), including the 2D Renderer pipeline, through an additional UPM package.** + * **Installation:** You can download the Unity Package Manager (UPM) package via the [download page](http://esotericsoftware.com/spine-unity-download) or find it in the [spine-runtimes/spine-unity/Modules](https://github.com/EsotericSoftware/spine-runtimes/tree/3.8-beta/spine-unity/Modules) subdirectory on the git repository. You can then either unzip (copy if using git) the package to + * a) the `Packages` directory in your project where it will automatically be loaded, or + * b) to an arbitrary directory outside the Assets directory and then open Package Manager in Unity, select the `+` icon, choose `Add package from disk..` and point it to the package.json file. + + The Project panel should now show an entry `Spine Universal RP Shaders` under `Packages`. If the directory is not yet listed, you will need to close and re-open Unity to have it display the directory and its contents. + * **Usage:** The package provides two shaders specifically built for the universal render pipeline: + * `Universal Render Pipeline/Spine/Skeleton`, as a universal variant of the `Spine/Skeleton` shader, + * `Universal Render Pipeline/Spine/Skeleton Lit`, as a universal variant of the `Spine/Skeleton Lit` shader, + * `Universal Render Pipeline/Spine/Sprite`, as a universal variant of the `Spine/Sprite/Vertex Lit` and `Pixel Lit` shaders, which were not functioning in the universal render pipeline, + * `Universal Render Pipeline/2D/Spine/Skeleton Lit`, as a universal 2D Renderer variant of the `Spine/Skeleton Lit` shader, and + * `Universal Render Pipeline/2D/Spine/Sprite`, as a universal 2D Renderer variant of the `Spine/Sprite/Vertex Lit` and `Pixel Lit` shaders. + The shaders can be assigned to materials as usual and will respect your settings of the assigned `UniversalRenderPipelineAsset` under `Project Settings - Graphics`. + * **Restrictions** As all Spine shaders, the URP shaders **do not support `Premultiply alpha` (PMA) atlas textures in Linear color space**. Please export your atlas textures as `straight alpha` textures with disabled `Premultiply alpha` setting when using Linear color space. You can check the current color space via `Project Settings - Player - Other Settings - Color Space.`. + * **Example:** You can find an example scene in the package under `com.esotericsoftware.spine.urp-shaders-3.8/Examples/URP Shaders.unity` that demonstrates usage of the URP shaders. + * Spine Preferences now provide an **`Atlas Texture Settings`** parameter for applying customizable texture import settings at all newly imported Spine atlas textures. + When exporting atlas textures from Spine with `Premultiply alpha` enabled (the default), you can leave it at `PMATexturePreset`. If you have disabled `Premultiply alpha`, set it to the included `StraightAlphaTexturePreset` asset. You can also create your own `TextureImporter` `Preset` asset and assign it here (include `PMA` or `Straight` in the name). In Unity versions before 2018.3 you can use `Texture2D` template assets instead of the newer `Preset` assets. Materials created for imported textures will also have the `Straight Alpha Texture` parameter configured accordingly. + +* **Changes of default values** + * `SkeletonMecanim`'s `Layer Mix Mode` now defaults to `MixMode.MixNext` instead of `MixMode.MixAlways`. + * `BlendModeMaterialAsset` and it's instance `Default BlendModeMaterials.asset` now have `Apply Additive Material` set to `true` by default in order to apply all blend modes by default. + +* **Deprecated** + * Deprecated `Modules/SlotBlendModes/SlotBlendModes` component. Changed namespace from `Spine.Unity.Modules` to `Spine.Unity.Deprecated`. Moved to `Deprecated/SlotBlendModes`. + +* **Restructuring (Non-Breaking)** + + Note: The following changes will most likely not affect users of the Spine-Unity runtime as the API remains unchanged and no references are invalidated. + * Removed duplicates of `.cginc` files in `Modules/Shaders/Sprite` that were also present in the `Modules/Shaders/Sprite/CGIncludes` directory. + * Moved shaders from `Modules/Shaders` to `Shaders` directory. + * Moved shaders from `Modules/SkeletonGraphic/Shaders` to `Shaders/SkeletonGraphic`. + * Renamed shader `Shaders/Spine-SkeletonLit.shader` to `Shaders/Spine-Skeleton-Lit.shader`. + * Moved components from `SkeletonGraphic` to `Components` and `Components/Following` except for `SkeletonGraphicMirror` which was moved to `Spine Examples/Scripts/Sample Components`. + * Moved `BoneFollower`, `BoneFollowerGraphic` and `PointFollower` from `Components` directory to `Components/Following`. + * Moved `BoundingBoxFollower` component from `Modules/BoundingBoxFollower` to `Components/Following`. + * Moved `Modules/SkeletonRenderSeparator` directory to `Components/SkeletonRenderSeparator`. + * Moved `Modules/CustomMaterials` directory to `Components/SkeletonRendererCustomMaterials`. + * Moved `Asset Types/BlendModeMaterialsAsset.cs` class, `Shaders/BlendModes/Default BlendModeMaterials.asset` and materials from `Shaders/BlendModes` to `SkeletonDataModifierAssets/BlendModeMaterials` directory. + * Moved `Modules/Ghost` directory to `Spine Examples/Scripts/Sample Components/Ghost`. + * Moved `Modules/SkeletonUtility Modules` directory to `Spine Examples/Scripts/Sample Components/SkeletonUtility Modules`. + * Moved `Modules/AnimationMatchModifier` directory to `Spine Examples/Scripts/MecanimAnimationMatchModifier`. + * Moved `SkeletonRagdoll` and `SkeletonRagdoll2D` components from `Modules/Ragdoll` directory to `Spine Examples/Scripts/Sample Components/SkeletonUtility Modules`. + * Moved `AttachmentTools.cs` to `Utility` directory. + * Split the file `AttachmentTools` into 5 separate files for each contained class. No namespace or other API changes performed. + * Split the file `Mesh Generation/SpineMesh` into 4 separate files for each contained class. No namespace or other API changes performed. + * Moved `SkeletonExtensions.cs` to `Utility` directory. + * Moved `Modules/YieldInstructions` directory to `Utility/YieldInstructions`. + * Moved corresponding editor scripts of the above components to restructured directories as well. + * Renamed inspector editor class `PointFollowerEditor` to `PointFollowerInspector` for consistency reasons. + +### XNA/MonoGame +* Updated to latest MonoGame version 3.7.1 +* Rewrote example project to be cleaner and better demonstrate basic Spine features. +* Added mix-and-match example to demonstrate the new Skin API. + +## Java +* **Breaking changes** + * Renamed `Slot#getAttachmentVertices()` to `Slot#getDeform()`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin#addAttachment()` to `Skin#setAttachment()`. + * Removed `VertexAttachment#applyDeform()` and replaced it with `VertexAttachment#deformAttachment`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * `JsonRollback` tool now converts from 3.8 JSON to 3.7. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + +* **Additions** + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin#getAttachments()`. Returns all attachments in the skin. + * Added `Skin#getAttachments(int slotIndex)`. Returns all attachements in the skin for the given slot index. + * Added `Skin#addSkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin#copySkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * Added `Attachment#copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment#newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + +### libGDX +* `SkeletonViewer` can load a skeleton by specifying it as the first argument on the command line. +* Added mix-and-match example to demonstrate the new Skin API. + +## Lua +* **Breaking changes** + * Renamed `Slot:getAttachmentVertices()` to `Slot#deform`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin:addAttachment()` to `Skin#setAttachment()`. + * Removed `VertexAttachment:applyDeform()` and replaced it with `VertexAttachment#deformAttachment`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed the `.json` file format to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + +* **Additions** + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin:getAttachments()`. Returns all attachments in the skin. + * Added `Skin:getAttachments(slotIndex)`. Returns all attachements in the skin for the given slot index. + * Added `Skin:addSkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin:copySkin(Skin skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * Added `Attachment:copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment:newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + +### Love2D +* Added support for 0-1 RGBA color component range change in Löve 0.11+. Older Löve versions using the 0-255 range are still supported! +* Added mix-and-match example to demonstrate the new Skin API. + +### Corona +* Added mix-and-match example to demonstrate the new Skin API. + +## Typescript/Javascript +* **Breaking changes** + * Renamed `MixDirection.in/out` to `MixDirection.mixIn/mixOut` as it was crashing a JS compressor. + * Renamed `Slot#getAttachmentVertices()` to `Slot#getDeform()`. + * Changed the `.json` curve format and added more assumptions for omitted values, reducing the average size of JSON exports. + * Renamed `Skin#addAttachment()` to `Skin#setAttachment()`. + * Removed `VertexAttachment#applyDeform()` and replaced it with `VertexAttachment#deformAttachment`. The attachment set on this field is used to decide if a `DeformTimeline` should be applied to the attachment active on the slot to which the timeline is applied. + * Removed `inheritDeform` field, getter, and setter from `MeshAttachment`. + * Changed `.skel` binary format, added a string table. References to strings in the data resolve to this string table, reducing storage size of binary files considerably. + * Changed the `.json` and `.skel` file formats to accomodate the new feature and file size optimiations. Old projects must be exported with Spine 3.8.20+ to be compatible with the 3.8 Spine runtimes. + * Updated runtime to be compatible with TypeScript 3.6.3. + +* **Additions** + * Added support for loading binary data via `AssetManager#loadBinary()`. `AssetManager#get()` will return a `Uint8Array` for such assets. + * Added support for loading binaries via new `SkeletonBinary`. Parses a `Uint8Array`. + * Added `x` and `y` coordinates for setup pose AABB in `SkeletonData`. + * Added support for rotated mesh region UVs. + * Added skin-specific bones and constraints which are only updated if the skeleton's current skin contains them. + * Improved Skin API to make it easier to handle mix-and-match use cases. + * Added `Skin#getAttachments()`. Returns all attachments in the skin. + * Added `Skin#getAttachments(slotIndex: number)`. Returns all attachements in the skin for the given slot index. + * Added `Skin#addSkin(skin: Skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. + * Added `Skin#copySkin(skin: Skin)`. Adds all attachments, bones, and skins from the specified skin to this skin. `VertexAttachment` are shallowly copied and will retain any parent mesh relationship. All other attachment types are deep copied. + * Added `Attachment#copy()` to all attachment type implementations. This lets you deep copy an attachment to modify it independently from the original, i.e. when programmatically changing texture coordinates or mesh vertices. + * Added `MeshAttachment#newLinkedMesh()`, creates a linked mesh linkted to either the original mesh, or the parent of the original mesh. + * Added IK softness. + * Added `AssetManager.setRawDataURI(path, data)`. Allows to embed data URIs for skeletons, atlases and atlas page images directly in the HTML/JS without needing to load it from a separate file. + +### WebGL backend +* `Input` can now take a partially defined implementation of `InputListener`. +* Added mix-and-match example to demonstrate the new Skin API. + +### Canvas backend + +### Three.js backend +* `SkeletonMesh` now takes an optional `SkeletonMeshMaterialParametersCustomizer` function that allows you to modify the `ShaderMaterialParameters` before the material is finalized. Use it to modify things like THREEJS' `Material.depthTest` etc. See #1590. + +### Player +* `SpinePlayer#setAnimation()` can now be called directly to set the animation being displayed. +* The player supports loading `.skel` binary skeleton files by setting the `SpinePlayerConfig#skelUrl` field instead of `SpinePlayerConfig#jsonUrl`. +* Added `SpinePlayerConfig#rawDataURIs`. Allows to embed data URIs for skeletons, atlases and atlas page images directly in the HTML/JS without needing to load it from a separate file. See the example for a demonstration. + +# 3.7 + +## AS3 +* **Breaking changes** + * The completion event will fire for looped 0 duration animations every frame. + * `MixPose` is now called `MixBlend` + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 +* **Additions** + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `TrackEntry#setMixBlend(MixBlend.add)` on each track. To specify the blend percentage, set `TrackEntry#alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `TrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + +### Starling +* Added support for vertex effects. See `RaptorExample.as` +* Added 'getTexture()' method to 'StarlingTextureAtlasAttachmentLoader' +* Breaking change: if a skeleton requires two color tinting, you have to enable it via `SkeletonSprite.twoColorTint = true`. In this case the skeleton will use the `TwoColorMeshStyle`, which internally uses a different vertex layout and shader. This means that skeletons with two color tinting enabled will break batching and hence increase the number of draw calls in your app. +* Added `VertexEffect` and implementations `JitterEffect` and `SwirlEffect`. Allows you to modify vertices before they are submitted for drawing. See Starling changes. +* Fix issues with StarlingAtlasAttachmentLoader, see https://github.com/EsotericSoftware/spine-runtimes/issues/939 +* Fix issues with region trimming support, see https://github.com/EsotericSoftware/spine-runtimes/commit/262bc26c64d4111002d80e201cb1a3345e6727df +* Added support for overriding `StarlingAtlasAttachmentLoader#getTexture()`, see https://github.com/EsotericSoftware/spine-runtimes/commit/ea7dbecb98edc74e439aa9ef90dcf6eed865f718 +* Texture atlas operations are no longer handled in `Starling#newRegionAttachment` and `Starling#newMeshAttachment` but delegated to the atlas. +* Added sample for additive animation blending, see https://github.com/EsotericSoftware/spine-runtimes/blob/6a556de01429878df47bb276a97959a8bdbbe32f/spine-starling/spine-starling-example/src/spine/examples/OwlExample.as +* Added sample on how to use bounding box attachment vertices https://github.com/EsotericSoftware/spine-runtimes/commit/e20428b02699226164fa73ba4b12f7d029ae6f4d +* Fully transparent meshes are not submitted for rendering. +* No hit-tests are performed when a skeleton is invisible. + +## C +* **Breaking changes** + * Listeners on `spAnimationState` and `spTrackEntry` will now also be called if a track entry gets disposed as part of disposing an animation state. + * The completion event will fire for looped 0 duration animations every frame. + * The spine-cocos2dx and spine-ue4 runtimes are now based on spine-cpp. See below for changes. + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 + * `spMeshAttachment` has two new fields `regionTextureWith` and `regionTextureHeight`. These must be set in custom attachment loader. See `AtlasAttachmentLoader`. +* **Additions** + * Added support for local and relative transform constraint calculation, including additional fields in `spTransformConstraintData`. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + * Added `spVertexEffect` and corresponding implementations `spJitterVertexEffect` and `spSwirlVertexEffect`. Create/dispose through the corresponding `spXXXVertexEffect_create()/dispose()` functions. Set on framework/engine specific renderer. + * Functions in `extension.h` are not prefixed with `_sp` instead of just `_` to avoid interference with other libraries. + * Introduced `SP_API` macro. Every spine-c function is prefixed with this macro. By default, it is an empty string. Can be used to markup spine-c functions with e.g. ``__declspec` when compiling to a dll or linking to that dll. + * Added `void *userData` to `spAnimationState`to be consumed in callbacks. + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `spTrackEntry->mixBlend = SP_MIXBLEND_ADD)` on each track. To specify the blend percentage, set `spTrackEntry->alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. + * Optimized attachment lookup to give a 40x speed-up. See https://github.com/EsotericSoftware/spine-runtimes/commit/cab81276263890b65d07fa2329ace16db1e365ff + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `spTrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + +### Cocos2d-Objc +* Added vertex effect support to modify vertices of skeletons on the CPU. See `RaptorExample.m`. +* Explanation how to handle ARC, see https://github.com/EsotericSoftware/spine-runtimes/commit/a4f122b08c5e2a51d6aad6fc5a947f7ec31f2eb8 +* The super class `::update()` method of `SkeletonRenderer` is now called, see https://github.com/EsotericSoftware/spine-runtimes/commit/f7bb98185236a6d8f35bfefc70afe4f31e9ec9d2 +* Added improved tint-black shader. + +### SFML +* `spine-sfml.h` no longer defines `SPINE_SHORT_NAMES` to avoid collisions with other APIs. See #1058. +* Added support for vertex effects. See raptor example. +* Added premultiplied alpha support to `SkeletonDrawable`. Use `SkeletonDrawable::setUsePremultipliedAlpha()`, see https://github.com/EsotericSoftware/spine-runtimes/commit/34086c1f41415309b2ecce86055f6656fcba2950 +* Added additive animation blending sample, see https://github.com/EsotericSoftware/spine-runtimes/blob/b7e712d3ca1d6be3ebcfe3254dc2cea9c44dda71/spine-sfml/example/main.cpp#L369 + +## C++ +* ** Additions ** + * Added C++ Spine runtime. See the [spine-cpp Runtime Guide](https://esotericsoftware.com/spine-cpp) for more information on spine-cpp. + * Added parsing of non-essential data (fps, images path, audio path) to for `.json`/`.skel` parsers. + +### Cocos2d-x +* Added ETC1 alpha support, thanks @halx99! Does not work when two color tint is enabled. +* Added `spAtlasPage_setCustomTextureLoader()` which let's you do texture loading manually. Thanks @jareguo. +* Added `SkeletonRenderer:setSlotsRange()` and `SkeletonRenderer::createWithSkeleton()`. This allows you to split rendering of a skeleton up into multiple parts, and render other nodes in between. See `SkeletonRendererSeparatorExample.cpp` for an example. +* Fully transparent attachments will not be rendered, improving rendering performance. +* Added improved tint-black shader. +* Updated to cocos2d-x 3.16 +* The skeleton setup pose and world transform are now calculated on initialization to avoid flickering on start-up. +* Updated to cocos2d-x 3.17.1 +* **Breaking change**: Switched from [spine-c](spine-c) to [spine-cpp](spine-cpp) as the underlying Spine runtime. See the [spine-cpp Runtime Guide](https://esotericsoftware.com/spine-cpp) for more information on spine-cpp. + * Added `Cocos2dAttachmentLoader` to be used when constructing an `Atlas`. Used by default by `SkeletonAnimation` and `SkeletonRenderer` when creating instances via the `createXXX` methods. + * All C structs and enums `spXXX` have been replaced with their C++ equivalents `spine::XXX` in all public interfaces. + * All instantiations via `new` of C++ classes from spine-cpp should contain `(__FILE__, __LINE__)`. This allows the tracking of instantations and detection of memory leaks via the `spine::DebugExtension`. + +### SFML +* Create a second SFML backend using [spine-cpp](spine-cpp/). See the [spine-cpp Runtime Guide](https://esotericsoftware.com/spine-cpp) for more information on spine-cpp. +* Added support for vertex effects. See raptor example. +* Added premultiplied alpha support to `SkeletonDrawable`. Use `SkeletonDrawable::setUsePremultipliedAlpha()`, see https://github.com/EsotericSoftware/spine-runtimes/commit/34086c1f41415309b2ecce86055f6656fcba2950 +* Added additive animation blending sample, see https://github.com/EsotericSoftware/spine-runtimes/blob/b7e712d3ca1d6be3ebcfe3254dc2cea9c44dda71/spine-sfml/example/main.cpp#L369 + +### UE4 + * spine-c is now exposed from the plugin shared library on Windows via __declspec. + * Updated to Unreal Engine 4.18 + * Added C++ example, see https://github.com/EsotericSoftware/spine-runtimes/commit/15011e81b7061495dba45e28b4d3f4efb10d7f40 + * `SkeletonRendererComponent` generates collision meshes by default. + * Disabled generation of collision meshes by `SkeletonRendererComponent`. Both `ProceduralMeshComponent` and `RuntimeMeshComponent` have a bug that generates a new PhysiX file every frame per component. Users are advised to add a separate collision shape to the root scene component of an actor instead. + * Using UE4 `FMemory` allocator by default. This should fix issues on some consoles. + * **Breaking change** moved away from `RuntimeMeshComponent`, as its maintainance has seized, back to `ProceduralMeshComponent`. Existing projects should just work. However, if you run into issues, you may have to remove the old `SpineSkeletonRendererComponent` and add a new one to your existing actors. + * **Breaking change** due to the removal of `RuntimeMeshComponent` and reversal to `ProceduralMeshComponent`, two color tinting is currently not supported. `ProceduralMeshComponent` does not support enough vertex attributes for us to encode the second color in the vertex stream. You can remove the `RuntimeMeshComponent/` directory from your plugins directory and remove the component from any `build.cs` files that may reference it. + * **Breaking change**: Switched from [spine-c](spine-c) to [spine-cpp](spine-cpp) as the underlying Spine runtime. See the [spine-cpp Runtime Guide](https://esotericsoftware.com/spine-cpp) for more information on spine-cpp. + * All C structs and enums `spXXX` have been replaced with their C++ equivalents `spine::XXX` in all public interfaces. + * All instantiations via `new` of C++ classes from spine-cpp should contain `(__FILE__, __LINE__)`. This allows the tracking of instantations and detection of memory leaks via the `spine::DebugExtension`. +* Updated to Unreal Engine 4.20 (samples require 4.17+), see the `spine-ue4/Plugins/SpinePlugin/Source/SpinePlugin/SpinePlugin.build.cs` file on how to compile in 4.20 with the latest UBT API changes. +* Updated to Unreal Engine 4.21 (samples require 4.21). +* **Breaking change**: `UBoneDriverComponent` and `UBoneFollowerComponent` are now `USceneComponent` instead of `UActorComponent`. They either update only themselves, or also the owning `UActor`, depending on whether the new flag `UseComponentTransform` is set. See https://github.com/EsotericSoftware/spine-runtimes/pull/1175 +* Added query methods for slots, bones, skins and animations to `SpineSkeletonComponent` and `UTrackEntry`. These allow you to query these objects by name in both C++ and blueprints. +* Added `Preview Animation` and `Preview Skin` properties to `SpineSkeletonAnimationComponent`. Enter an animation or skin name to live-preview it in the editor. Enter an empty string to reset the animation or skin. + +## C# ## +* **Breaking changes** + * The completion event will fire for looped 0 duration animations every frame. + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 +* **Additions** + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `TrackEntry#MixBlend = MixBlend.add` on each track. To specify the blend percentage, set `TrackEntry#Alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `TrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + +### Unity +* **Runtime and Editor, and Assembly Definition** Files and folders have been reorganized into "Runtime" and "Editor". Each of these have an `.asmdef` file that defines these separately as their own assembly in Unity *(Note: Spine `.asmdef` files are currently deactivated to `.txt` extension, see below)*. For projects not using assembly definition, you may delete the `.asmdef` files. These assembly definitions will be ignored by older versions of Unity that don't support it. + * In this scheme, the entirety of the base spine-csharp runtime is inside the "Runtime" folder, to be compiled in the same assembly as spine-unity so they can continue to share internal members. +* **Spine `.asmdef` files are now deactivated (using `.txt` extension) by default** This prevents problems when updating Spine through unitypackages, overwriting the Timeline reference entry in `spine-unity.asmdef` (added automatically when enabling Unity 2019 Timeline support, see `Timeline Support for Unity 2019`), causing compile errors. In case you want to enable the `.asmdef` files, rename the files: + `Spine/Runtime/spine-unity.txt` to `Spine/Runtime/spine-unity.asmdef` and + `Spine/Editor/spine-unity-editor.txt` to `Spine/Editor/spine-unity-editor.asmdef`. +* **SkeletonAnimator is now SkeletonMecanim** The Spine-Unity Mecanim-driven component `SkeletonAnimator` has been renamed `SkeletonMecanim` to make it more autocomplete-friendly and more obvious at human-glance. The .meta files and guids should remain intact so existing projects and prefabs should not break. However, user code needs to be updated to use `SkeletonMecanim`. +* **SpineAtlasAsset** The existing `AtlasAsset` type has been renamed to `SpineAtlasAsset` to signify that it specifically uses a Spine/libGDX atlas as its source. Serialization should be intact but user code will need to be updated to refer to existing atlases as `SpineAtlasAsset`. + * **AtlasAssetBase** `SpineAtlasAsset` now has an abstract base class called `SpineAtlasAsset`. This is the base class to derive when using alternate atlas sources. Existing SkeletonDataAsset field "atlasAssets" now have the "AtlasAssetBase" type. Serialization should be intact, but user code will need to be updated to refer to the atlas assets accordingly. + * This change is in preparation for alternate atlas options such as Unity's SpriteAtlas. +* **Optional Straight Alpha for shaders** Spine-Unity's included Unity shaders now have a `_STRAIGHT_ALPHA_INPUT` shader_feature, toggled as a checkbox in the Material's inspector. This allows the Material to use a non-premultiplied alpha/straight alpha input texture. + * The following shaders now have the "Straight Alpha Texture" checkbox when used on a material: + * `Spine/Skeleton` + * `Spine/Skeleton Tint Black` + * `Spine/Skeleton Lit` + * `Spine/Skeleton Tint` + * `Spine/Skeleton Fill` + * `Spine/SkeletonGraphic (Premultiply Alpha)` was renamed to `Spine/SkeletonGraphic` + * `Spine/SkeletonGraphic Tint Black (Premultiply Alpha)` was renamed to `Spine/SkeletonGraphic Tint Black` + * `Spine/Skeleton PMA Multiply` + * `Spine/Skeleton PMA Screen` + * Dedicated straight alpha shaders were removed from the runtime. + * `Spine/Straight Alpha/Skeleton Fill` + * `Spine/Straight Alpha/Skeleton Tint` +* **Detection of Incorrect Texture Settings** Especially when atlas textures are exported with setting `Premultiply alpha` enabled, it is important to configure Unity's texture import settings correctly. By default, you will now receive warnings where texture settings are expected to cause incorrect rendering. + * The following rules apply: + * `sRGB (Color Texture)` shall be disabled when `Generate Mip Maps` is enabled, otherwise you will receive white border outlines. + * `Alpha Is Transparency` shall be disabled on `Premultiply alpha` textures, otherwise you will receive light ghosting artifacts in transparent areas. + * These warnings can be disabled in `Edit - Preferences - Spine`. +* **Sprite Mask Support for all Included Shaders** The `Skeleton Animation` and `Skeleton Mecanim` components now provide an additional `Mask Interaction` field in the Inspector, covering identical functionality as Unity's built in `Sprite Renderer` component: + * `Mask Interaction` modes: + * `None` - The sprite will not interact with the masking system. Default behavior. + * `Visible Inside Mask` - The sprite will be visible only in areas where a mask is present. + * `Visible Outside Mask` - The sprite will be visible only in areas where no mask is present. + * `Automatically Generated Materials` When switching `Mask Interaction` modes in the Inspector outside of Play mode, the required additional material assets are generated for the respective `Stencil Compare` parameters - with file suffixes `'_InsideMask'` and `'_OutsideMask'`, placed in the same folder as the original materials. By default all generated materials are kept as references by the `Skeleton Animation` component for switching at runtime. + These materials can be managed and optimized via the `SkeletonAnimation`'s `Advanced` section: + * Using the `Clear` button you can clear the reference to unneeded materials, + * Using the `Delete` button the respective assets are deleted as well as references cleared. Note that other `Skeleton Animation` GameObjects might still reference the materials, so use with caution! + * With the `Set` button you can again assign a link to the respective materials to prepare them for runtime use. If the materials were not present or have been deleted, they are generated again based on the default materials. + * When switching `Mask Interaction` mode at runtime, the previously prepared materials are switched active automatically. When the respective materials have not been prepared, material copies of the default materials are created on the fly. Note that these materials are not shared between similar `Skeleton Animation` GameObjects, so it is recommended to use the generated material assets where possible. + * **Every shader now exposes the `Stencil Compare` parameter** for further customization. This way you have maximum flexibility to use custom mechanisms to switch materials at runtime if you should ever need more than the three materials generated by `Skeleton Animation`'s `Mask Interaction` parameter. Reference `Stencil Compare` values are: + * `CompareFunction.Disabled` for `Mask Interaction - None` + * `CompareFunction.LessEqual` for `Mask Interaction - Visible Inside Mask` + * `CompareFunction.Greater` for `Mask Interaction - Visible Outside Mask` +* **RectMask2D Support for SkeletonGraphic** Both `SkeletonGraphic` shaders '`Spine/SkeletonGraphic`' and '`Spine/SkeletonGraphic Tint Black`' now respect masking areas defined via Unity's `RectMask2D` component. +* **Timeline Support for Unity 2019** using the existing Timeline components. By default, all Spine Timeline components are deactivated in Unity 2019 and **can be activated via the Spine Preferences menu**. This step became necessary because in Unity 2019, Timeline has been moved to a separate Package and is no longer included in the Unity core. Please visit `Edit - Preferences - Spine` and at `Timeline Package Support` hit `Enable` to automatically perform all necessary steps to activate the Timeline components. +This will automatically: + 1. download the Unity Timeline package + 2. activate the Spine Timeline components by setting the compile definition `SPINE_TIMELINE_PACKAGE_DOWNLOADED` for all platforms + 3. modify the `spine-unity.asmdef` file by adding the reference to the Unity Timeline library. +* Added `Create 2D Hinge Chain` functionality at `SkeletonUtilityBone` inspector, previously only `Create 3D Hinge Chain` was available. + +### XNA/MonoGame +* Added support for any `Effect` to be used by `SkeletonRenderer` +* Added support for `IVertexEffect` to modify vertices of skeletons on the CPU. `IVertexEffect` instances can be set on the `SkeletonRenderer`. See example project. +* Added `SkeletonDebugRenderer` +* Made `MeshBatcher` of SkeletonRenderer accessible via a getter. Allows user to batch their own geometry together with skeleton meshes for maximum batching instead of using XNA SpriteBatcher. + +## Java +* **Breaking changes** + * Skeleton attachments: Moved update of attached skeleton out of libGDX `SkeletonRenderer`, added overloaded method `Skeleton#updateWorldTransform(Bone)`, used for `SkeletonAttachment`. You now MUST call this new method with the bone of the parent skeleton to which the child skeleton is attached. See `SkeletonAttachmentTest` for and example. + * The completion event will fire for looped 0 duration animations every frame. + * `MixPose` is now called `MixBlend`. + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 +* **Additions** + * Added `EventData#audioPath` field. This field contains the file name of the audio file used for the event. + * Added convenience method to add all attachments from one skin to another, see https://github.com/EsotericSoftware/spine-runtimes/commit/a0b7bb6c445efdfac12b0cdee2057afa3eff3ead + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `TrackEntry#setMixBlend(MixBlend.add)` on each track. To specify the blend percentage, set `TrackEntry#alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `TrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + +### libGDX +* Added `VertexEffect` interface, instances of which can be set on `SkeletonRenderer`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect` and `VertexEffectTest`. +* Added improved tint-black shader. +* Improved performance by avoiding batch flush when not switching between normal and additive rendering with PMA +* Improvements to skeleton viewer. +* `TwoColorPolygonBatch` implements the `Batch` interface, allowing to the be used with other libGDX classes that require a batcher for drawing, potentially improving performance. See https://github.com/EsotericSoftware/spine-runtimes/commit/a46b3d1d0c135d51f9bef9ca17a5f8e5dda69927 +* Added `SkeletonDrawable` to render skeletons in scene2d UI https://github.com/EsotericSoftware/spine-runtimes/commit/b93686c185e2c9d5466969a8e07eee573ebe4b97 + +## Lua +* **Breaking changes** + * The completion event will fire for looped 0 duration animations every frame. + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 +* **Additions** + * Added `JitterEffect` and `SwirlEffect` and support for vertex effects in Corona and Love + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `TrackEntry:setMixBlend(MixBlend.add)` on each track. To specify the blend percentage, set `TrackEntry.alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `TrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + +### Love2D +* Added support for vertex effects. Set an implementation like "JitterEffect" on `Skeleton.vertexEffect`. See `main.lua` for an example. + +### Corona +* Added support for vertex effects. Set an implementation like "JitterEffect" on `SkeletonRenderer.vertexEffect`. See `main.lua` for an example + +## Typescript/Javascript +* **Breaking changes** + * The completion event will fire for looped 0 duration animations every frame. + * Skeleton `flipX/flipY` has been replaced with `scaleX/scaleY`. This cleans up applying transforms and is more powerful. Allows scaling a whole skeleton which has bones that disallow scale inheritance + * Mix time is no longer affected by `TrackEntry#timeScale`. See https://github.com/EsotericSoftware/spine-runtimes/issues/1194 +* **Additions** + * Added `AssetManager.loadTextureAtlas`. Instead of loading the `.atlas` and corresponding image files manually, you can simply specify the location of the `.atlas` file and AssetManager will load the atlas and all its images automatically. `AssetManager.get("atlasname.atlas")` will then return an instance of `spine.TextureAtlas`. + * Added additive animation blending. When playing back multiple animations on different tracks, where each animation modifies the same skeleton property, the results of tracks with lower indices are discarded, and only the result from the track with the highest index is used. With animation blending, the results of all tracks are mixed together. This allows effects like mixing multiple facial expressions (angry, happy, sad) with percentage mixes. By default the old behaviour is retained (results from lower tracks are discarded). To enable additive blending across animation tracks, call `TrackEntry#setMixBlend(MixBlend.add)` on each track. To specify the blend percentage, set `TrackEntry#alpha`. See http://esotericsoftware.com/forum/morph-target-track-animation-mix-mode-9459 for a discussion. See https://github.com/EsotericSoftware/spine-runtimes/blob/f045d221836fa56191ccda73dd42ae884d4731b8/spine-ts/webgl/tests/test-additive-animation-blending.html for an example. + * Added work-around for iOS WebKit JIT bug, see https://github.com/EsotericSoftware/spine-runtimes/commit/c28bbebf804980f55cdd773fed9ff145e0e7e76c + * Support for stretchy IK + * Support for audio events, see `audioPath`, `volume` and `balance` fields on event (data). + * `TrackEntry` has an additional field called `holdPrevious`. It can be used to counter act a limitation of `AnimationState` resulting in "dipping" of parts of the animation. For a full discussion of the problem and the solution we've implemented, see this [forum thread](http://esotericsoftware.com/forum/Probably-Easy-Animation-mixing-with-multiple-tracks-10682?p=48130&hilit=holdprevious#p48130). + * Added `AssetManager#setRawDataURI(path, data)`. Allows to set raw data URIs for a specific path, which in turn enables embedding assets into JavaScript/HTML. + +### WebGL backend +* Added `VertexEffect` interface, instances of which can be set on `SkeletonRenderer`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect`, and the example which allows to set effects. +* Added `slotRangeStart` and `slotRangeEnd` parameters to `SkeletonRenderer#draw` and `SceneRenderer#drawSkeleton`. This allows you to render only a range of slots in the draw order. See `spine-ts/webgl/tests/test-slot-range.html` for an example. +* Added improved tint-black shader. +* Added `SceneRenderer#drawTextureUV()`, allowing to draw a texture with manually specified texture coordinates. +* Exposed all renderers in `SceneRenderer`. + +### Canvas backend +* Added support for shearing and non-uniform scaling inherited from parent bones. +* Added support for alpha tinting. + +### Three.js backend +* Added `VertexEffect` interface, instances of which can be set on `SkeletonMesh`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect`. +* Added support for multi-page atlases + +### Widget backend + * Added fields `atlasContent`, `atlasPagesContent`, and `jsonContent` to `WidgetConfiguration` allowing you to directly pass the contents of the `.atlas`, atlas page `.png` files, and the `.json` file without having to do a request. See `README.md` and the example for details. + * `SpineWidget.setAnimation()` now takes an additional optional parameter for callbacks when animations are completed/interrupted/etc. + +# 3.6 + +## AS3 +* **Breaking changes** + * Removed `Bone.worldToLocalRotationX` and `Bone.worldToLocalRotationY`. Replaced by `Bone.worldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * Made `Bone` fields `_a`, `_b`, `_c`, `_d`, `_worldX` and `_worldY` public, removed underscore prefix. + * Removed `VertexAttachment.computeWorldVertices` overload, changed `VertexAttachment.computeWorldVertices2` to `VertexAttachment.computeWorldVertices`, added `stride` parameter. + * Removed `RegionAttachment.vertices` field. The vertices array is provided to `RegionAttachment.computeWorldVertices` by the API user now. + * Removed `RegionAttachment.updateWorldVertices`, added `RegionAttachment.computeWorldVertices`. The new method now computes the x/y positions of the 4 vertices of the corner and places them in the provided `worldVertices` array, starting at `offset`, then moving by `stride` array elements when advancing to the next vertex. This allows to directly compose the vertex buffer and avoids a copy. The computation of the full vertices, including vertex colors and texture coordinates, is now done by the backend's respective renderer. + * Replaced `r`, `g`, `b`, `a` fields with instances of new `Color` class in `RegionAttachment`, `MeshAttachment`, `Skeleton`, `SkeletonData`, `Slot` and `SlotData`. + * The completion event will fire for looped 0 duration animations every frame. + +* **Additions** + * Added `Skeleton.getBounds` from reference implementation. + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `Bone.localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `TwoColorTimeline` and additional fields on `Slot` and `SlotData`. + * Added `PointAttachment`, additional method `newPointAttachment` in `AttachmentLoader` interface. + * Added `ClippingAttachment`, additional method `newClippingAttachment` in `AttachmentLoader` interface. + * `AnimationState#apply` returns boolean indicating if any timeline was applied or not. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + * Added `VertexEffect` and implementations `JitterEffect` and `SwirlEffect`. Allows you to modify vertices before they are submitted for drawing. See Starling changes. + +### Starling + * Fixed renderer to work with 3.6 changes. + * Added support for two color tinting. + * Added support for clipping. + * Added support for rotated regions in texture atlas loaded via StarlingAtlasAttachmentLoader. + * Added support for vertex effects. See `RaptorExample.as` + * Added 'getTexture()' method to 'StarlingTextureAtlasAttachmentLoader' + * Breaking change: if a skeleton requires two color tinting, you have to enable it via `SkeletonSprite.twoColorTint = true`. In this case the skeleton will use the `TwoColorMeshStyle`, which internally uses a different vertex layout and shader. This means that skeletons with two color tinting enabled will break batching and hence increase the number of draw calls in your app. + +## C +* **Breaking changes** + * `spVertexAttachment_computeWorldVertices` and `spRegionAttachment_computeWorldVerticeS` now take new parameters to make it possible to directly output the calculated vertex positions to a vertex buffer. Removes the need for additional copies in the backends' respective renderers. + * Removed `spBoundingBoxAttachment_computeWorldVertices`, superseded by `spVertexAttachment_computeWorldVertices`. + * Removed `spPathAttachment_computeWorldVertices` and `spPathAttachment_computeWorldVertices1`, superseded by `spVertexAttachment_computeWorldVertices`. + * Removed `sp_MeshAttachment_computeWorldVertices`, superseded by `spVertexAttachment_computeWorldVertices`. + * Removed `spBone_worldToLocalRotationX` and `spBone_worldToLocalRotationY`. Replaced by `spBone_worldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * Replaced `r`, `g`, `b`, `a` fields with instances of new `spColor` struct in `spRegionAttachment`, `spMeshAttachment`, `spSkeleton`, `spSkeletonData`, `spSlot` and `spSlotData`. + * Removed `spVertexIndex`from public API. + * Listeners on `spAnimationState` or `spTrackEntry` will now be also called in case a track entry is disposed as part of dispoing the `spAnimationState`. + * The completion event will fire for looped 0 duration animations every frame. +* **Additions** + * Added support for local and relative transform constraint calculation, including additional fields in `spTransformConstraintData`. + * Added `spPointAttachment`, additional method `spAtlasAttachmentLoadeR_newPointAttachment`. + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `spBone_localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `spTwoColorTimeline` and additional fields on `spSlot` and `spSlotData`. + * Added `userData` field to `spTrackEntry`, so users can expose data in `spAnimationState` callbacks. + * Modified kvec.h used by SkeletonBinary.c to use Spine's MALLOC/FREE macros. That way there's only one place to inject custom allocators ([extension.h](https://github.com/EsotericSoftware/spine-runtimes/blob/master/spine-c/spine-c/include/spine/extension.h)) [commit](https://github.com/EsotericSoftware/spine-runtimes/commit/c2cfbc6cb8709daa082726222d558188d75a004f) + * Added macros to define typed dynamic arrays, see `Array.h/.c` + * Added `spClippingAttachment` and respective enum. + * Added `spSkeletonClipper` and `spTriangulator`, used to implement software clipping of attachments. + * `AnimationState#apply` returns boolean indicating if any timeline was applied or not. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + * Added `spVertexEffect` and corresponding implementations `spJitterVertexEffect` and `spSwirlVertexEffect`. Create/dispose through the corresponding `spXXXVertexEffect_create()/dispose()` functions. Set on framework/engine specific renderer. See changes for spine-c based frameworks/engines below. + * Functions in `extension.h` are not prefixed with `_sp` instead of just `_` to avoid interference with other libraries. + * Introduced `SP_API` macro. Every spine-c function is prefixed with this macro. By default, it is an empty string. Can be used to markup spine-c functions with e.g. ``__declspec` when compiling to a dll or linking to that dll. + +### Cocos2d-X + * Fixed renderer to work with 3.6 changes + * Optimized rendering by removing all per-frame allocation in `SkeletonRenderer`, resulting in 15% performance increase for large numbers of skeletons being rendered per frame. + * Added support for two color tinting. Tinting is enabled/disabled per `SkeletonRenderer`/`SkeletonAnimation` instance. Use `SkeletonRenderer::setTwoColorTint()`. Note that two color tinting requires the use of a non-standard shader and vertex format. This means that skeletons rendered with two color tinting will break batching. However, skeletons with two color tinting enabled and rendered after each other will be batched. + * Updated example to use Cocos2d-x 3.14.1. + * Added mesh debug rendering. Enable/Disable via `SkeletonRenderer::setDebugMeshesEnabled()`. + * Added support for clipping. + * SkeletonRenderer now combines the displayed color of the Node (cascaded from all parents) with the skeleton color for tinting. + * Added support for vertex effects. See `RaptorExample.cpp`. + * Added ETC1 alpha support, thanks @halx99! Does not work when two color tint is enabled. + * Added `spAtlasPage_setCustomTextureLoader()` which let's you do texture loading manually. Thanks @jareguo. + * Added `SkeletonRenderer:setSlotsRange()` and `SkeletonRenderer::createWithSkeleton()`. This allows you to split rendering of a skeleton up into multiple parts, and render other nodes in between. See `SkeletonRendererSeparatorExample.cpp` for an example. + +### Cocos2d-Objc + * Fixed renderer to work with 3.6 changes + * Added support for two color tinting. Tinting is enabled/disabled per `SkeletonRenderer/SkeletonAnimation.twoColorTint = true`. Note that two color tinted skeletons do not batch with other nodes. + * Added support for clipping. + +### SFML + * Fixed renderer to work with 3.6 changes. Sadly, two color tinting does not work, as the vertex format in SFML is fixed. + * Added support for clipping. + * Added support for vertex effects. See raptor example. + * Added premultiplied alpha support to `SkeletonDrawable`. + +### Unreal Engine 4 + * Fixed renderer to work with 3.6 changes + * Added new UPROPERTY to SpineSkeletonRendererComponent called `Color`. This allows to set the tint color of the skeleton in the editor, C++ and Blueprints. Under the hood, the `spSkeleton->color` will be set on every tick of the renderer component. + * Added support for clipping. + * Switched from built-in ProceduralMeshComponent to RuntimeMeshComponent by Koderz (https://github.com/Koderz/UE4RuntimeMeshComponent, MIT). Needed for more flexibility regarding vertex format, should not have an impact on existing code/assets. You need to copy the RuntimeMeshComponentPlugin from our repository in `spine-ue4\Plugins\` to your project as well! + * Added support for two color tinting. All base materials, e.g. SpineUnlitNormalMaterial, now do proper two color tinting. No material parameters have changed. + * Updated to Unreal Engine 4.16.1. Note that 4.16 has a regression which will make it impossible to compile plain .c files! + * spine-c is now exposed from the plugin shared library on Windows via __declspec. + +## C# +* **Breaking changes** + * `MeshAttachment.parentMesh` is now a private field to enforce using the `.ParentMesh` setter property in external code. The `MeshAttachment.ParentMesh` property is an appropriate replacement wherever `.parentMesh` was used. + * `Skeleton.GetBounds` takes a scratch array as input so it doesn't have to allocate a new array on each invocation itself. Reduces GC activity. + * Removed `Bone.WorldToLocalRotationX` and `Bone.WorldToLocalRotationY`. Replaced by `Bone.WorldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * Added `stride` parameter to `VertexAttachment.ComputeWorldVertices`. + * Removed `RegionAttachment.Vertices` field. The vertices array is provided to `RegionAttachment.ComputeWorldVertices` by the API user now. + * Removed `RegionAttachment.UpdateWorldVertices`, added `RegionAttachment.ComputeWorldVertices`. The new method now computes the x/y positions of the 4 vertices of the corner and places them in the provided `worldVertices` array, starting at `offset`, then moving by `stride` array elements when advancing to the next vertex. This allows to directly compose the vertex buffer and avoids a copy. The computation of the full vertices, including vertex colors and texture coordinates, is now done by the backend's respective renderer. + * The completion event will fire for looped 0 duration animations every frame. + + * **Additions** + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `Bone.localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `TwoColorTimeline` and additional fields on `Slot` and `SlotData`. + * Added `PointAttachment`, additional method `NewPointAttachment` in `AttachmentLoader` interface. + * Added `ClippingAttachment`, additional method `NewClippingAttachment` in `AttachmentLoader` interface. + * Added `SkeletonClipper` and `Triangulator`, used to implement software clipping of attachments. + * `AnimationState.Apply` returns a bool indicating if any timeline was applied or not. + * `Animation.Apply` and `Timeline.Apply`` now take enums `MixPose` and `MixDirection` instead of bools. + +### Unity + * Refactored renderer to work with new 3.6 features. + * **Two color tinting** is currently supported via extra UV2 and UV3 mesh vertex streams. To use Two color tinting, you need to: + * switch on "Tint Black" under "Advanced...", + * use the new `Spine/Skeleton Tint Black` shader, or your own shader that treats the UV2 and UV3 streams similarly. + * Additionally, for SkeletonGraphic, you can use `Spine/SkeletonGraphic Tint Black` (or the bundled SkeletonGraphicTintBlack material) or your own shader that uses UV2 and UV3 streams similarly. **Additional Shader Channels** TexCoord1 and TexCoord2 will need to be enabled from the Canvas component's inspector. These correspond to UV2 and UV3. + * **Clipping** is now supported. Caution: The SkeletonAnimation switches to slightly slower mesh generation code when clipping so limit your use of `ClippingAttachment`s when using on large numbers of skeletons. + * **SkeletonRenderer.initialFlip** Spine components such as SkeletonRenderer, SkeletonAnimation, SkeletonAnimator now has `initialFlipX` and `initialFlipY` fields which are also visible in the inspector under "Advanced...". It will allow you to set and preview a starting flip value for your skeleton component. This is applied immediately when the internal skeleton object is instantiated. + * **[SpineAttribute] Improvements** + * **Icons have been added to SpineAttributeDrawers**. This should make your default inspectors easier to understand at a glance. + * **Added Constraint Attributes** You can now use `[SpineIkConstraint]` `[SpineTransformConstraint]` `[SpinePathConstraint]` + * **SpineAttribute dataField** parameter can also now detect sibling fields within arrays and serializable structs/classes. + * **[SpineAttribute(includeNone:false)]** SpineAttributes now have an `includeNone` optional parameter to specify if you want to include or exclude a none ("") value option in the dropdown menu. Default is `includeNone:true`. + * **[SpineAttachment(skinField:"mySkin")]** The SpineAttachment attribute now has a skinField optional parameter to limit the dropdown items to attachments in a specific skin instead of the just default skin or all the skins in SkeletonData. + * **SkeletonDebugWindow**. Debugging tools have been moved from the SkeletonAnimation and SkeletonUtility component inspectors into its own utility window. You can access "Skeleton Debug" under the `Advanced...` foldout in the SkeletonAnimation inspector, or in SkeletonAnimation's right-click/context menu. + * **Skeleton Baking Window** The old Skeleton Baking feature is also now accessible through the SkeletonDataAsset's right-click/context menu. + * **AttachmentTools source material**. `AttachmentTools` methods can now accept a `sourceMaterial` argument to copy material properties from. + * **AttachmentTools Skin Extensions**. Using AttachmentTools, you can now add entries by slot name by also providing a skeleton argument. Also `Append(Skin)`, `RemoveAttachment` and `Clear` have been added. + * **BoneFollower and SkeletonUtilityBone Add RigidBody Button**. The BoneFollower and SkeletonUtilityBone component inspectors will now offer to add a `Rigidbody` or `Rigidbody2D` if it detects a collider of the appropriate type. Having a rigidbody on a moving transform with a collider fits better with the Unity physics systems and prevents excess calculations. It will not detect colliders on child objects so you have to add Rigidbody components manually accordingly. + * **SkeletonRenderer.OnPostProcessVertices** is a new callback that gives you a reference to the MeshGenerator after it has generated a mesh from the current skeleton pose. You can access `meshGenerator.VertexBuffer` or `meshGenerator.ColorBuffer` to modify these before they get pushed into the UnityEngine.Mesh for rendering. This can be useful for non-shader vertex effects. + * **Examples** + * **Examples now use properties**. The code in the example scripts have been switched over to using properties instead of fields to encourage their use for consistency. This is in anticipation of both users who want to move the Spine folders to the Unity Plugins folder (compiled as a different assembly), and of Unity 2017's ability to manually define different assemblies for shorter compilation times. + * **Mix And Match**. The mix-and-match example scene, code and data have been updated to reflect the current recommended setup for animation-compatible custom equip systems The underlying API has changed since 3.5 and the new API calls in MixAndMatch.cs is recommended. Documentation is in progress. + * **Sample Components**. `AtasRegionAttacher` and `SpriteAttacher` are now part of `Sample Components`, to reflect that they are meant to be used as sample code rather than production. A few other sample components have also been added. New imports of the unitypackage Examples folder will see a "Legacy" folder comprised of old sample components that no longer contain the most up-to-date and recommended workflows, but are kept in case old setups used them for production. + * **Spine folder**. In the unitypackage, the "spine-csharp" and "spine-unity" folders are now inside a "Spine" folder. This change will only affect fresh imports. Importing the unitypackage to update Spine-Unity in your existing project will update the appropriate files however you chose to arrange them, as long as the meta files are intact. + * **Breaking changes** + * The Sprite shaders module was updated to the latest version from the [source](https://github.com/traggett/UnitySpriteShaders/commits/master). Some changes were made to the underlying keyword structure. You may need to review the settings of your lit materials. Particularly, your Fixed Normals settings. + * The `Spine/Skeleton Lit` shader was switched over to non-fixed-function code. It now no longer requires mesh normals and has fixed normals at the shader level. + * The old MeshGenerator classes, interfaces and code in `Spine.Unity.MeshGeneration` are now deprecated. All mesh-generating components now share the class `Spine.Unity.MeshGenerator` defined in `SpineMesh.cs`. MeshGenerator is a serializable class. + * The `SkeletonRenderer.renderMeshes` optimization is currently non-functional. + * Old triangle-winding code has been removed from `SkeletonRenderer`. Please use shaders that have backface culling off. + * Render settings in `SkeletonGraphic` can now be accessed under `SkeletonGraphic.MeshGenerator.settings`. This is visible in the SkeletonGraphic inspector as `Advanced...` + * We will continue to bundle the unitypackage with the empty .cs files of deprecated classes until Spine 3.7 to ensure the upgrade process does not break. + * The [SpineAttachment(slotField:)] optional parameter found property value now acts as a Find(slotName) argument rather than Contains(slotName). + * `SkeletonAnimator` now uses a `SkeletonAnimator.MecanimTranslator` class to translate an Animator's Mecanim State Machine into skeleton poses. This makes code reuse possible for a Mecanim version of SkeletonGraphic. + * `SkeletonAnimator` `autoreset` and the `mixModes` array are now a part of SkeletonAnimator's MecanimTranslator `.Translator`. `autoReset` is set to true by default. Old prefabs and scene objects with Skeleton Animator may no longer have correct values set. + * Warnings and conditionals checking for specific Unity 5.2-and-below incompatibility have been removed. + +## XNA/MonoGame + * Added support for clipping + * Removed `RegionBatcher` and `SkeletonRegionRenderer`, renamed `SkeletonMeshRenderer` to `SkeletonRenderer` + * Added support for two color tint. For it to work, you need to add the `SpineEffect.fx` file to your content project, then load it via `var effect = Content.Load("SpineEffect");`, and set it on the `SkeletonRenderer`. See the example project for code. + * Added support for any `Effect` to be used by `SkeletonRenderer` + * Added support for `IVertexEffect` to modify vertices of skeletons on the CPU. `IVertexEffect` instances can be set on the `SkeletonRenderer`. See example project. + * Added `SkeletonDebugRenderer` + * Made `MeshBatcher` of SkeletonRenderer accessible via a getter. Allows user to batch their own geometry together with skeleton meshes for maximum batching instead of using XNA SpriteBatcher. + +## Java +* **Breaking changes** + * `Skeleton.getBounds` takes a scratch array as input so it doesn't have to allocate a new array on each invocation itself. Reduces GC activity. + * Removed `Bone.worldToLocalRotationX` and `Bone.worldToLocalRotationY`. Replaced by `Bone.worldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * Added `stride` parameter to `VertexAttachment.computeWorldVertices`. + * Removed `RegionAttachment.vertices` field. The vertices array is provided to `RegionAttachment.computeWorldVertices` by the API user now. + * Removed `RegionAttachment.updateWorldVertices`, added `RegionAttachment.computeWorldVertices`. The new method now computes the x/y positions of the 4 vertices of the corner and places them in the provided `worldVertices` array, starting at `offset`, then moving by `stride` array elements when advancing to the next vertex. This allows to directly compose the vertex buffer and avoids a copy. The computation of the full vertices, including vertex colors and texture coordinates, is now done by the backend's respective renderer. + * Skeleton attachments: Moved update of attached skeleton out of libGDX `SkeletonRenderer`, added overloaded method `Skeleton#updateWorldTransform(Bone), used for `SkeletonAttachment`. You now MUST call this new method + with the bone of the parent skeleton to which the child skeleton is attached. See `SkeletonAttachmentTest` for and example. + * The completion event will fire for looped 0 duration animations every frame. + +* **Additions** + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `Bone.localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `TwoColorTimeline` and additional fields on `Slot` and `SlotData`. + * Added `PointAttachment`, additional method `newPointAttachment` in `AttachmentLoader` interface. + * Added `ClippingAttachment`, additional method `newClippingAttachment` in `AttachmentLoader` interface. + * Added `SkeletonClipper` and `Triangulator`, used to implement software clipping of attachments. + * `AnimationState#apply` returns boolean indicating if any timeline was applied or not. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + +### libGDX + * Fixed renderer to work with 3.6 changes + * Added support for two color tinting. Use the new `TwoColorPolygonBatch` together with `SkeletonRenderer` + * Added support for clipping. See `SkeletonClipper`. Used automatically by `SkeletonRenderer`. Does not work when using a `SpriteBatch` with `SkeletonRenderer`. Use `PolygonSpriteBatch` or `TwoColorPolygonBatch` instead. + * Added `VertexEffect` interface, instances of which can be set on `SkeletonRenderer`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect` and `VertexEffectTest`. + +## Lua +* **Breaking changes** + * Removed `Bone:worldToLocalRotationX` and `Bone:worldToLocalRotationY`. Replaced by `Bone:worldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * `VertexAttachment:computeWorldVertices` now takes offsets and stride to allow compositing vertices directly in a vertex buffer to be send to the GPU. The compositing is now performed in the backends' respective renderers. This also affects the subclasses `MeshAttachment`, `BoundingBoxAttachment` and `PathAttachment`. + * Removed `RegionAttachment:updateWorldVertices`, added `RegionAttachment:computeWorldVertices`, which takes offsets and stride to allow compositing vertices directly in a vertex buffer to be send to the GPU. The compositing is now performed in the backends' respective renderers. + * Removed `MeshAttachment.worldVertices` field. Computation is now performed in each backends' respective renderer. The `uv` coordinates are now stored in `MeshAttachment.uvs`. + * Removed `RegionAttachment.vertices` field. Computation is now performed in each backends respective renderer. The `uv` coordinates for each vertex are now stored in the `RegionAttachment.uvs` field. + * The completion event will fire for looped 0 duration animations every frame. + * **Additions** + * Added `Bone:localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `TwoColorTimeline` and additional fields on `Slot` and `SlotData`. + * Added `PointAttachment`, additional method `newPointAttachment` in `AttachmentLoader` interface. + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `ClippingAttachment`, additional method `newClippingAttachment` in `AttachmentLoader` interface. + * Added `SkeletonClipper` and `Triangulator`, used to implement software clipping of attachments. + * `AnimationState#apply` returns boolean indicating if any timeline was applied or not. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + * Added `JitterEffect` and `SwirlEffect` and support for vertex effects in Corona and Love + +### Love2D + * Fixed renderer to work with 3.6 changes + * Added support for two color tinting. Enable it via `SkeletonRenderer.new(true)`. + * Added clipping support. + * Added support for vertex effects. Set an implementation like "JitterEffect" on `Skeleton.vertexEffect`. See `main.lua` for an example. + +### Corona + * Fixed renderer to work with 3.6 changes. Sadly, two color tinting is not supported, as Corona doesn't let us change the vertex format needed and its doesn't allow to modify shaders in the way needed for two color tinting + * Added clipping support. + * Added support for vertex effects. Set an implementation like "JitterEffect" on `SkeletonRenderer.vertexEffect`. See `main.lua` for an example + +## Typescript/Javascript +* **Breaking changes** + * `Skeleton.getBounds` takes a scratch array as input so it doesn't have to allocate a new array on each invocation itself. Reduces GC activity. + * Removed `Bone.worldToLocalRotationX` and `Bone.worldToLocalRotationY`. Replaced by `Bone.worldToLocalRotation` (rotation given relative to x-axis, counter-clockwise, in degrees). + * Removed `VertexAttachment.computeWorldVertices` overload, changed `VertexAttachment.computeWorldVerticesWith` to `VertexAttachment.computeWorldVertices`, added `stride` parameter. + * Removed `RegionAttachment.vertices` field. The vertices array is provided to `RegionAttachment.computeWorldVertices` by the API user now. + * Removed `RegionAttachment.updateWorldVertices`, added `RegionAttachment.computeWorldVertices`. The new method now computes the x/y positions of the 4 vertices of the corner and places them in the provided `worldVertices` array, starting at `offset`, then moving by `stride` array elements when advancing to the next vertex. This allows to directly compose the vertex buffer and avoids a copy. The computation of the full vertices, including vertex colors and texture coordinates, is now done by the backend's respective renderer. + * The completion event will fire for looped 0 duration animations every frame. + * Removed the Spine Widget in favor of [Spine Web Player](https://esotericsoftware.com/spine-player). + +* **Additions** + * Added support for local and relative transform constraint calculation, including additional fields in `TransformConstraintData` + * Added `Bone.localToWorldRotation`(rotation given relative to x-axis, counter-clockwise, in degrees). + * Added two color tinting support, including `TwoColorTimeline` and additional fields on `Slot` and `SlotData`. + * Added `PointAttachment`, additional method `newPointAttachment` in `AttachmentLoader` interface. + * Added `ClippingAttachment`, additional method `newClippingAttachment` in `AttachmentLoader` interface. + * Added `SkeletonClipper` and `Triangulator`, used to implement software clipping of attachments. + * `AnimationState#apply` returns boolean indicating if any timeline was applied or not. + * `Animation#apply` and `Timeline#apply`` now take enums `MixPose` and `MixDirection` instead of booleans + * Added `AssetManager.loadTextureAtlas`. Instead of loading the `.atlas` and corresponding image files manually, you can simply specify the location of the `.atlas` file and AssetManager will load the atlas and all its images automatically. `AssetManager.get("atlasname.atlas")` will then return an instance of `spine.TextureAtlas`. + * Added the [Spine Web Player](https://esotericsoftware.com/spine-player) + + +### WebGL backend + * Fixed WebGL context loss + * Added `Restorable` interface, implemented by any WebGL resource that needs restoration after a context loss. All WebGL resource classes (`Shader`, `Mesh`, `GLTexture`) implement this interface. + * Added `ManagedWebGLRenderingContext`. Handles setup of a `WebGLRenderingContext` given a canvas element and restoration of WebGL resources (`Shader`, `Mesh`, `GLTexture`) on WebGL context loss. WebGL resources register themselves with the `ManagedWebGLRenderingContext`. If the context is informed of a context loss and restoration, the registered WebGL resources' `restore()` method is called. The `restore()` method implementation on each resource type will recreate the GPU side objects. + * All classes that previously took a `WebGLRenderingContext` in the constructor now also allow a `ManagedWebGLRenderingContext`. This ensures existing applications do not break. + * To use automatic context restauration: + 1. Create or fetch a canvas element from the DOM + 2. Instantiate a `ManagedWebGLRenderingContext`, passing the canvas to the constructor. This will setup a `WebGLRenderingContext` internally and manage context loss/restoration. + 3. Pass the `ManagedWebGLRenderingContext` to the constructors of classes that you previously passed a `WebGLRenderingContext` to (`AssetManager`, `GLTexture`, `Mesh`, `Shader`, `PolygonBatcher`, `SceneRenderer`, `ShapeRenderer`, `SkeletonRenderer`, `SkeletonDebugRenderer`). + * Fixed renderer to work with 3.6 changes. + * Added support for two color tinting. + * Improved performance by using `DYNAMIC_DRAW` for vertex buffer objects and fixing bug that copied to much data to the GPU each frame in `PolygonBatcher`/`Mesh`. + * Added two color tinting support, enabled by default. You can disable it via the constructors of `SceneRenderer`, `SkeletonRenderer`and `PolygonBatcher`. Note that you will need to use a shader created via `Shader.newTwoColoredTexturedShader` shader with `SkeletonRenderer` and `PolygonBatcher` if two color tinting is enabled. + * Added clipping support + * Added `VertexEffect` interface, instances of which can be set on `SkeletonRenderer`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect`, and the example which allows to set effects. + * Added `slotRangeStart` and `slotRangeEnd` parameters to `SkeletonRenderer#draw` and `SceneRenderer#drawSkeleton`. This allows you to render only a range of slots in the draw order. See `spine-ts/webgl/tests/test-slot-range.html` for an example. + +### Canvas backend + * Fixed renderer to work for 3.6 changes. Sadly, we can't support two color tinting via the Canvas API. + * Added support for shearing and non-uniform scaling inherited from parent bones. + * Added support for alpha tinting. + +### Three.js backend + * Fixed renderer to work with 3.6 changes. Two color tinting is not supported. + * Added clipping support + * Added `VertexEffect` interface, instances of which can be set on `SkeletonMesh`. Allows to modify vertices before submitting them to GPU. See `SwirlEffect`, `JitterEffect`. + * Added support for multi-page atlases + +### Widget backend + * Fixed WebGL context loss (see WebGL backend changes). Enabled automatically. + * Fixed renderer to work for 3.6 changes. Supports two color tinting & clipping (see WebGL backend changes for details). + * Added fields `atlasContent`, `atlasPagesContent`, and `jsonContent` to `WidgetConfiguration` allowing you to directly pass the contents of the `.atlas`, atlas page `.png` files, and the `.json` file without having to do a request. See `README.md` and the example for details. + * `SpineWidget.setAnimation()` now takes an additional optional parameter for callbacks when animations are completed/interrupted/etc. diff --git a/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md.meta b/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md.meta new file mode 100644 index 0000000..f420de7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/CHANGELOG.md.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3a206f1c4d5fd9e49a16634698666cfe +timeCreated: 1583165336 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor.meta b/Assets/CrazyZoo/Plugins/Spine/Editor.meta new file mode 100644 index 0000000..973e2aa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ad14d5a4cd7a0444286d315541ee0495 +folderAsset: yes +timeCreated: 1527569319 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef new file mode 100644 index 0000000..a11acd0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef @@ -0,0 +1,12 @@ +{ + "name": "spine-unity-editor", + "references": [ + "spine-unity" + ], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef.meta new file mode 100644 index 0000000..ebee9eb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity-editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 173464ddf4cdb6640a4dfa8a9281ad69 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity.meta new file mode 100644 index 0000000..c83b838 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 83fbec88df35fe34bab43a5dde6788af +folderAsset: yes +timeCreated: 1527569675 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor.meta new file mode 100644 index 0000000..3db0fd1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: f0e95036e72b08544a9d295dd4366f40 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types.meta new file mode 100644 index 0000000..5ce846b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: eb646ac6e394e534b80d5cac61478488 +folderAsset: yes +timeCreated: 1563305058 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs new file mode 100644 index 0000000..3c4c149 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs @@ -0,0 +1,185 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +using System.Reflection; +using System; + +namespace Spine.Unity.Editor { + using Editor = UnityEditor.Editor; + + [CustomEditor(typeof(AnimationReferenceAsset))] + public class AnimationReferenceAssetEditor : Editor { + + const string InspectorHelpText = "This is a Spine-Unity Animation Reference Asset. It serializes a reference to a SkeletonDataAsset and an animationName. It does not contain actual animation data. At runtime, it stores a reference to a Spine.Animation.\n\n" + + "You can use this in your AnimationState calls instead of a string animation name or a Spine.Animation reference. Use its implicit conversion into Spine.Animation or its .Animation property.\n\n" + + "Use AnimationReferenceAssets as an alternative to storing strings or finding animations and caching per component. This only does the lookup by string once, and allows you to store and manage animations via asset references."; + + readonly SkeletonInspectorPreview preview = new SkeletonInspectorPreview(); + FieldInfo skeletonDataAssetField = typeof(AnimationReferenceAsset).GetField("skeletonDataAsset", BindingFlags.NonPublic | BindingFlags.Instance); + FieldInfo nameField = typeof(AnimationReferenceAsset).GetField("animationName", BindingFlags.NonPublic | BindingFlags.Instance); + + AnimationReferenceAsset ThisAnimationReferenceAsset { get { return target as AnimationReferenceAsset; } } + SkeletonDataAsset ThisSkeletonDataAsset { get { return skeletonDataAssetField.GetValue(ThisAnimationReferenceAsset) as SkeletonDataAsset; } } + string ThisAnimationName { get { return nameField.GetValue(ThisAnimationReferenceAsset) as string; } } + + bool changeNextFrame = false; + SerializedProperty animationNameProperty; + SkeletonDataAsset lastSkeletonDataAsset; + SkeletonData lastSkeletonData; + + void OnEnable () { HandleOnEnablePreview(); } + void OnDestroy () { + HandleOnDestroyPreview(); + AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; + EditorApplication.update -= preview.HandleEditorUpdate; + } + + public override void OnInspectorGUI () { + animationNameProperty = animationNameProperty ?? serializedObject.FindProperty("animationName"); + string animationName = animationNameProperty.stringValue; + + Animation animation = null; + if (ThisSkeletonDataAsset != null) { + var skeletonData = ThisSkeletonDataAsset.GetSkeletonData(true); + if (skeletonData != null) { + animation = skeletonData.FindAnimation(animationName); + } + } + bool animationNotFound = (animation == null); + + if (changeNextFrame) { + changeNextFrame = false; + + if (ThisSkeletonDataAsset != lastSkeletonDataAsset || ThisSkeletonDataAsset.GetSkeletonData(true) != lastSkeletonData) { + preview.Clear(); + preview.Initialize(Repaint, ThisSkeletonDataAsset, LastSkinName); + + if (animationNotFound) { + animationNameProperty.stringValue = ""; + preview.ClearAnimationSetupPose(); + } + } + + preview.ClearAnimationSetupPose(); + + if (!string.IsNullOrEmpty(animationNameProperty.stringValue)) + preview.PlayPauseAnimation(animationNameProperty.stringValue, true); + } + + lastSkeletonDataAsset = ThisSkeletonDataAsset; + lastSkeletonData = ThisSkeletonDataAsset.GetSkeletonData(true); + + //EditorGUILayout.HelpBox(AnimationReferenceAssetEditor.InspectorHelpText, MessageType.Info, true); + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + DrawDefaultInspector(); + if (EditorGUI.EndChangeCheck()) { + changeNextFrame = true; + } + + // Draw extra info below default inspector. + EditorGUILayout.Space(); + if (ThisSkeletonDataAsset == null) { + EditorGUILayout.HelpBox("SkeletonDataAsset is missing.", MessageType.Error); + } else if (string.IsNullOrEmpty(animationName)) { + EditorGUILayout.HelpBox("No animation selected.", MessageType.Warning); + } else if (animationNotFound) { + EditorGUILayout.HelpBox(string.Format("Animation named {0} was not found for this Skeleton.", animationNameProperty.stringValue), MessageType.Warning); + } else { + using (new SpineInspectorUtility.BoxScope()) { + if (!string.Equals(AssetUtility.GetPathSafeName(animationName), ThisAnimationReferenceAsset.name, System.StringComparison.OrdinalIgnoreCase)) + EditorGUILayout.HelpBox("Animation name value does not match this asset's name. Inspectors using this asset may be misleading.", MessageType.None); + + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(animationName, SpineEditorUtilities.Icons.animation)); + if (animation != null) { + EditorGUILayout.LabelField(string.Format("Timelines: {0}", animation.Timelines.Count)); + EditorGUILayout.LabelField(string.Format("Duration: {0} sec", animation.Duration)); + } + } + } + } + + #region Preview Handlers + string TargetAssetGUID { get { return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(ThisSkeletonDataAsset)); } } + string LastSkinKey { get { return TargetAssetGUID + "_lastSkin"; } } + string LastSkinName { get { return EditorPrefs.GetString(LastSkinKey, ""); } } + + void HandleOnEnablePreview () { + if (ThisSkeletonDataAsset != null && ThisSkeletonDataAsset.skeletonJSON == null) + return; + SpineEditorUtilities.ConfirmInitialization(); + + // This handles the case where the managed editor assembly is unloaded before recompilation when code changes. + AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; + AppDomain.CurrentDomain.DomainUnload += OnDomainUnload; + + preview.Initialize(this.Repaint, ThisSkeletonDataAsset, LastSkinName); + preview.PlayPauseAnimation(ThisAnimationName, true); + preview.OnSkinChanged -= HandleOnSkinChanged; + preview.OnSkinChanged += HandleOnSkinChanged; + EditorApplication.update -= preview.HandleEditorUpdate; + EditorApplication.update += preview.HandleEditorUpdate; + } + + private void OnDomainUnload (object sender, EventArgs e) { + OnDestroy(); + } + + private void HandleOnSkinChanged (string skinName) { + EditorPrefs.SetString(LastSkinKey, skinName); + preview.PlayPauseAnimation(ThisAnimationName, true); + } + + void HandleOnDestroyPreview () { + EditorApplication.update -= preview.HandleEditorUpdate; + preview.OnDestroy(); + } + + override public bool HasPreviewGUI () { + if (serializedObject.isEditingMultipleObjects) return false; + return ThisSkeletonDataAsset != null && ThisSkeletonDataAsset.GetSkeletonData(true) != null; + } + + override public void OnInteractivePreviewGUI (Rect r, GUIStyle background) { + preview.Initialize(this.Repaint, ThisSkeletonDataAsset); + preview.HandleInteractivePreviewGUI(r, background); + } + + public override GUIContent GetPreviewTitle () { return SpineInspectorUtility.TempContent("Preview"); } + public override void OnPreviewSettings () { preview.HandleDrawSettings(); } + public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) { return preview.GetStaticPreview(width, height); } + #endregion + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs.meta new file mode 100644 index 0000000..58c7aaa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/AnimationReferenceAssetEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9511532e80feed24881a5863f5485446 +timeCreated: 1523316585 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs new file mode 100644 index 0000000..5cb6eca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs @@ -0,0 +1,1247 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#define SPINE_SKELETON_MECANIM + + #if (UNITY_2017_4 || UNITY_2018_1_OR_NEWER ) + #define SPINE_UNITY_2018_PREVIEW_API + #endif + + +using System; +using System.Reflection; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +using CompatibilityProblemInfo = Spine.Unity.SkeletonDataCompatibility.CompatibilityProblemInfo; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + using Icons = SpineEditorUtilities.Icons; + using Animation = Spine.Animation; + + [CustomEditor(typeof(SkeletonDataAsset)), CanEditMultipleObjects] + public class SkeletonDataAssetInspector : UnityEditor.Editor { + internal static bool showAnimationStateData = true; + internal static bool showAnimationList = true; + internal static bool showSlotList = false; + internal static bool showAttachments = false; + + SerializedProperty atlasAssets, skeletonJSON, scale, fromAnimation, toAnimation, duration, defaultMix; + SerializedProperty skeletonDataModifiers; + SerializedProperty blendModeMaterials; + #if SPINE_TK2D + SerializedProperty spriteCollection; + #endif + + #if SPINE_SKELETON_MECANIM + static bool isMecanimExpanded = false; + SerializedProperty controller; + #endif + + SkeletonDataAsset targetSkeletonDataAsset; + SkeletonData targetSkeletonData; + + readonly List warnings = new List(); + CompatibilityProblemInfo compatibilityProblemInfo = null; + readonly SkeletonInspectorPreview preview = new SkeletonInspectorPreview(); + + GUIStyle activePlayButtonStyle, idlePlayButtonStyle; + readonly GUIContent DefaultMixLabel = new GUIContent("Default Mix Duration", "Sets 'SkeletonDataAsset.defaultMix' in the asset and 'AnimationState.data.defaultMix' at runtime load time."); + + string TargetAssetGUID { get { return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(targetSkeletonDataAsset)); } } + string LastSkinKey { get { return TargetAssetGUID + "_lastSkin"; } } + string LastSkinName { get { return EditorPrefs.GetString(LastSkinKey, ""); } } + + void OnEnable () { + InitializeEditor(); + } + + void OnDestroy () { + HandleOnDestroyPreview(); + AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; + EditorApplication.update -= preview.HandleEditorUpdate; + } + + private void OnDomainUnload (object sender, EventArgs e) { + OnDestroy(); + } + + public void UpdateSkeletonData () { + preview.Clear(); + InitializeEditor(); + if (targetSkeletonDataAsset) + EditorUtility.SetDirty(targetSkeletonDataAsset); + } + + void InitializeEditor () { + SpineEditorUtilities.ConfirmInitialization(); + targetSkeletonDataAsset = (SkeletonDataAsset)target; + + bool newAtlasAssets = atlasAssets == null; + if (newAtlasAssets) atlasAssets = serializedObject.FindProperty("atlasAssets"); + skeletonJSON = serializedObject.FindProperty("skeletonJSON"); + scale = serializedObject.FindProperty("scale"); + fromAnimation = serializedObject.FindProperty("fromAnimation"); + toAnimation = serializedObject.FindProperty("toAnimation"); + duration = serializedObject.FindProperty("duration"); + defaultMix = serializedObject.FindProperty("defaultMix"); + + skeletonDataModifiers = serializedObject.FindProperty("skeletonDataModifiers"); + blendModeMaterials = serializedObject.FindProperty("blendModeMaterials"); + + #if SPINE_SKELETON_MECANIM + controller = serializedObject.FindProperty("controller"); + #endif + + #if SPINE_TK2D + if (newAtlasAssets) atlasAssets.isExpanded = false; + spriteCollection = serializedObject.FindProperty("spriteCollection"); + #else + // Analysis disable once ConvertIfToOrExpression + if (newAtlasAssets) atlasAssets.isExpanded = true; + #endif + + // This handles the case where the managed editor assembly is unloaded before recompilation when code changes. + AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload; + AppDomain.CurrentDomain.DomainUnload += OnDomainUnload; + + EditorApplication.update -= preview.HandleEditorUpdate; + EditorApplication.update += preview.HandleEditorUpdate; + preview.OnSkinChanged -= HandlePreviewSkinChanged; + preview.OnSkinChanged += HandlePreviewSkinChanged; + + PopulateWarnings(); + if (targetSkeletonDataAsset.skeletonJSON == null) { + targetSkeletonData = null; + return; + } + + targetSkeletonData = NoProblems() ? targetSkeletonDataAsset.GetSkeletonData(false) : null; + + if (targetSkeletonData != null && NoProblems()) { + preview.Initialize(this.Repaint, targetSkeletonDataAsset, this.LastSkinName); + } + + } + + void Clear () { + preview.Clear(); + targetSkeletonDataAsset.Clear(); + targetSkeletonData = null; + } + + override public void OnInspectorGUI () { + // Multi-Editing + if (serializedObject.isEditingMultipleObjects) { + OnInspectorGUIMulti(); + return; + } + + { // Lazy initialization because accessing EditorStyles values in OnEnable during a recompile causes UnityEditor to throw null exceptions. (Unity 5.3.5) + idlePlayButtonStyle = idlePlayButtonStyle ?? new GUIStyle(EditorStyles.miniButton); + if (activePlayButtonStyle == null) { + activePlayButtonStyle = new GUIStyle(idlePlayButtonStyle); + activePlayButtonStyle.normal.textColor = Color.red; + } + } + + serializedObject.Update(); + + // Header + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(target.name + " (SkeletonDataAsset)", Icons.spine), EditorStyles.whiteLargeLabel); + if (targetSkeletonData != null) EditorGUILayout.LabelField("(Drag and Drop to instantiate.)", EditorStyles.miniLabel); + + // Main Serialized Fields + using (var changeCheck = new EditorGUI.ChangeCheckScope()) { + using (new SpineInspectorUtility.BoxScope()) + DrawSkeletonDataFields(); + + if (compatibilityProblemInfo != null) + return; + + using (new SpineInspectorUtility.BoxScope()) { + DrawAtlasAssetsFields(); + HandleAtlasAssetsNulls(); + } + + if (changeCheck.changed) { + if (serializedObject.ApplyModifiedProperties()) { + this.Clear(); + this.InitializeEditor(); + + if (SpineEditorUtilities.Preferences.autoReloadSceneSkeletons) + SpineEditorUtilities.DataReloadHandler.ReloadSceneSkeletonComponents(targetSkeletonDataAsset); + + return; + } + } + } + + // Unity Quirk: Some code depends on valid preview. If preview is initialized elsewhere, this can cause contents to change between Layout and Repaint events, causing GUILayout control count errors. + if (NoProblems()) + preview.Initialize(this.Repaint, targetSkeletonDataAsset, this.LastSkinName); + + if (targetSkeletonData != null) { + GUILayout.Space(20f); + + using (new SpineInspectorUtility.BoxScope(false)) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Mix Settings", Icons.animationRoot), EditorStyles.boldLabel); + DrawAnimationStateInfo(); + EditorGUILayout.Space(); + } + + EditorGUILayout.LabelField("Preview", EditorStyles.boldLabel); + DrawAnimationList(); + if (targetSkeletonData.Animations.Count > 0) { + const string AnimationReferenceButtonText = "Create Animation Reference Assets"; + const string AnimationReferenceTooltipText = "AnimationReferenceAsset acts as Unity asset for a reference to a Spine.Animation. This can be used in inspectors.\n\nIt serializes a reference to a SkeletonDataAsset and an animationName.\n\nAt runtime, a reference to its Spine.Animation is loaded and cached into the object to be used as needed. This skips the need to find and cache animation references in individual MonoBehaviours."; + if (GUILayout.Button(SpineInspectorUtility.TempContent(AnimationReferenceButtonText, Icons.animationRoot, AnimationReferenceTooltipText), GUILayout.Width(250), GUILayout.Height(26))) { + CreateAnimationReferenceAssets(); + } + } + EditorGUILayout.Space(); + DrawSlotList(); + EditorGUILayout.Space(); + + DrawUnityTools(); + + } else { + #if !SPINE_TK2D + // Draw Reimport Button + using (new EditorGUI.DisabledGroupScope(skeletonJSON.objectReferenceValue == null)) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Attempt Reimport", Icons.warning))) + DoReimport(); + } + #else + EditorGUILayout.HelpBox("Couldn't load SkeletonData.", MessageType.Error); + #endif + + DrawWarningList(); + } + + if (!Application.isPlaying) + serializedObject.ApplyModifiedProperties(); + } + + void CreateAnimationReferenceAssets () { + const string AssetFolderName = "ReferenceAssets"; + string parentFolder = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(targetSkeletonDataAsset)); + string dataPath = parentFolder + "/" + AssetFolderName; + if (!AssetDatabase.IsValidFolder(dataPath)) { + AssetDatabase.CreateFolder(parentFolder, AssetFolderName); + } + + FieldInfo nameField = typeof(AnimationReferenceAsset).GetField("animationName", BindingFlags.NonPublic | BindingFlags.Instance); + FieldInfo skeletonDataAssetField = typeof(AnimationReferenceAsset).GetField("skeletonDataAsset", BindingFlags.NonPublic | BindingFlags.Instance); + foreach (var animation in targetSkeletonData.Animations) { + string assetPath = string.Format("{0}/{1}.asset", dataPath, AssetUtility.GetPathSafeName(animation.Name)); + AnimationReferenceAsset existingAsset = AssetDatabase.LoadAssetAtPath(assetPath); + if (existingAsset == null) { + AnimationReferenceAsset newAsset = ScriptableObject.CreateInstance(); + skeletonDataAssetField.SetValue(newAsset, targetSkeletonDataAsset); + nameField.SetValue(newAsset, animation.Name); + AssetDatabase.CreateAsset(newAsset, assetPath); + } + } + + var folderObject = AssetDatabase.LoadAssetAtPath(dataPath, typeof(UnityEngine.Object)); + if (folderObject != null) { + Selection.activeObject = folderObject; + EditorGUIUtility.PingObject(folderObject); + } + } + + void OnInspectorGUIMulti () { + + // Skeleton data file field. + using (new SpineInspectorUtility.BoxScope()) { + EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine)); + EditorGUILayout.DelayedFloatField(scale); //EditorGUILayout.PropertyField(scale); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(skeletonDataModifiers, true); + + DrawBlendModeMaterialProperties(); + } + + // Texture source field. + using (new SpineInspectorUtility.BoxScope()) { + EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel); + #if !SPINE_TK2D + EditorGUILayout.PropertyField(atlasAssets, true); + #else + using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) { + EditorGUILayout.PropertyField(atlasAssets, true); + } + EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(spriteCollection, true); + #endif + } + + // Mix settings. + using (new SpineInspectorUtility.BoxScope()) { + EditorGUILayout.LabelField("Mix Settings", EditorStyles.boldLabel); + SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160); + EditorGUILayout.Space(); + } + + } + + void DrawBlendModeMaterialProperties () { + if (skeletonDataModifiers.arraySize > 0) { + EditorGUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight + 5)); + EditorGUILayout.PrefixLabel("Blend Modes"); + if (GUILayout.Button(new GUIContent("Upgrade", "Upgrade BlendModeMaterialAsset to built-in BlendModeMaterials."), EditorStyles.miniButton, GUILayout.Width(65f))) { + foreach (SkeletonDataAsset skeletonData in targets) { + BlendModeMaterialsUtility.UpgradeBlendModeMaterials(skeletonData); + } + } + EditorGUILayout.EndHorizontal(); + } + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(blendModeMaterials, true); + if (EditorGUI.EndChangeCheck()) { + serializedObject.ApplyModifiedProperties(); + foreach (SkeletonDataAsset skeletonData in targets) { + BlendModeMaterialsUtility.UpdateBlendModeMaterials(skeletonData); + } + } + } + + void DrawSkeletonDataFields () { + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel); + if (targetSkeletonData != null) { + var sd = targetSkeletonData; + string m = string.Format("{8} - {0} {1}\nBones: {2}\nConstraints: \n {5} IK \n {6} Path \n {7} Transform\n\nSlots: {3}\nSkins: {4}\n\nAnimations: {9}", + sd.Version, string.IsNullOrEmpty(sd.Version) ? "" : "export ", sd.Bones.Count, sd.Slots.Count, sd.Skins.Count, sd.IkConstraints.Count, sd.PathConstraints.Count, sd.TransformConstraints.Count, skeletonJSON.objectReferenceValue.name, sd.Animations.Count); + EditorGUILayout.LabelField(GUIContent.none, new GUIContent(Icons.info, m), GUILayout.Width(30f)); + } + } + EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine)); + + if (compatibilityProblemInfo != null) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(compatibilityProblemInfo.DescriptionString(), Icons.warning), GUILayout.Height(52)); + return; + } + + EditorGUILayout.DelayedFloatField(scale); //EditorGUILayout.PropertyField(scale); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(skeletonDataModifiers, true); + + DrawBlendModeMaterialProperties(); + } + + void DrawAtlasAssetsFields () { + EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel); + #if !SPINE_TK2D + EditorGUILayout.PropertyField(atlasAssets, true); + #else + using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) { + EditorGUILayout.PropertyField(atlasAssets, true); + } + EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(spriteCollection, true); + #endif + + if (atlasAssets.arraySize == 0) + EditorGUILayout.HelpBox("AtlasAssets array is empty. Skeleton's attachments will load without being mapped to images.", MessageType.Info); + } + + void HandleAtlasAssetsNulls () { + bool hasNulls = false; + foreach (var a in targetSkeletonDataAsset.atlasAssets) { + if (a == null) { + hasNulls = true; + break; + } + } + if (hasNulls) { + if (targetSkeletonDataAsset.atlasAssets.Length == 1) { + EditorGUILayout.HelpBox("Atlas array cannot have null entries!", MessageType.None); + } + else { + EditorGUILayout.HelpBox("Atlas array should not have null entries!", MessageType.Error); + if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Remove null entries"))) { + var trimmedAtlasAssets = new List(); + foreach (var a in targetSkeletonDataAsset.atlasAssets) { + if (a != null) + trimmedAtlasAssets.Add(a); + } + targetSkeletonDataAsset.atlasAssets = trimmedAtlasAssets.ToArray(); + serializedObject.Update(); + } + } + } + } + + void DrawAnimationStateInfo () { + using (new SpineInspectorUtility.IndentScope()) + showAnimationStateData = EditorGUILayout.Foldout(showAnimationStateData, "Animation State Data"); + + if (!showAnimationStateData) + return; + + using (var cc = new EditorGUI.ChangeCheckScope()) { + using (new SpineInspectorUtility.IndentScope()) + SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160); + + + if (fromAnimation.arraySize > 0) { + using (new SpineInspectorUtility.IndentScope()) { + EditorGUILayout.LabelField("Custom Mix Durations", EditorStyles.boldLabel); + } + + for (int i = 0; i < fromAnimation.arraySize; i++) { + SerializedProperty from = fromAnimation.GetArrayElementAtIndex(i); + SerializedProperty to = toAnimation.GetArrayElementAtIndex(i); + SerializedProperty durationProp = duration.GetArrayElementAtIndex(i); + using (new EditorGUILayout.HorizontalScope()) { + GUILayout.Space(16f); // Space instead of EditorGUIUtility.indentLevel. indentLevel will add the space on every field. + EditorGUILayout.PropertyField(from, GUIContent.none); + //EditorGUILayout.LabelField(">", EditorStyles.miniLabel, GUILayout.Width(9f)); + EditorGUILayout.PropertyField(to, GUIContent.none); + //GUILayout.Space(5f); + durationProp.floatValue = EditorGUILayout.FloatField(durationProp.floatValue, GUILayout.MinWidth(25f), GUILayout.MaxWidth(60f)); + if (GUILayout.Button("Delete", EditorStyles.miniButton)) { + duration.DeleteArrayElementAtIndex(i); + toAnimation.DeleteArrayElementAtIndex(i); + fromAnimation.DeleteArrayElementAtIndex(i); + } + } + } + } + + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + if (GUILayout.Button("Add Custom Mix")) { + duration.arraySize++; + toAnimation.arraySize++; + fromAnimation.arraySize++; + } + EditorGUILayout.Space(); + } + + if (cc.changed) { + targetSkeletonDataAsset.FillStateData(); + EditorUtility.SetDirty(targetSkeletonDataAsset); + serializedObject.ApplyModifiedProperties(); + } + } + } + + void DrawAnimationList () { + showAnimationList = EditorGUILayout.Foldout(showAnimationList, SpineInspectorUtility.TempContent(string.Format("Animations [{0}]", targetSkeletonData.Animations.Count), Icons.animationRoot)); + if (!showAnimationList) + return; + + bool isPreviewWindowOpen = preview.IsValid; + + if (isPreviewWindowOpen) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Setup Pose", Icons.skeleton), GUILayout.Width(105), GUILayout.Height(18))) { + preview.ClearAnimationSetupPose(); + preview.RefreshOnNextUpdate(); + } + } else { + EditorGUILayout.HelpBox("Animations can be previewed if you expand the Preview window below.", MessageType.Info); + } + + EditorGUILayout.LabelField("Name", " Duration"); + //bool nonessential = targetSkeletonData.ImagesPath != null; // Currently the only way to determine if skeleton data has nonessential data. (Spine 3.6) + //float fps = targetSkeletonData.Fps; + //if (nonessential && fps == 0) fps = 30; + + var activeTrack = preview.ActiveTrack; + foreach (Animation animation in targetSkeletonData.Animations) { + using (new GUILayout.HorizontalScope()) { + if (isPreviewWindowOpen) { + bool active = activeTrack != null && activeTrack.Animation == animation; + //bool sameAndPlaying = active && activeTrack.TimeScale > 0f; + if (GUILayout.Button("\u25BA", active ? activePlayButtonStyle : idlePlayButtonStyle, GUILayout.Width(24))) { + preview.PlayPauseAnimation(animation.Name, true); + activeTrack = preview.ActiveTrack; + } + } else { + GUILayout.Label("-", GUILayout.Width(24)); + } + //string frameCountString = (fps > 0) ? ("(" + (Mathf.RoundToInt(animation.Duration * fps)) + ")").PadLeft(12, ' ') : string.Empty; + //EditorGUILayout.LabelField(new GUIContent(animation.Name, Icons.animation), SpineInspectorUtility.TempContent(animation.Duration.ToString("f3") + "s" + frameCountString)); + string durationString = animation.Duration.ToString("f3"); + EditorGUILayout.LabelField(new GUIContent(animation.Name, Icons.animation), SpineInspectorUtility.TempContent(durationString + "s", tooltip: string.Format("{0} seconds\n{1} timelines", durationString, animation.Timelines.Count))); + } + } + } + + void DrawSlotList () { + showSlotList = EditorGUILayout.Foldout(showSlotList, SpineInspectorUtility.TempContent("Slots", Icons.slotRoot)); + + if (!showSlotList) return; + if (!preview.IsValid) return; + + var defaultSkin = targetSkeletonData.DefaultSkin; + Skin skin = preview.Skeleton.Skin ?? defaultSkin; + + using (new SpineInspectorUtility.IndentScope()) { + + using (new EditorGUILayout.HorizontalScope()) { + showAttachments = EditorGUILayout.ToggleLeft("Show Attachments", showAttachments, GUILayout.MaxWidth(150f)); + if (showAttachments) { + if (skin != null) { + int attachmentCount = skin.Attachments.Count; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("{0} ({1} attachment{2})", skin.Name, attachmentCount, SpineInspectorUtility.PluralThenS(attachmentCount)), Icons.skin)); + } + + } + } + + var slotAttachments = new List(); + var defaultSkinAttachments = new List(); + var slotsItems = preview.Skeleton.Slots.Items; + for (int i = preview.Skeleton.Slots.Count - 1; i >= 0; i--) { + Slot slot = slotsItems[i]; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot)); + if (showAttachments) { + slotAttachments.Clear(); + defaultSkinAttachments.Clear(); + + using (new SpineInspectorUtility.IndentScope()) { + { + skin.GetAttachments(i, slotAttachments); + if (defaultSkin != null) { + if (skin != defaultSkin) { + defaultSkin.GetAttachments(i, slotAttachments); + defaultSkin.GetAttachments(i, defaultSkinAttachments); + } + else { + defaultSkin.GetAttachments(i, defaultSkinAttachments); + } + } + } + + for (int a = 0; a < slotAttachments.Count; a++) { + var skinEntry = slotAttachments[a]; + Attachment attachment = skinEntry.Attachment; + string attachmentName = skinEntry.Name; + bool attachmentIsFromSkin = !defaultSkinAttachments.Contains(skinEntry); + + Texture2D attachmentTypeIcon = Icons.GetAttachmentIcon(attachment); + bool initialState = slot.Attachment == attachment; + + Texture2D iconToUse = attachmentIsFromSkin ? Icons.skinPlaceholder : attachmentTypeIcon; + bool toggled = EditorGUILayout.ToggleLeft(SpineInspectorUtility.TempContent(attachmentName, iconToUse), slot.Attachment == attachment, GUILayout.MinWidth(150f)); + + if (attachmentIsFromSkin) { + Rect extraIconRect = GUILayoutUtility.GetLastRect(); + extraIconRect.x += extraIconRect.width - (attachmentTypeIcon.width * 2f); + extraIconRect.width = attachmentTypeIcon.width; + extraIconRect.height = attachmentTypeIcon.height; + GUI.DrawTexture(extraIconRect, attachmentTypeIcon); + } + + if (toggled != initialState) { + slot.Attachment = toggled ? attachment : null; + preview.RefreshOnNextUpdate(); + } + } + } + + } + } + } + + } + + void DrawUnityTools () { + #if SPINE_SKELETON_MECANIM + using (new SpineInspectorUtility.BoxScope()) { + isMecanimExpanded = EditorGUILayout.Foldout(isMecanimExpanded, SpineInspectorUtility.TempContent("SkeletonMecanim", SpineInspectorUtility.UnityIcon())); + if (isMecanimExpanded) { + using (new SpineInspectorUtility.IndentScope()) { + EditorGUILayout.PropertyField(controller, SpineInspectorUtility.TempContent("Controller", SpineInspectorUtility.UnityIcon())); + if (controller.objectReferenceValue == null) { + + // Generate Mecanim Controller Button + using (new GUILayout.HorizontalScope()) { + GUILayout.Space(EditorGUIUtility.labelWidth); + if (GUILayout.Button(SpineInspectorUtility.TempContent("Generate Mecanim Controller"), GUILayout.Height(20))) + SkeletonBaker.GenerateMecanimAnimationClips(targetSkeletonDataAsset); + } + EditorGUILayout.HelpBox("SkeletonMecanim is the Mecanim alternative to SkeletonAnimation.\nIt is not required.", MessageType.Info); + + } else { + + // Update AnimationClips button. + using (new GUILayout.HorizontalScope()) { + GUILayout.Space(EditorGUIUtility.labelWidth); + if (GUILayout.Button(SpineInspectorUtility.TempContent("Force Update AnimationClips"), GUILayout.Height(20))) + SkeletonBaker.GenerateMecanimAnimationClips(targetSkeletonDataAsset); + } + + } + } + } + } + #endif + } + + void DrawWarningList () { + foreach (string line in warnings) + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning)); + } + + void PopulateWarnings () { + warnings.Clear(); + compatibilityProblemInfo = null; + + if (skeletonJSON.objectReferenceValue == null) { + warnings.Add("Missing Skeleton JSON"); + } else { + var fieldValue = (TextAsset)skeletonJSON.objectReferenceValue; + string problemDescription = null; + if (!AssetUtility.IsSpineData(fieldValue, out compatibilityProblemInfo, ref problemDescription)) { + if (problemDescription != null) + warnings.Add(problemDescription); + else + warnings.Add("Skeleton data file is not a valid Spine JSON or binary file."); + } else { + #if SPINE_TK2D + bool searchForSpineAtlasAssets = true; + bool isSpriteCollectionNull = spriteCollection.objectReferenceValue == null; + if (!isSpriteCollectionNull) searchForSpineAtlasAssets = false; + #else + // Analysis disable once ConvertToConstant.Local + bool searchForSpineAtlasAssets = true; + #endif + + if (searchForSpineAtlasAssets) { + bool detectedNullAtlasEntry = false; + var atlasList = new List(); + var actualAtlasAssets = targetSkeletonDataAsset.atlasAssets; + + for (int i = 0; i < actualAtlasAssets.Length; i++) { + if (actualAtlasAssets[i] == null) { + detectedNullAtlasEntry = true; + break; + } else { + if (actualAtlasAssets[i].MaterialCount > 0) + atlasList.Add(actualAtlasAssets[i].GetAtlas()); + } + } + + if (detectedNullAtlasEntry) { + warnings.Add("AtlasAsset elements should not be null."); + } else { + List missingPaths = null; + if (atlasAssets.arraySize > 0) { + missingPaths = AssetUtility.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue)); + foreach (var atlas in atlasList) { + if (atlas == null) + continue; + for (int i = 0; i < missingPaths.Count; i++) { + if (atlas.FindRegion(missingPaths[i]) != null) { + missingPaths.RemoveAt(i); + i--; + } + } + } + + #if SPINE_TK2D + if (missingPaths.Count > 0) + warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets."); + #endif + } + + if (missingPaths != null) { + foreach (string missingRegion in missingPaths) + warnings.Add(string.Format("Missing Region: '{0}'", missingRegion)); + } + + } + } + + } + } + } + + void DoReimport () { + AssetUtility.ImportSpineContent(new [] { AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue) }, null, true); + preview.Clear(); + InitializeEditor(); + EditorUtility.SetDirty(targetSkeletonDataAsset); + } + + void HandlePreviewSkinChanged (string skinName) { + EditorPrefs.SetString(LastSkinKey, skinName); + } + + bool NoProblems() { + return warnings.Count == 0 && compatibilityProblemInfo == null; + } + + #region Preview Handlers + void HandleOnDestroyPreview () { + EditorApplication.update -= preview.HandleEditorUpdate; + preview.OnDestroy(); + } + + override public bool HasPreviewGUI () { + if (serializedObject.isEditingMultipleObjects) + return false; + + for (int i = 0; i < atlasAssets.arraySize; i++) { + var prop = atlasAssets.GetArrayElementAtIndex(i); + if (prop.objectReferenceValue == null) + return false; + } + + return skeletonJSON.objectReferenceValue != null; + } + + override public void OnInteractivePreviewGUI (Rect r, GUIStyle background) { + if (NoProblems()) { + preview.Initialize(this.Repaint, targetSkeletonDataAsset, this.LastSkinName); + preview.HandleInteractivePreviewGUI(r, background); + } + } + + override public GUIContent GetPreviewTitle () { return SpineInspectorUtility.TempContent("Preview"); } + public override void OnPreviewSettings () { preview.HandleDrawSettings(); } + public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) { return preview.GetStaticPreview(width, height); } + #endregion + } + + internal class SkeletonInspectorPreview { + Color OriginColor = new Color(0.3f, 0.3f, 0.3f, 1); + static readonly int SliderHash = "Slider".GetHashCode(); + + SkeletonDataAsset skeletonDataAsset; + SkeletonData skeletonData; + + SkeletonAnimation skeletonAnimation; + GameObject previewGameObject; + internal bool requiresRefresh; + float animationLastTime; + + static float CurrentTime { get { return (float)EditorApplication.timeSinceStartup; } } + + Action Repaint; + public event Action OnSkinChanged; + + Texture previewTexture; + PreviewRenderUtility previewRenderUtility; + Camera PreviewUtilityCamera { + get { + if (previewRenderUtility == null) return null; + #if UNITY_2017_1_OR_NEWER + return previewRenderUtility.camera; + #else + return previewRenderUtility.m_Camera; + #endif + } + } + + static Vector3 lastCameraPositionGoal; + static float lastCameraOrthoGoal; + float cameraOrthoGoal = 1; + Vector3 cameraPositionGoal = new Vector3(0, 0, -10); + double cameraAdjustEndFrame = 0; + + List currentAnimationEvents = new List(); + List currentAnimationEventTimes = new List(); + List currentAnimationEventTooltips = new List(); + + public bool IsValid { get { return skeletonAnimation != null && skeletonAnimation.valid; } } + + public Skeleton Skeleton { get { return IsValid ? skeletonAnimation.Skeleton : null; } } + + public float TimeScale { + get { return IsValid ? skeletonAnimation.timeScale : 1f; } + set { if (IsValid) skeletonAnimation.timeScale = value; } + } + + public bool IsPlayingAnimation { get { + if (!IsValid) return false; + var currentTrack = skeletonAnimation.AnimationState.GetCurrent(0); + return currentTrack != null && currentTrack.TimeScale > 0; + } + } + + public TrackEntry ActiveTrack { get { return IsValid ? skeletonAnimation.AnimationState.GetCurrent(0) : null; } } + + public Vector3 PreviewCameraPosition { + get { return PreviewUtilityCamera.transform.position; } + set { PreviewUtilityCamera.transform.position = value; } + } + + public void HandleDrawSettings () { + const float SliderWidth = 150; + const float SliderSnap = 0.25f; + const float SliderMin = 0f; + const float SliderMax = 2f; + + if (IsValid) { + float timeScale = GUILayout.HorizontalSlider(TimeScale, SliderMin, SliderMax, GUILayout.MaxWidth(SliderWidth)); + timeScale = Mathf.RoundToInt(timeScale / SliderSnap) * SliderSnap; + TimeScale = timeScale; + } + } + + public void HandleEditorUpdate () { + AdjustCamera(); + if (IsPlayingAnimation) { + RefreshOnNextUpdate(); + Repaint(); + } else if (requiresRefresh) { + Repaint(); + } + } + + public void Initialize (Action repaintCallback, SkeletonDataAsset skeletonDataAsset, string skinName = "") { + if (skeletonDataAsset == null) return; + if (skeletonDataAsset.GetSkeletonData(false) == null) { + DestroyPreviewGameObject(); + return; + } + + this.Repaint = repaintCallback; + this.skeletonDataAsset = skeletonDataAsset; + this.skeletonData = skeletonDataAsset.GetSkeletonData(false); + + if (skeletonData == null) { + DestroyPreviewGameObject(); + return; + } + + const int PreviewLayer = 30; + const int PreviewCameraCullingMask = 1 << PreviewLayer; + + if (previewRenderUtility == null) { + previewRenderUtility = new PreviewRenderUtility(true); + animationLastTime = CurrentTime; + + { + var c = this.PreviewUtilityCamera; + c.orthographic = true; + c.cullingMask = PreviewCameraCullingMask; + c.nearClipPlane = 0.01f; + c.farClipPlane = 1000f; + c.orthographicSize = lastCameraOrthoGoal; + c.transform.position = lastCameraPositionGoal; + } + + DestroyPreviewGameObject(); + } + + if (previewGameObject == null) { + try { + previewGameObject = EditorInstantiation.InstantiateSkeletonAnimation(skeletonDataAsset, skinName, useObjectFactory:false).gameObject; + + if (previewGameObject != null) { + previewGameObject.hideFlags = HideFlags.HideAndDontSave; + previewGameObject.layer = PreviewLayer; + skeletonAnimation = previewGameObject.GetComponent(); + skeletonAnimation.initialSkinName = skinName; + skeletonAnimation.LateUpdate(); + previewGameObject.GetComponent().enabled = false; + + #if SPINE_UNITY_2018_PREVIEW_API + previewRenderUtility.AddSingleGO(previewGameObject); + #endif + } + + if (this.ActiveTrack != null) cameraAdjustEndFrame = EditorApplication.timeSinceStartup + skeletonAnimation.AnimationState.GetCurrent(0).Alpha; + AdjustCameraGoals(); + } catch { + DestroyPreviewGameObject(); + } + + RefreshOnNextUpdate(); + } + } + + public void HandleInteractivePreviewGUI (Rect r, GUIStyle background) { + if (Event.current.type == EventType.Repaint) { + if (requiresRefresh) { + previewRenderUtility.BeginPreview(r, background); + DoRenderPreview(true); + previewTexture = previewRenderUtility.EndPreview(); + requiresRefresh = false; + } + if (previewTexture != null) + GUI.DrawTexture(r, previewTexture, ScaleMode.StretchToFill, false); + } + + DrawSkinToolbar(r); + //DrawSetupPoseButton(r); + DrawTimeBar(r); + HandleMouseScroll(r); + } + + public Texture2D GetStaticPreview (int width, int height) { + var c = this.PreviewUtilityCamera; + if (c == null) + return null; + + RefreshOnNextUpdate(); + AdjustCameraGoals(); + c.orthographicSize = cameraOrthoGoal / 2; + c.transform.position = cameraPositionGoal; + previewRenderUtility.BeginStaticPreview(new Rect(0, 0, width, height)); + DoRenderPreview(false); + var tex = previewRenderUtility.EndStaticPreview(); + + return tex; + } + + public void DoRenderPreview (bool drawHandles) { + if (this.PreviewUtilityCamera.activeTexture == null || this.PreviewUtilityCamera.targetTexture == null) + return; + + GameObject go = previewGameObject; + if (requiresRefresh && go != null) { + var renderer = go.GetComponent(); + renderer.enabled = true; + + + if (!EditorApplication.isPlaying) { + float current = CurrentTime; + float deltaTime = (current - animationLastTime); + skeletonAnimation.Update(deltaTime); + animationLastTime = current; + skeletonAnimation.LateUpdate(); + } + + var thisPreviewUtilityCamera = this.PreviewUtilityCamera; + + if (drawHandles) { + Handles.SetCamera(thisPreviewUtilityCamera); + Handles.color = OriginColor; + + // Draw Cross + float scale = skeletonDataAsset.scale; + float cl = 1000 * scale; + Handles.DrawLine(new Vector3(-cl, 0), new Vector3(cl, 0)); + Handles.DrawLine(new Vector3(0, cl), new Vector3(0, -cl)); + } + + thisPreviewUtilityCamera.Render(); + + if (drawHandles) { + Handles.SetCamera(thisPreviewUtilityCamera); + SpineHandles.DrawBoundingBoxes(skeletonAnimation.transform, skeletonAnimation.skeleton); + if (SkeletonDataAssetInspector.showAttachments) + SpineHandles.DrawPaths(skeletonAnimation.transform, skeletonAnimation.skeleton); + } + + renderer.enabled = false; + } + } + + public void AdjustCamera () { + if (previewRenderUtility == null) + return; + + if (CurrentTime < cameraAdjustEndFrame) + AdjustCameraGoals(); + + lastCameraPositionGoal = cameraPositionGoal; + lastCameraOrthoGoal = cameraOrthoGoal; + + var c = this.PreviewUtilityCamera; + float orthoSet = Mathf.Lerp(c.orthographicSize, cameraOrthoGoal, 0.1f); + + c.orthographicSize = orthoSet; + + float dist = Vector3.Distance(c.transform.position, cameraPositionGoal); + if (dist > 0f) { + Vector3 pos = Vector3.Lerp(c.transform.position, cameraPositionGoal, 0.1f); + pos.x = 0; + c.transform.position = pos; + c.transform.rotation = Quaternion.identity; + RefreshOnNextUpdate(); + } + } + + void AdjustCameraGoals () { + if (previewGameObject == null) return; + + Bounds bounds = previewGameObject.GetComponent().bounds; + cameraOrthoGoal = bounds.size.y; + cameraPositionGoal = bounds.center + new Vector3(0, 0, -10f); + } + + void HandleMouseScroll (Rect position) { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(SliderHash, FocusType.Passive); + switch (current.GetTypeForControl(controlID)) { + case EventType.ScrollWheel: + if (position.Contains(current.mousePosition)) { + cameraOrthoGoal += current.delta.y * 0.06f; + cameraOrthoGoal = Mathf.Max(0.01f, cameraOrthoGoal); + GUIUtility.hotControl = controlID; + current.Use(); + } + break; + } + } + + public void RefreshOnNextUpdate () { + requiresRefresh = true; + } + + public void ClearAnimationSetupPose () { + if (skeletonAnimation == null) { + Debug.LogWarning("Animation was stopped but preview doesn't exist. It's possible that the Preview Panel is closed."); + } + + skeletonAnimation.AnimationState.ClearTracks(); + skeletonAnimation.Skeleton.SetToSetupPose(); + } + + public void PlayPauseAnimation (string animationName, bool loop) { + if (skeletonData == null) return; + + if (skeletonAnimation == null) { + //Debug.LogWarning("Animation was stopped but preview doesn't exist. It's possible that the Preview Panel is closed."); + return; + } + + if (!skeletonAnimation.valid) return; + + if (string.IsNullOrEmpty(animationName)) { + skeletonAnimation.Skeleton.SetToSetupPose(); + skeletonAnimation.AnimationState.ClearTracks(); + return; + } + + var targetAnimation = skeletonData.FindAnimation(animationName); + if (targetAnimation != null) { + var currentTrack = this.ActiveTrack; + bool isEmpty = (currentTrack == null); + bool isNewAnimation = isEmpty || currentTrack.Animation != targetAnimation; + + var skeleton = skeletonAnimation.Skeleton; + var animationState = skeletonAnimation.AnimationState; + + if (isEmpty) { + skeleton.SetToSetupPose(); + animationState.SetAnimation(0, targetAnimation, loop); + } else { + bool sameAnimation = (currentTrack.Animation == targetAnimation); + if (sameAnimation) { + currentTrack.TimeScale = (currentTrack.TimeScale == 0) ? 1f : 0f; // pause/play + } else { + currentTrack.TimeScale = 1f; + animationState.SetAnimation(0, targetAnimation, loop); + } + } + + if (isNewAnimation) { + currentAnimationEvents.Clear(); + currentAnimationEventTimes.Clear(); + foreach (Timeline timeline in targetAnimation.Timelines) { + var eventTimeline = timeline as EventTimeline; + if (eventTimeline != null) { + for (int i = 0; i < eventTimeline.Events.Length; i++) { + currentAnimationEvents.Add(eventTimeline.Events[i]); + currentAnimationEventTimes.Add(eventTimeline.Frames[i]); + } + } + } + } + } else { + Debug.LogFormat("The Spine.Animation named '{0}' was not found for this Skeleton.", animationName); + } + + } + + void DrawSkinToolbar (Rect r) { + if (!this.IsValid) return; + + var skeleton = this.Skeleton; + string label = (skeleton.Skin != null) ? skeleton.Skin.Name : "default"; + + Rect popRect = new Rect(r); + popRect.y += 32; + popRect.x += 4; + popRect.height = 24; + popRect.width = 40; + EditorGUI.DropShadowLabel(popRect, SpineInspectorUtility.TempContent("Skin")); + + popRect.y += 11; + popRect.width = 150; + popRect.x += 44; + + if (GUI.Button(popRect, SpineInspectorUtility.TempContent(label, Icons.skin), EditorStyles.popup)) { + DrawSkinDropdown(); + } + } + + void DrawSetupPoseButton (Rect r) { + if (!this.IsValid) + return; + + var skeleton = this.Skeleton; + + Rect popRect = new Rect(r); + popRect.y += 64; + popRect.x += 4; + popRect.height = 24; + popRect.width = 40; + + //popRect.y += 11; + popRect.width = 150; + //popRect.x += 44; + + if (GUI.Button(popRect, SpineInspectorUtility.TempContent("Reset to SetupPose", Icons.skeleton))) { + ClearAnimationSetupPose(); + RefreshOnNextUpdate(); + } + } + + void DrawSkinDropdown () { + var menu = new GenericMenu(); + foreach (Skin s in skeletonData.Skins) + menu.AddItem(new GUIContent(s.Name, Icons.skin), skeletonAnimation.skeleton.Skin == s, HandleSkinDropdownSelection, s); + + menu.ShowAsContext(); + } + + void HandleSkinDropdownSelection (object o) { + Skin skin = (Skin)o; + skeletonAnimation.initialSkinName = skin.Name; + skeletonAnimation.Initialize(true); + RefreshOnNextUpdate(); + if (OnSkinChanged != null) OnSkinChanged(skin.Name); + } + + void DrawTimeBar (Rect r) { + if (skeletonAnimation == null) + return; + + Rect barRect = new Rect(r); + barRect.height = 32; + barRect.x += 4; + barRect.width -= 4; + + GUI.Box(barRect, ""); + + Rect lineRect = new Rect(barRect); + float lineRectWidth = lineRect.width; + TrackEntry t = skeletonAnimation.AnimationState.GetCurrent(0); + + if (t != null && Icons.userEvent != null) { // when changing to play mode, Icons.userEvent will not be reset + int loopCount = (int)(t.TrackTime / t.TrackEnd); + float currentTime = t.TrackTime - (t.TrackEnd * loopCount); + float normalizedTime = currentTime / t.Animation.Duration; + float wrappedTime = normalizedTime % 1f; + + lineRect.x = barRect.x + (lineRectWidth * wrappedTime) - 0.5f; + lineRect.width = 2; + + GUI.color = Color.red; + GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture); + GUI.color = Color.white; + + currentAnimationEventTooltips = currentAnimationEventTooltips ?? new List(); + currentAnimationEventTooltips.Clear(); + for (int i = 0; i < currentAnimationEvents.Count; i++) { + float eventTime = currentAnimationEventTimes[i]; + var userEventIcon = Icons.userEvent; + float iconX = Mathf.Max(((eventTime / t.Animation.Duration) * lineRectWidth) - (userEventIcon.width / 2), barRect.x); + float iconY = barRect.y + userEventIcon.height; + var evRect = new Rect(barRect) { + x = iconX, + y = iconY, + width = userEventIcon.width, + height = userEventIcon.height + }; + GUI.DrawTexture(evRect, userEventIcon); + Event ev = Event.current; + if (ev.type == EventType.Repaint) { + if (evRect.Contains(ev.mousePosition)) { + string eventName = currentAnimationEvents[i].Data.Name; + Rect tooltipRect = new Rect(evRect) { + width = EditorStyles.helpBox.CalcSize(new GUIContent(eventName)).x + }; + tooltipRect.y -= 4; + tooltipRect.y -= tooltipRect.height * currentAnimationEventTooltips.Count; // Avoid several overlapping tooltips. + tooltipRect.x += 4; + + // Handle tooltip overflowing to the right. + float rightEdgeOverflow = (tooltipRect.x + tooltipRect.width) - (barRect.x + barRect.width); + if (rightEdgeOverflow > 0) + tooltipRect.x -= rightEdgeOverflow; + + currentAnimationEventTooltips.Add(new SpineEventTooltip { rect = tooltipRect, text = eventName }); + } + } + } + + // Draw tooltips. + for (int i = 0; i < currentAnimationEventTooltips.Count; i++) { + GUI.Label(currentAnimationEventTooltips[i].rect, currentAnimationEventTooltips[i].text, EditorStyles.helpBox); + GUI.tooltip = currentAnimationEventTooltips[i].text; + } + } + } + + public void OnDestroy () { + DisposePreviewRenderUtility(); + DestroyPreviewGameObject(); + } + + public void Clear () { + DisposePreviewRenderUtility(); + DestroyPreviewGameObject(); + } + + void DisposePreviewRenderUtility () { + if (previewRenderUtility != null) { + previewRenderUtility.Cleanup(); + previewRenderUtility = null; + } + } + + void DestroyPreviewGameObject () { + if (previewGameObject != null) { + GameObject.DestroyImmediate(previewGameObject); + previewGameObject = null; + } + } + + internal struct SpineEventTooltip { + public Rect rect; + public string text; + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs.meta new file mode 100644 index 0000000..fba64b6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SkeletonDataAssetInspector.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 01cbef8f24d105f4bafa9668d669e040 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs new file mode 100644 index 0000000..ef9b437 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs @@ -0,0 +1,383 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +//#define BAKE_ALL_BUTTON +//#define REGION_BAKING_MESH + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using Spine; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + + [CustomEditor(typeof(SpineAtlasAsset)), CanEditMultipleObjects] + public class SpineAtlasAssetInspector : UnityEditor.Editor { + SerializedProperty atlasFile, materials; + SpineAtlasAsset atlasAsset; + + GUIContent spriteSlicesLabel; + GUIContent SpriteSlicesLabel { + get { + if (spriteSlicesLabel == null) { + spriteSlicesLabel = new GUIContent( + "Apply Regions as Texture Sprite Slices", + SpineEditorUtilities.Icons.unity, + "Adds Sprite slices to atlas texture(s). " + + "Updates existing slices if ones with matching names exist. \n\n" + + "If your atlas was exported with Premultiply Alpha, " + + "your SpriteRenderer should use the generated Spine _Material asset (or any Material with a PMA shader) instead of Sprites-Default."); + } + return spriteSlicesLabel; + } + } + + static List GetRegions (Atlas atlas) { + FieldInfo regionsField = SpineInspectorUtility.GetNonPublicField(typeof(Atlas), "regions"); + return (List)regionsField.GetValue(atlas); + } + + void OnEnable () { + SpineEditorUtilities.ConfirmInitialization(); + atlasFile = serializedObject.FindProperty("atlasFile"); + materials = serializedObject.FindProperty("materials"); + materials.isExpanded = true; + atlasAsset = (SpineAtlasAsset)target; + #if REGION_BAKING_MESH + UpdateBakedList(); + #endif + } + + #if REGION_BAKING_MESH + private List baked; + private List bakedObjects; + + void UpdateBakedList () { + AtlasAsset asset = (AtlasAsset)target; + baked = new List(); + bakedObjects = new List(); + if (atlasFile.objectReferenceValue != null) { + List regions = this.Regions; + string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset); + string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath); + string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name); + for (int i = 0; i < regions.Count; i++) { + AtlasRegion region = regions[i]; + string bakedPrefabPath = Path.Combine(bakedDirPath, AssetUtility.GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/"); + GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject)); + baked.Add(prefab != null); + bakedObjects.Add(prefab); + } + } + } + #endif + + override public void OnInspectorGUI () { + if (serializedObject.isEditingMultipleObjects) { + DrawDefaultInspector(); + return; + } + + serializedObject.Update(); + atlasAsset = (atlasAsset == null) ? (SpineAtlasAsset)target : atlasAsset; + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(atlasFile); + EditorGUILayout.PropertyField(materials, true); + if (EditorGUI.EndChangeCheck()) { + serializedObject.ApplyModifiedProperties(); + atlasAsset.Clear(); + atlasAsset.GetAtlas(); + } + + if (materials.arraySize == 0) { + EditorGUILayout.HelpBox("No materials", MessageType.Error); + return; + } + + for (int i = 0; i < materials.arraySize; i++) { + SerializedProperty prop = materials.GetArrayElementAtIndex(i); + var material = (Material)prop.objectReferenceValue; + if (material == null) { + EditorGUILayout.HelpBox("Materials cannot be null.", MessageType.Error); + return; + } + } + + EditorGUILayout.Space(); + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent("Set Mipmap Bias to " + SpinePreferences.DEFAULT_MIPMAPBIAS, tooltip: "This may help textures with mipmaps be less blurry when used for 2D sprites."))) { + foreach (var m in atlasAsset.materials) { + var texture = m.mainTexture; + string texturePath = AssetDatabase.GetAssetPath(texture.GetInstanceID()); + var importer = (TextureImporter)TextureImporter.GetAtPath(texturePath); + importer.mipMapBias = SpinePreferences.DEFAULT_MIPMAPBIAS; + EditorUtility.SetDirty(texture); + } + Debug.Log("Texture mipmap bias set to " + SpinePreferences.DEFAULT_MIPMAPBIAS); + } + + EditorGUILayout.Space(); + if (atlasFile.objectReferenceValue != null) { + if (SpineInspectorUtility.LargeCenteredButton(SpriteSlicesLabel)) { + var atlas = atlasAsset.GetAtlas(); + foreach (var m in atlasAsset.materials) + UpdateSpriteSlices(m.mainTexture, atlas); + } + } + + EditorGUILayout.Space(); + + #if REGION_BAKING_MESH + if (atlasFile.objectReferenceValue != null) { + Atlas atlas = asset.GetAtlas(); + FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic); + List regions = (List)field.GetValue(atlas); + EditorGUILayout.LabelField(new GUIContent("Region Baking", SpineEditorUtilities.Icons.unityIcon)); + EditorGUI.indentLevel++; + AtlasPage lastPage = null; + for (int i = 0; i < regions.Count; i++) { + if (lastPage != regions[i].page) { + if (lastPage != null) { + EditorGUILayout.Separator(); + EditorGUILayout.Separator(); + } + lastPage = regions[i].page; + Material mat = ((Material)lastPage.rendererObject); + if (mat != null) { + GUILayout.BeginHorizontal(); + { + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.ObjectField(mat, typeof(Material), false, GUILayout.Width(250)); + EditorGUI.EndDisabledGroup(); + } + GUILayout.EndHorizontal(); + + } else { + EditorGUILayout.LabelField(new GUIContent("Page missing material!", SpineEditorUtilities.Icons.warning)); + } + } + GUILayout.BeginHorizontal(); + { + //EditorGUILayout.ToggleLeft(baked[i] ? "" : regions[i].name, baked[i]); + bool result = baked[i] ? EditorGUILayout.ToggleLeft("", baked[i], GUILayout.Width(24)) : EditorGUILayout.ToggleLeft(" " + regions[i].name, baked[i]); + if(baked[i]){ + EditorGUILayout.ObjectField(bakedObjects[i], typeof(GameObject), false, GUILayout.Width(250)); + } + if (result && !baked[i]) { + //bake + baked[i] = true; + bakedObjects[i] = SpineEditorUtilities.BakeRegion(atlasAsset, regions[i]); + EditorGUIUtility.PingObject(bakedObjects[i]); + } else if (!result && baked[i]) { + //unbake + bool unbakeResult = EditorUtility.DisplayDialog("Delete Baked Region", "Do you want to delete the prefab for " + regions[i].name, "Yes", "Cancel"); + switch (unbakeResult) { + case true: + //delete + string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset); + string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath); + string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name); + string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(regions[i]) + ".prefab").Replace("\\", "/"); + AssetDatabase.DeleteAsset(bakedPrefabPath); + baked[i] = false; + break; + case false: + //do nothing + break; + } + } + } + GUILayout.EndHorizontal(); + } + EditorGUI.indentLevel--; + + #if BAKE_ALL_BUTTON + // Check state + bool allBaked = true; + bool allUnbaked = true; + for (int i = 0; i < regions.Count; i++) { + allBaked &= baked[i]; + allUnbaked &= !baked[i]; + } + + if (!allBaked && GUILayout.Button("Bake All")) { + for (int i = 0; i < regions.Count; i++) { + if (!baked[i]) { + baked[i] = true; + bakedObjects[i] = SpineEditorUtilities.BakeRegion(atlasAsset, regions[i]); + } + } + + } else if (!allUnbaked && GUILayout.Button("Unbake All")) { + bool unbakeResult = EditorUtility.DisplayDialog("Delete All Baked Regions", "Are you sure you want to unbake all region prefabs? This cannot be undone.", "Yes", "Cancel"); + switch (unbakeResult) { + case true: + //delete + for (int i = 0; i < regions.Count; i++) { + if (baked[i]) { + string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset); + string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath); + string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name); + string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(regions[i]) + ".prefab").Replace("\\", "/"); + AssetDatabase.DeleteAsset(bakedPrefabPath); + baked[i] = false; + } + } + break; + case false: + //do nothing + break; + } + + } + #endif + + } + #else + if (atlasFile.objectReferenceValue != null) { + + + int baseIndent = EditorGUI.indentLevel; + + var regions = SpineAtlasAssetInspector.GetRegions(atlasAsset.GetAtlas()); + int regionsCount = regions.Count; + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.LabelField("Atlas Regions", EditorStyles.boldLabel); + EditorGUILayout.LabelField(string.Format("{0} regions total", regionsCount)); + } + AtlasPage lastPage = null; + for (int i = 0; i < regionsCount; i++) { + if (lastPage != regions[i].page) { + if (lastPage != null) { + EditorGUILayout.Separator(); + EditorGUILayout.Separator(); + } + lastPage = regions[i].page; + Material mat = ((Material)lastPage.rendererObject); + if (mat != null) { + EditorGUI.indentLevel = baseIndent; + using (new GUILayout.HorizontalScope()) + using (new EditorGUI.DisabledGroupScope(true)) + EditorGUILayout.ObjectField(mat, typeof(Material), false, GUILayout.Width(250)); + EditorGUI.indentLevel = baseIndent + 1; + } else { + EditorGUILayout.HelpBox("Page missing material!", MessageType.Warning); + } + } + + string regionName = regions[i].name; + Texture2D icon = SpineEditorUtilities.Icons.image; + if (regionName.EndsWith(" ")) { + regionName = string.Format("'{0}'", regions[i].name); + icon = SpineEditorUtilities.Icons.warning; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(regionName, icon, "Region name ends with whitespace. This may cause errors. Please check your source image filenames.")); + } else { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(regionName, icon)); + } + + } + EditorGUI.indentLevel = baseIndent; + } + #endif + + if (serializedObject.ApplyModifiedProperties() || SpineInspectorUtility.UndoRedoPerformed(Event.current)) + atlasAsset.Clear(); + } + + static public void UpdateSpriteSlices (Texture texture, Atlas atlas) { + string texturePath = AssetDatabase.GetAssetPath(texture.GetInstanceID()); + var t = (TextureImporter)TextureImporter.GetAtPath(texturePath); + t.spriteImportMode = SpriteImportMode.Multiple; + var spriteSheet = t.spritesheet; + var sprites = new List(spriteSheet); + + var regions = SpineAtlasAssetInspector.GetRegions(atlas); + char[] FilenameDelimiter = {'.'}; + int updatedCount = 0; + int addedCount = 0; + + foreach (var r in regions) { + string pageName = r.page.name.Split(FilenameDelimiter, StringSplitOptions.RemoveEmptyEntries)[0]; + string textureName = texture.name; + bool pageMatch = string.Equals(pageName, textureName, StringComparison.Ordinal); + +// if (pageMatch) { +// int pw = r.page.width; +// int ph = r.page.height; +// bool mismatchSize = pw != texture.width || pw > t.maxTextureSize || ph != texture.height || ph > t.maxTextureSize; +// if (mismatchSize) +// Debug.LogWarningFormat("Size mismatch found.\nExpected atlas size is {0}x{1}. Texture Import Max Size of texture '{2}'({4}x{5}) is currently set to {3}.", pw, ph, texture.name, t.maxTextureSize, texture.width, texture.height); +// } + + int spriteIndex = pageMatch ? sprites.FindIndex( + (s) => string.Equals(s.name, r.name, StringComparison.Ordinal) + ) : -1; + bool spriteNameMatchExists = spriteIndex >= 0; + + if (pageMatch) { + Rect spriteRect = new Rect(); + + if (r.rotate) { + spriteRect.width = r.height; + spriteRect.height = r.width; + } else { + spriteRect.width = r.width; + spriteRect.height = r.height; + } + spriteRect.x = r.x; + spriteRect.y = r.page.height - spriteRect.height - r.y; + + if (spriteNameMatchExists) { + var s = sprites[spriteIndex]; + s.rect = spriteRect; + sprites[spriteIndex] = s; + updatedCount++; + } else { + sprites.Add(new SpriteMetaData { + name = r.name, + pivot = new Vector2(0.5f, 0.5f), + rect = spriteRect + }); + addedCount++; + } + } + + } + + t.spritesheet = sprites.ToArray(); + EditorUtility.SetDirty(t); + AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate); + EditorGUIUtility.PingObject(texture); + Debug.Log(string.Format("Applied sprite slices to {2}. {0} added. {1} updated.", addedCount, updatedCount, texture.name)); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs.meta new file mode 100644 index 0000000..2f5962a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineAtlasAssetInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ca9b3ce36d70a05408e3bdd5e92c7f64 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs new file mode 100644 index 0000000..6820b56 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs @@ -0,0 +1,153 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using Spine; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + + [CustomEditor(typeof(SpineSpriteAtlasAsset)), CanEditMultipleObjects] + public class SpineSpriteAtlasAssetInspector : UnityEditor.Editor { + SerializedProperty atlasFile, materials; + SpineSpriteAtlasAsset atlasAsset; + + static List GetRegions (Atlas atlas) { + FieldInfo regionsField = SpineInspectorUtility.GetNonPublicField(typeof(Atlas), "regions"); + return (List)regionsField.GetValue(atlas); + } + + void OnEnable () { + SpineEditorUtilities.ConfirmInitialization(); + atlasFile = serializedObject.FindProperty("spriteAtlasFile"); + materials = serializedObject.FindProperty("materials"); + materials.isExpanded = true; + atlasAsset = (SpineSpriteAtlasAsset)target; + + if (!SpineSpriteAtlasAsset.AnySpriteAtlasNeedsRegionsLoaded()) + return; + EditorApplication.update -= SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + EditorApplication.update += SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + } + + void OnDisable () { + EditorApplication.update -= SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + } + + override public void OnInspectorGUI () { + if (serializedObject.isEditingMultipleObjects) { + DrawDefaultInspector(); + return; + } + + serializedObject.Update(); + atlasAsset = (atlasAsset == null) ? (SpineSpriteAtlasAsset)target : atlasAsset; + + if (atlasAsset.RegionsNeedLoading) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Load regions by entering Play mode"), GUILayout.Height(20))) { + EditorApplication.isPlaying = true; + } + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(atlasFile); + EditorGUILayout.PropertyField(materials, true); + if (EditorGUI.EndChangeCheck()) { + serializedObject.ApplyModifiedProperties(); + atlasAsset.Clear(); + atlasAsset.GetAtlas(); + atlasAsset.updateRegionsInPlayMode = true; + } + + if (materials.arraySize == 0) { + EditorGUILayout.HelpBox("No materials", MessageType.Error); + return; + } + + for (int i = 0; i < materials.arraySize; i++) { + SerializedProperty prop = materials.GetArrayElementAtIndex(i); + var material = (Material)prop.objectReferenceValue; + if (material == null) { + EditorGUILayout.HelpBox("Materials cannot be null.", MessageType.Error); + return; + } + } + + if (atlasFile.objectReferenceValue != null) { + int baseIndent = EditorGUI.indentLevel; + + var regions = SpineSpriteAtlasAssetInspector.GetRegions(atlasAsset.GetAtlas()); + int regionsCount = regions.Count; + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.LabelField("Atlas Regions", EditorStyles.boldLabel); + EditorGUILayout.LabelField(string.Format("{0} regions total", regionsCount)); + } + AtlasPage lastPage = null; + for (int i = 0; i < regionsCount; i++) { + if (lastPage != regions[i].page) { + if (lastPage != null) { + EditorGUILayout.Separator(); + EditorGUILayout.Separator(); + } + lastPage = regions[i].page; + Material mat = ((Material)lastPage.rendererObject); + if (mat != null) { + EditorGUI.indentLevel = baseIndent; + using (new GUILayout.HorizontalScope()) + using (new EditorGUI.DisabledGroupScope(true)) + EditorGUILayout.ObjectField(mat, typeof(Material), false, GUILayout.Width(250)); + EditorGUI.indentLevel = baseIndent + 1; + } else { + EditorGUILayout.HelpBox("Page missing material!", MessageType.Warning); + } + } + + string regionName = regions[i].name; + Texture2D icon = SpineEditorUtilities.Icons.image; + if (regionName.EndsWith(" ")) { + regionName = string.Format("'{0}'", regions[i].name); + icon = SpineEditorUtilities.Icons.warning; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(regionName, icon, "Region name ends with whitespace. This may cause errors. Please check your source image filenames.")); + } else { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(regionName, icon)); + } + } + EditorGUI.indentLevel = baseIndent; + } + + if (serializedObject.ApplyModifiedProperties() || SpineInspectorUtility.UndoRedoPerformed(Event.current)) + atlasAsset.Clear(); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs.meta new file mode 100644 index 0000000..238789e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Asset Types/SpineSpriteAtlasAssetInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f063dc5ff6881db4a9ee2e059812cba2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components.meta new file mode 100644 index 0000000..a6574b2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0134640f881c8d24d812a6f9af9d0761 +folderAsset: yes +timeCreated: 1563304704 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs new file mode 100644 index 0000000..1603385 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs @@ -0,0 +1,207 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using Spine.Unity; + +namespace Spine.Unity.Editor { + + using Editor = UnityEditor.Editor; + using Event = UnityEngine.Event; + + [CustomEditor(typeof(BoneFollowerGraphic)), CanEditMultipleObjects] + public class BoneFollowerGraphicInspector : Editor { + + SerializedProperty boneName, skeletonGraphic, followXYPosition, followZPosition, followBoneRotation, + followLocalScale, followSkeletonFlip, maintainedAxisOrientation; + BoneFollowerGraphic targetBoneFollower; + bool needsReset; + + #region Context Menu Item + [MenuItem ("CONTEXT/SkeletonGraphic/Add BoneFollower GameObject")] + static void AddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonGraphic = cmd.context as SkeletonGraphic; + var go = EditorInstantiation.NewGameObject("BoneFollower", true, typeof(RectTransform)); + var t = go.transform; + t.SetParent(skeletonGraphic.transform); + t.localPosition = Vector3.zero; + + var f = go.AddComponent(); + f.skeletonGraphic = skeletonGraphic; + f.SetBone(skeletonGraphic.Skeleton.RootBone.Data.Name); + + EditorGUIUtility.PingObject(t); + + Undo.RegisterCreatedObjectUndo(go, "Add BoneFollowerGraphic"); + } + + // Validate + [MenuItem ("CONTEXT/SkeletonGraphic/Add BoneFollower GameObject", true)] + static bool ValidateAddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonGraphic = cmd.context as SkeletonGraphic; + return skeletonGraphic.IsValid; + } + #endregion + + void OnEnable () { + skeletonGraphic = serializedObject.FindProperty("skeletonGraphic"); + boneName = serializedObject.FindProperty("boneName"); + followBoneRotation = serializedObject.FindProperty("followBoneRotation"); + followXYPosition = serializedObject.FindProperty("followXYPosition"); + followZPosition = serializedObject.FindProperty("followZPosition"); + followLocalScale = serializedObject.FindProperty("followLocalScale"); + followSkeletonFlip = serializedObject.FindProperty("followSkeletonFlip"); + maintainedAxisOrientation = serializedObject.FindProperty("maintainedAxisOrientation"); + + targetBoneFollower = (BoneFollowerGraphic)target; + if (targetBoneFollower.SkeletonGraphic != null) + targetBoneFollower.SkeletonGraphic.Initialize(false); + + if (!targetBoneFollower.valid || needsReset) { + targetBoneFollower.Initialize(); + targetBoneFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + } + + public void OnSceneGUI () { + var tbf = target as BoneFollowerGraphic; + var skeletonGraphicComponent = tbf.SkeletonGraphic; + if (skeletonGraphicComponent == null) return; + + var transform = skeletonGraphicComponent.transform; + var skeleton = skeletonGraphicComponent.Skeleton; + var canvas = skeletonGraphicComponent.canvas; + float positionScale = canvas == null ? 1f : skeletonGraphicComponent.canvas.referencePixelsPerUnit; + + if (string.IsNullOrEmpty(boneName.stringValue)) { + SpineHandles.DrawBones(transform, skeleton, positionScale); + SpineHandles.DrawBoneNames(transform, skeleton, positionScale); + Handles.Label(tbf.transform.position, "No bone selected", EditorStyles.helpBox); + } else { + var targetBone = tbf.bone; + if (targetBone == null) return; + + SpineHandles.DrawBoneWireframe(transform, targetBone, SpineHandles.TransformContraintColor, positionScale); + Handles.Label(targetBone.GetWorldPosition(transform, positionScale), targetBone.Data.Name, SpineHandles.BoneNameStyle); + } + } + + override public void OnInspectorGUI () { + if (serializedObject.isEditingMultipleObjects) { + if (needsReset) { + needsReset = false; + foreach (var o in targets) { + var bf = (BoneFollower)o; + bf.Initialize(); + bf.LateUpdate(); + } + SceneView.RepaintAll(); + } + + EditorGUI.BeginChangeCheck(); + DrawDefaultInspector(); + needsReset |= EditorGUI.EndChangeCheck(); + return; + } + + if (needsReset && Event.current.type == EventType.Layout) { + targetBoneFollower.Initialize(); + targetBoneFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + serializedObject.Update(); + + // Find Renderer + if (skeletonGraphic.objectReferenceValue == null) { + SkeletonGraphic parentRenderer = targetBoneFollower.GetComponentInParent(); + if (parentRenderer != null && parentRenderer.gameObject != targetBoneFollower.gameObject) { + skeletonGraphic.objectReferenceValue = parentRenderer; + Debug.Log("Inspector automatically assigned BoneFollowerGraphic.SkeletonGraphic"); + } + } + + EditorGUILayout.PropertyField(skeletonGraphic); + var skeletonGraphicComponent = skeletonGraphic.objectReferenceValue as SkeletonGraphic; + if (skeletonGraphicComponent != null) { + if (skeletonGraphicComponent.gameObject == targetBoneFollower.gameObject) { + skeletonGraphic.objectReferenceValue = null; + EditorUtility.DisplayDialog("Invalid assignment.", "BoneFollowerGraphic can only follow a skeleton on a separate GameObject.\n\nCreate a new GameObject for your BoneFollower, or choose a SkeletonGraphic from a different GameObject.", "Ok"); + } + } + + if (!targetBoneFollower.valid) { + needsReset = true; + } + + if (targetBoneFollower.valid) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(boneName); + needsReset |= EditorGUI.EndChangeCheck(); + + EditorGUILayout.PropertyField(followBoneRotation); + EditorGUILayout.PropertyField(followXYPosition); + EditorGUILayout.PropertyField(followZPosition); + EditorGUILayout.PropertyField(followLocalScale); + EditorGUILayout.PropertyField(followSkeletonFlip); + if ((followSkeletonFlip.hasMultipleDifferentValues || followSkeletonFlip.boolValue == false) && + (followBoneRotation.hasMultipleDifferentValues || followBoneRotation.boolValue == true)) { + using (new SpineInspectorUtility.IndentScope()) + EditorGUILayout.PropertyField(maintainedAxisOrientation); + } + + //BoneFollowerInspector.RecommendRigidbodyButton(targetBoneFollower); + } else { + var boneFollowerSkeletonGraphic = targetBoneFollower.skeletonGraphic; + if (boneFollowerSkeletonGraphic == null) { + EditorGUILayout.HelpBox("SkeletonGraphic is unassigned. Please assign a SkeletonRenderer (SkeletonAnimation or SkeletonMecanim).", MessageType.Warning); + } else { + boneFollowerSkeletonGraphic.Initialize(false); + + if (boneFollowerSkeletonGraphic.skeletonDataAsset == null) + EditorGUILayout.HelpBox("Assigned SkeletonGraphic does not have SkeletonData assigned to it.", MessageType.Warning); + + if (!boneFollowerSkeletonGraphic.IsValid) + EditorGUILayout.HelpBox("Assigned SkeletonGraphic is invalid. Check target SkeletonGraphic, its SkeletonDataAsset or the console for other errors.", MessageType.Warning); + } + } + + var current = Event.current; + bool wasUndo = (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed"); + if (wasUndo) + targetBoneFollower.Initialize(); + + serializedObject.ApplyModifiedProperties(); + } + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs.meta new file mode 100644 index 0000000..b3d60a4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerGraphicInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: da44a8561fd243c43a1f77bda36de0eb +timeCreated: 1499279157 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs new file mode 100644 index 0000000..17cc739 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs @@ -0,0 +1,228 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + + using Editor = UnityEditor.Editor; + using Event = UnityEngine.Event; + + [CustomEditor(typeof(BoneFollower)), CanEditMultipleObjects] + public class BoneFollowerInspector : Editor { + SerializedProperty boneName, skeletonRenderer, followXYPosition, followZPosition, followBoneRotation, + followLocalScale, followSkeletonFlip, maintainedAxisOrientation; + BoneFollower targetBoneFollower; + bool needsReset; + + #region Context Menu Item + [MenuItem ("CONTEXT/SkeletonRenderer/Add BoneFollower GameObject")] + static void AddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + var go = EditorInstantiation.NewGameObject("New BoneFollower", true); + var t = go.transform; + t.SetParent(skeletonRenderer.transform); + t.localPosition = Vector3.zero; + + var f = go.AddComponent(); + f.skeletonRenderer = skeletonRenderer; + + EditorGUIUtility.PingObject(t); + + Undo.RegisterCreatedObjectUndo(go, "Add BoneFollower"); + } + + // Validate + [MenuItem ("CONTEXT/SkeletonRenderer/Add BoneFollower GameObject", true)] + static bool ValidateAddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + return skeletonRenderer.valid; + } + + [MenuItem("CONTEXT/BoneFollower/Rename BoneFollower GameObject")] + static void RenameGameObject (MenuCommand cmd) { + AutonameGameObject(cmd.context as BoneFollower); + } + #endregion + + static void AutonameGameObject (BoneFollower boneFollower) { + if (boneFollower == null) return; + + string boneName = boneFollower.boneName; + boneFollower.gameObject.name = string.IsNullOrEmpty(boneName) ? "BoneFollower" : string.Format("{0} (BoneFollower)", boneName); + } + + void OnEnable () { + skeletonRenderer = serializedObject.FindProperty("skeletonRenderer"); + boneName = serializedObject.FindProperty("boneName"); + followBoneRotation = serializedObject.FindProperty("followBoneRotation"); + followXYPosition = serializedObject.FindProperty("followXYPosition"); + followZPosition = serializedObject.FindProperty("followZPosition"); + followLocalScale = serializedObject.FindProperty("followLocalScale"); + followSkeletonFlip = serializedObject.FindProperty("followSkeletonFlip"); + maintainedAxisOrientation = serializedObject.FindProperty("maintainedAxisOrientation"); + + targetBoneFollower = (BoneFollower)target; + if (targetBoneFollower.SkeletonRenderer != null) + targetBoneFollower.SkeletonRenderer.Initialize(false); + + if (!targetBoneFollower.valid || needsReset) { + targetBoneFollower.Initialize(); + targetBoneFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + } + + public void OnSceneGUI () { + var tbf = target as BoneFollower; + var skeletonRendererComponent = tbf.skeletonRenderer; + if (skeletonRendererComponent == null) return; + + var transform = skeletonRendererComponent.transform; + var skeleton = skeletonRendererComponent.skeleton; + + if (string.IsNullOrEmpty(boneName.stringValue)) { + SpineHandles.DrawBones(transform, skeleton); + SpineHandles.DrawBoneNames(transform, skeleton); + Handles.Label(tbf.transform.position, "No bone selected", EditorStyles.helpBox); + } else { + var targetBone = tbf.bone; + if (targetBone == null) return; + SpineHandles.DrawBoneWireframe(transform, targetBone, SpineHandles.TransformContraintColor); + Handles.Label(targetBone.GetWorldPosition(transform), targetBone.Data.Name, SpineHandles.BoneNameStyle); + } + } + + override public void OnInspectorGUI () { + if (serializedObject.isEditingMultipleObjects) { + if (needsReset) { + needsReset = false; + foreach (var o in targets) { + var bf = (BoneFollower)o; + bf.Initialize(); + bf.LateUpdate(); + } + SceneView.RepaintAll(); + } + + EditorGUI.BeginChangeCheck(); + DrawDefaultInspector(); + needsReset |= EditorGUI.EndChangeCheck(); + return; + } + + if (needsReset && Event.current.type == EventType.Layout) { + targetBoneFollower.Initialize(); + targetBoneFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + serializedObject.Update(); + + // Find Renderer + if (skeletonRenderer.objectReferenceValue == null) { + SkeletonRenderer parentRenderer = targetBoneFollower.GetComponentInParent(); + if (parentRenderer != null && parentRenderer.gameObject != targetBoneFollower.gameObject) { + skeletonRenderer.objectReferenceValue = parentRenderer; + Debug.Log("Inspector automatically assigned BoneFollower.SkeletonRenderer"); + } + } + + EditorGUILayout.PropertyField(skeletonRenderer); + var skeletonRendererReference = skeletonRenderer.objectReferenceValue as SkeletonRenderer; + if (skeletonRendererReference != null) { + if (skeletonRendererReference.gameObject == targetBoneFollower.gameObject) { + skeletonRenderer.objectReferenceValue = null; + EditorUtility.DisplayDialog("Invalid assignment.", "BoneFollower can only follow a skeleton on a separate GameObject.\n\nCreate a new GameObject for your BoneFollower, or choose a SkeletonRenderer from a different GameObject.", "Ok"); + } + } + + if (!targetBoneFollower.valid) { + needsReset = true; + } + + if (targetBoneFollower.valid) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(boneName); + needsReset |= EditorGUI.EndChangeCheck(); + + EditorGUILayout.PropertyField(followBoneRotation); + EditorGUILayout.PropertyField(followXYPosition); + EditorGUILayout.PropertyField(followZPosition); + EditorGUILayout.PropertyField(followLocalScale); + EditorGUILayout.PropertyField(followSkeletonFlip); + if ((followSkeletonFlip.hasMultipleDifferentValues || followSkeletonFlip.boolValue == false) && + (followBoneRotation.hasMultipleDifferentValues || followBoneRotation.boolValue == true)) { + using (new SpineInspectorUtility.IndentScope()) + EditorGUILayout.PropertyField(maintainedAxisOrientation); + } + + BoneFollowerInspector.RecommendRigidbodyButton(targetBoneFollower); + } else { + var boneFollowerSkeletonRenderer = targetBoneFollower.skeletonRenderer; + if (boneFollowerSkeletonRenderer == null) { + EditorGUILayout.HelpBox("SkeletonRenderer is unassigned. Please assign a SkeletonRenderer (SkeletonAnimation or SkeletonMecanim).", MessageType.Warning); + } else { + boneFollowerSkeletonRenderer.Initialize(false); + + if (boneFollowerSkeletonRenderer.skeletonDataAsset == null) + EditorGUILayout.HelpBox("Assigned SkeletonRenderer does not have SkeletonData assigned to it.", MessageType.Warning); + + if (!boneFollowerSkeletonRenderer.valid) + EditorGUILayout.HelpBox("Assigned SkeletonRenderer is invalid. Check target SkeletonRenderer, its SkeletonDataAsset or the console for other errors.", MessageType.Warning); + } + } + + var current = Event.current; + bool wasUndo = (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed"); + if (wasUndo) + targetBoneFollower.Initialize(); + + serializedObject.ApplyModifiedProperties(); + } + + internal static void RecommendRigidbodyButton (Component component) { + bool hasCollider2D = component.GetComponent() != null || component.GetComponent() != null; + bool hasCollider3D = !hasCollider2D && component.GetComponent(); + bool missingRigidBody = (hasCollider2D && component.GetComponent() == null) || (hasCollider3D && component.GetComponent() == null); + if (missingRigidBody) { + using (new SpineInspectorUtility.BoxScope()) { + EditorGUILayout.HelpBox("Collider detected. Unity recommends adding a Rigidbody to the Transforms of any colliders that are intended to be dynamically repositioned and rotated.", MessageType.Warning); + var rbType = hasCollider2D ? typeof(Rigidbody2D) : typeof(Rigidbody); + string rbLabel = string.Format("Add {0}", rbType.Name); + var rbContent = SpineInspectorUtility.TempContent(rbLabel, SpineInspectorUtility.UnityIcon(rbType), "Add a rigidbody to this GameObject to be the Physics body parent of the attached collider."); + if (SpineInspectorUtility.CenteredButton(rbContent)) component.gameObject.AddComponent(rbType); + } + } + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs.meta new file mode 100644 index 0000000..0448ccb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoneFollowerInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: c71ca35fd6241cb49a0b0756a664fcf7 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs new file mode 100644 index 0000000..2c2585d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs @@ -0,0 +1,261 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(BoundingBoxFollowerGraphic))] + public class BoundingBoxFollowerGraphicInspector : UnityEditor.Editor { + SerializedProperty skeletonGraphic, slotName, isTrigger, clearStateOnDisable; + BoundingBoxFollowerGraphic follower; + bool rebuildRequired = false; + bool addBoneFollower = false; + bool sceneRepaintRequired = false; + bool debugIsExpanded; + + GUIContent addBoneFollowerLabel; + GUIContent AddBoneFollowerLabel { + get { + if (addBoneFollowerLabel == null) addBoneFollowerLabel = new GUIContent("Add Bone Follower", Icons.bone); + return addBoneFollowerLabel; + } + } + + void InitializeEditor () { + skeletonGraphic = serializedObject.FindProperty("skeletonGraphic"); + slotName = serializedObject.FindProperty("slotName"); + isTrigger = serializedObject.FindProperty("isTrigger"); + clearStateOnDisable = serializedObject.FindProperty("clearStateOnDisable"); + follower = (BoundingBoxFollowerGraphic)target; + } + + public override void OnInspectorGUI () { + + #if !NEW_PREFAB_SYSTEM + bool isInspectingPrefab = (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab); + #else + bool isInspectingPrefab = false; + #endif + + // Note: when calling InitializeEditor() in OnEnable, it throws exception + // "SerializedObjectNotCreatableException: Object at index 0 is null". + InitializeEditor(); + + // Try to auto-assign SkeletonGraphic field. + if (skeletonGraphic.objectReferenceValue == null) { + var foundSkeletonGraphic = follower.GetComponentInParent(); + if (foundSkeletonGraphic != null) + Debug.Log("BoundingBoxFollowerGraphic automatically assigned: " + foundSkeletonGraphic.gameObject.name); + else if (Event.current.type == EventType.Repaint) + Debug.Log("No Spine GameObject detected. Make sure to set this GameObject as a child of the Spine GameObject; or set BoundingBoxFollowerGraphic's 'Skeleton Graphic' field in the inspector."); + + skeletonGraphic.objectReferenceValue = foundSkeletonGraphic; + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + } + + var skeletonGraphicValue = skeletonGraphic.objectReferenceValue as SkeletonGraphic; + if (skeletonGraphicValue != null && skeletonGraphicValue.gameObject == follower.gameObject) { + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { + EditorGUILayout.HelpBox("It's ideal to add BoundingBoxFollowerGraphic to a separate child GameObject of the Spine GameObject.", MessageType.Warning); + + if (GUILayout.Button(new GUIContent("Move BoundingBoxFollowerGraphic to new GameObject", Icons.boundingBox), GUILayout.Height(30f))) { + AddBoundingBoxFollowerGraphicChild(skeletonGraphicValue, follower); + DestroyImmediate(follower); + return; + } + } + EditorGUILayout.Space(); + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(skeletonGraphic); + EditorGUILayout.PropertyField(slotName, new GUIContent("Slot")); + if (EditorGUI.EndChangeCheck()) { + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + #if !NEW_PREFAB_SYSTEM + if (!isInspectingPrefab) + rebuildRequired = true; + #endif + } + + using (new SpineInspectorUtility.LabelWidthScope(150f)) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(isTrigger); + bool triggerChanged = EditorGUI.EndChangeCheck(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(clearStateOnDisable, new GUIContent(clearStateOnDisable.displayName, "Enable this if you are pooling your Spine GameObject")); + bool clearStateChanged = EditorGUI.EndChangeCheck(); + + if (clearStateChanged || triggerChanged) { + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + if (triggerChanged) + foreach (var col in follower.colliderTable.Values) + col.isTrigger = isTrigger.boolValue; + } + } + + if (isInspectingPrefab) { + follower.colliderTable.Clear(); + follower.nameTable.Clear(); + EditorGUILayout.HelpBox("BoundingBoxAttachments cannot be previewed in prefabs.", MessageType.Info); + + // How do you prevent components from being saved into the prefab? No such HideFlag. DontSaveInEditor | DontSaveInBuild does not work. DestroyImmediate does not work. + var collider = follower.GetComponent(); + if (collider != null) Debug.LogWarning("Found BoundingBoxFollowerGraphic collider components in prefab. These are disposed and regenerated at runtime."); + + } else { + using (new SpineInspectorUtility.BoxScope()) { + if (debugIsExpanded = EditorGUILayout.Foldout(debugIsExpanded, "Debug Colliders")) { + EditorGUI.indentLevel++; + EditorGUILayout.LabelField(string.Format("Attachment Names ({0} PolygonCollider2D)", follower.colliderTable.Count)); + EditorGUI.BeginChangeCheck(); + foreach (var kp in follower.nameTable) { + string attachmentName = kp.Value; + var collider = follower.colliderTable[kp.Key]; + bool isPlaceholder = attachmentName != kp.Key.Name; + collider.enabled = EditorGUILayout.ToggleLeft(new GUIContent(!isPlaceholder ? attachmentName : string.Format("{0} [{1}]", attachmentName, kp.Key.Name), isPlaceholder ? Icons.skinPlaceholder : Icons.boundingBox), collider.enabled); + } + sceneRepaintRequired |= EditorGUI.EndChangeCheck(); + EditorGUI.indentLevel--; + } + } + + } + + if (follower.Slot == null) + follower.Initialize(false); + bool hasBoneFollower = follower.GetComponent() != null; + if (!hasBoneFollower) { + bool buttonDisabled = follower.Slot == null; + using (new EditorGUI.DisabledGroupScope(buttonDisabled)) { + addBoneFollower |= SpineInspectorUtility.LargeCenteredButton(AddBoneFollowerLabel, true); + EditorGUILayout.Space(); + } + } + + + if (Event.current.type == EventType.Repaint) { + if (addBoneFollower) { + var boneFollower = follower.gameObject.AddComponent(); + boneFollower.skeletonGraphic = skeletonGraphicValue; + boneFollower.SetBone(follower.Slot.Data.BoneData.Name); + addBoneFollower = false; + } + + if (sceneRepaintRequired) { + SceneView.RepaintAll(); + sceneRepaintRequired = false; + } + + if (rebuildRequired) { + follower.Initialize(); + rebuildRequired = false; + } + } + } + + #region Menus + [MenuItem("CONTEXT/SkeletonGraphic/Add BoundingBoxFollowerGraphic GameObject")] + static void AddBoundingBoxFollowerGraphicChild (MenuCommand command) { + var go = AddBoundingBoxFollowerGraphicChild((SkeletonGraphic)command.context); + Undo.RegisterCreatedObjectUndo(go, "Add BoundingBoxFollowerGraphic"); + } + + [MenuItem("CONTEXT/SkeletonGraphic/Add all BoundingBoxFollowerGraphic GameObjects")] + static void AddAllBoundingBoxFollowerGraphicChildren (MenuCommand command) { + var objects = AddAllBoundingBoxFollowerGraphicChildren((SkeletonGraphic)command.context); + foreach (var go in objects) + Undo.RegisterCreatedObjectUndo(go, "Add BoundingBoxFollowerGraphic"); + } + #endregion + + public static GameObject AddBoundingBoxFollowerGraphicChild (SkeletonGraphic skeletonGraphic, + BoundingBoxFollowerGraphic original = null, string name = "BoundingBoxFollowerGraphic", + string slotName = null) { + + var go = EditorInstantiation.NewGameObject(name, true); + go.transform.SetParent(skeletonGraphic.transform, false); + go.AddComponent(); + var newFollower = go.AddComponent(); + + if (original != null) { + newFollower.slotName = original.slotName; + newFollower.isTrigger = original.isTrigger; + newFollower.clearStateOnDisable = original.clearStateOnDisable; + } + if (slotName != null) + newFollower.slotName = slotName; + + newFollower.skeletonGraphic = skeletonGraphic; + newFollower.Initialize(); + + Selection.activeGameObject = go; + EditorGUIUtility.PingObject(go); + return go; + } + + public static List AddAllBoundingBoxFollowerGraphicChildren ( + SkeletonGraphic skeletonGraphic, BoundingBoxFollowerGraphic original = null) { + + List createdGameObjects = new List(); + foreach (var skin in skeletonGraphic.Skeleton.Data.Skins) { + var attachments = skin.Attachments; + foreach (var entry in attachments) { + var boundingBoxAttachment = entry.Value as BoundingBoxAttachment; + if (boundingBoxAttachment == null) + continue; + int slotIndex = entry.Key.SlotIndex; + var slot = skeletonGraphic.Skeleton.Slots.Items[slotIndex]; + string slotName = slot.Data.Name; + GameObject go = AddBoundingBoxFollowerGraphicChild(skeletonGraphic, + original, boundingBoxAttachment.Name, slotName); + var boneFollower = go.AddComponent(); + boneFollower.skeletonGraphic = skeletonGraphic; + boneFollower.SetBone(slot.Data.BoneData.Name); + createdGameObjects.Add(go); + } + } + return createdGameObjects; + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs.meta new file mode 100644 index 0000000..1596069 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerGraphicInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c4f5b276299bc048ad00f3cd2d1ea09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs new file mode 100644 index 0000000..0d68b63 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs @@ -0,0 +1,260 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(BoundingBoxFollower))] + public class BoundingBoxFollowerInspector : UnityEditor.Editor { + SerializedProperty skeletonRenderer, slotName, isTrigger, clearStateOnDisable; + BoundingBoxFollower follower; + bool rebuildRequired = false; + bool addBoneFollower = false; + bool sceneRepaintRequired = false; + bool debugIsExpanded; + + GUIContent addBoneFollowerLabel; + GUIContent AddBoneFollowerLabel { + get { + if (addBoneFollowerLabel == null) addBoneFollowerLabel = new GUIContent("Add Bone Follower", Icons.bone); + return addBoneFollowerLabel; + } + } + + void InitializeEditor () { + skeletonRenderer = serializedObject.FindProperty("skeletonRenderer"); + slotName = serializedObject.FindProperty("slotName"); + isTrigger = serializedObject.FindProperty("isTrigger"); + clearStateOnDisable = serializedObject.FindProperty("clearStateOnDisable"); + follower = (BoundingBoxFollower)target; + } + + public override void OnInspectorGUI () { + + #if !NEW_PREFAB_SYSTEM + bool isInspectingPrefab = (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab); + #else + bool isInspectingPrefab = false; + #endif + + // Note: when calling InitializeEditor() in OnEnable, it throws exception + // "SerializedObjectNotCreatableException: Object at index 0 is null". + InitializeEditor(); + + // Try to auto-assign SkeletonRenderer field. + if (skeletonRenderer.objectReferenceValue == null) { + var foundSkeletonRenderer = follower.GetComponentInParent(); + if (foundSkeletonRenderer != null) + Debug.Log("BoundingBoxFollower automatically assigned: " + foundSkeletonRenderer.gameObject.name); + else if (Event.current.type == EventType.Repaint) + Debug.Log("No Spine GameObject detected. Make sure to set this GameObject as a child of the Spine GameObject; or set BoundingBoxFollower's 'Skeleton Renderer' field in the inspector."); + + skeletonRenderer.objectReferenceValue = foundSkeletonRenderer; + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + } + + var skeletonRendererValue = skeletonRenderer.objectReferenceValue as SkeletonRenderer; + if (skeletonRendererValue != null && skeletonRendererValue.gameObject == follower.gameObject) { + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { + EditorGUILayout.HelpBox("It's ideal to add BoundingBoxFollower to a separate child GameObject of the Spine GameObject.", MessageType.Warning); + + if (GUILayout.Button(new GUIContent("Move BoundingBoxFollower to new GameObject", Icons.boundingBox), GUILayout.Height(30f))) { + AddBoundingBoxFollowerChild(skeletonRendererValue, follower); + DestroyImmediate(follower); + return; + } + } + EditorGUILayout.Space(); + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(skeletonRenderer); + EditorGUILayout.PropertyField(slotName, new GUIContent("Slot")); + if (EditorGUI.EndChangeCheck()) { + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + #if !NEW_PREFAB_SYSTEM + if (!isInspectingPrefab) + rebuildRequired = true; + #endif + } + + using (new SpineInspectorUtility.LabelWidthScope(150f)) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(isTrigger); + bool triggerChanged = EditorGUI.EndChangeCheck(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(clearStateOnDisable, new GUIContent(clearStateOnDisable.displayName, "Enable this if you are pooling your Spine GameObject")); + bool clearStateChanged = EditorGUI.EndChangeCheck(); + + if (clearStateChanged || triggerChanged) { + serializedObject.ApplyModifiedProperties(); + InitializeEditor(); + if (triggerChanged) + foreach (var col in follower.colliderTable.Values) + col.isTrigger = isTrigger.boolValue; + } + } + + if (isInspectingPrefab) { + follower.colliderTable.Clear(); + follower.nameTable.Clear(); + EditorGUILayout.HelpBox("BoundingBoxAttachments cannot be previewed in prefabs.", MessageType.Info); + + // How do you prevent components from being saved into the prefab? No such HideFlag. DontSaveInEditor | DontSaveInBuild does not work. DestroyImmediate does not work. + var collider = follower.GetComponent(); + if (collider != null) Debug.LogWarning("Found BoundingBoxFollower collider components in prefab. These are disposed and regenerated at runtime."); + + } else { + using (new SpineInspectorUtility.BoxScope()) { + if (debugIsExpanded = EditorGUILayout.Foldout(debugIsExpanded, "Debug Colliders")) { + EditorGUI.indentLevel++; + EditorGUILayout.LabelField(string.Format("Attachment Names ({0} PolygonCollider2D)", follower.colliderTable.Count)); + EditorGUI.BeginChangeCheck(); + foreach (var kp in follower.nameTable) { + string attachmentName = kp.Value; + var collider = follower.colliderTable[kp.Key]; + bool isPlaceholder = attachmentName != kp.Key.Name; + collider.enabled = EditorGUILayout.ToggleLeft(new GUIContent(!isPlaceholder ? attachmentName : string.Format("{0} [{1}]", attachmentName, kp.Key.Name), isPlaceholder ? Icons.skinPlaceholder : Icons.boundingBox), collider.enabled); + } + sceneRepaintRequired |= EditorGUI.EndChangeCheck(); + EditorGUI.indentLevel--; + } + } + + } + + if (follower.Slot == null) + follower.Initialize(false); + bool hasBoneFollower = follower.GetComponent() != null; + if (!hasBoneFollower) { + bool buttonDisabled = follower.Slot == null; + using (new EditorGUI.DisabledGroupScope(buttonDisabled)) { + addBoneFollower |= SpineInspectorUtility.LargeCenteredButton(AddBoneFollowerLabel, true); + EditorGUILayout.Space(); + } + } + + + if (Event.current.type == EventType.Repaint) { + if (addBoneFollower) { + var boneFollower = follower.gameObject.AddComponent(); + boneFollower.skeletonRenderer = skeletonRendererValue; + boneFollower.SetBone(follower.Slot.Data.BoneData.Name); + addBoneFollower = false; + } + + if (sceneRepaintRequired) { + SceneView.RepaintAll(); + sceneRepaintRequired = false; + } + + if (rebuildRequired) { + follower.Initialize(); + rebuildRequired = false; + } + } + } + + #region Menus + [MenuItem("CONTEXT/SkeletonRenderer/Add BoundingBoxFollower GameObject")] + static void AddBoundingBoxFollowerChild (MenuCommand command) { + var go = AddBoundingBoxFollowerChild((SkeletonRenderer)command.context); + Undo.RegisterCreatedObjectUndo(go, "Add BoundingBoxFollower"); + } + + [MenuItem("CONTEXT/SkeletonRenderer/Add all BoundingBoxFollower GameObjects")] + static void AddAllBoundingBoxFollowerChildren (MenuCommand command) { + var objects = AddAllBoundingBoxFollowerChildren((SkeletonRenderer)command.context); + foreach (var go in objects) + Undo.RegisterCreatedObjectUndo(go, "Add BoundingBoxFollower"); + } + #endregion + + public static GameObject AddBoundingBoxFollowerChild (SkeletonRenderer skeletonRenderer, + BoundingBoxFollower original = null, string name = "BoundingBoxFollower", + string slotName = null) { + + var go = EditorInstantiation.NewGameObject(name, true); + go.transform.SetParent(skeletonRenderer.transform, false); + var newFollower = go.AddComponent(); + + if (original != null) { + newFollower.slotName = original.slotName; + newFollower.isTrigger = original.isTrigger; + newFollower.clearStateOnDisable = original.clearStateOnDisable; + } + if (slotName != null) + newFollower.slotName = slotName; + + newFollower.skeletonRenderer = skeletonRenderer; + newFollower.Initialize(); + + Selection.activeGameObject = go; + EditorGUIUtility.PingObject(go); + return go; + } + + public static List AddAllBoundingBoxFollowerChildren ( + SkeletonRenderer skeletonRenderer, BoundingBoxFollower original = null) { + + List createdGameObjects = new List(); + foreach (var skin in skeletonRenderer.Skeleton.Data.Skins) { + var attachments = skin.Attachments; + foreach (var entry in attachments) { + var boundingBoxAttachment = entry.Value as BoundingBoxAttachment; + if (boundingBoxAttachment == null) + continue; + int slotIndex = entry.Key.SlotIndex; + var slot = skeletonRenderer.Skeleton.Slots.Items[slotIndex]; + string slotName = slot.Data.Name; + GameObject go = AddBoundingBoxFollowerChild(skeletonRenderer, + original, boundingBoxAttachment.Name, slotName); + var boneFollower = go.AddComponent(); + boneFollower.skeletonRenderer = skeletonRenderer; + boneFollower.SetBone(slot.Data.BoneData.Name); + createdGameObjects.Add(go); + } + } + return createdGameObjects; + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs.meta new file mode 100644 index 0000000..e42ba77 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/BoundingBoxFollowerInspector.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 670a3cefa3853bd48b5da53a424fd542 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs new file mode 100644 index 0000000..858a8ec --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs @@ -0,0 +1,188 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + + using Editor = UnityEditor.Editor; + using Event = UnityEngine.Event; + + [CustomEditor(typeof(PointFollower)), CanEditMultipleObjects] + public class PointFollowerInspector : Editor { + SerializedProperty slotName, pointAttachmentName, skeletonRenderer, followZPosition, followBoneRotation, followSkeletonFlip; + PointFollower targetPointFollower; + bool needsReset; + + #region Context Menu Item + [MenuItem("CONTEXT/SkeletonRenderer/Add PointFollower GameObject")] + static void AddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + var go = EditorInstantiation.NewGameObject("PointFollower", true); + var t = go.transform; + t.SetParent(skeletonRenderer.transform); + t.localPosition = Vector3.zero; + + var f = go.AddComponent(); + f.skeletonRenderer = skeletonRenderer; + + EditorGUIUtility.PingObject(t); + + Undo.RegisterCreatedObjectUndo(go, "Add PointFollower"); + } + + // Validate + [MenuItem("CONTEXT/SkeletonRenderer/Add PointFollower GameObject", true)] + static bool ValidateAddBoneFollowerGameObject (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + return skeletonRenderer.valid; + } + #endregion + + void OnEnable () { + skeletonRenderer = serializedObject.FindProperty("skeletonRenderer"); + slotName = serializedObject.FindProperty("slotName"); + pointAttachmentName = serializedObject.FindProperty("pointAttachmentName"); + + targetPointFollower = (PointFollower)target; + if (targetPointFollower.skeletonRenderer != null) + targetPointFollower.skeletonRenderer.Initialize(false); + + if (!targetPointFollower.IsValid || needsReset) { + targetPointFollower.Initialize(); + targetPointFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + } + + public void OnSceneGUI () { + var tbf = target as PointFollower; + var skeletonRendererComponent = tbf.skeletonRenderer; + if (skeletonRendererComponent == null) + return; + + var skeleton = skeletonRendererComponent.skeleton; + var skeletonTransform = skeletonRendererComponent.transform; + + if (string.IsNullOrEmpty(pointAttachmentName.stringValue)) { + // Draw all active PointAttachments in the current skin + var currentSkin = skeleton.Skin; + if (currentSkin != skeleton.Data.DefaultSkin) DrawPointsInSkin(skeleton.Data.DefaultSkin, skeleton, skeletonTransform); + if (currentSkin != null) DrawPointsInSkin(currentSkin, skeleton, skeletonTransform); + } else { + int slotIndex = skeleton.FindSlotIndex(slotName.stringValue); + if (slotIndex >= 0) { + var slot = skeleton.Slots.Items[slotIndex]; + var point = skeleton.GetAttachment(slotIndex, pointAttachmentName.stringValue) as PointAttachment; + if (point != null) { + DrawPointAttachmentWithLabel(point, slot.Bone, skeletonTransform); + } + } + } + } + + static void DrawPointsInSkin (Skin skin, Skeleton skeleton, Transform transform) { + foreach (var skinEntry in skin.Attachments) { + var attachment = skinEntry.Value as PointAttachment; + if (attachment != null) { + var skinKey = (Skin.SkinEntry)skinEntry.Key; + var slot = skeleton.Slots.Items[skinKey.SlotIndex]; + DrawPointAttachmentWithLabel(attachment, slot.Bone, transform); + } + } + } + + static void DrawPointAttachmentWithLabel (PointAttachment point, Bone bone, Transform transform) { + Vector3 labelOffset = new Vector3(0f, -0.2f, 0f); + SpineHandles.DrawPointAttachment(bone, point, transform); + Handles.Label(labelOffset + point.GetWorldPosition(bone, transform), point.Name, SpineHandles.PointNameStyle); + } + + override public void OnInspectorGUI () { + if (serializedObject.isEditingMultipleObjects) { + if (needsReset) { + needsReset = false; + foreach (var o in targets) { + var bf = (BoneFollower)o; + bf.Initialize(); + bf.LateUpdate(); + } + SceneView.RepaintAll(); + } + + EditorGUI.BeginChangeCheck(); + DrawDefaultInspector(); + needsReset |= EditorGUI.EndChangeCheck(); + return; + } + + if (needsReset && Event.current.type == EventType.Layout) { + targetPointFollower.Initialize(); + targetPointFollower.LateUpdate(); + needsReset = false; + SceneView.RepaintAll(); + } + serializedObject.Update(); + + DrawDefaultInspector(); + + // Find Renderer + if (skeletonRenderer.objectReferenceValue == null) { + SkeletonRenderer parentRenderer = targetPointFollower.GetComponentInParent(); + if (parentRenderer != null && parentRenderer.gameObject != targetPointFollower.gameObject) { + skeletonRenderer.objectReferenceValue = parentRenderer; + Debug.Log("Inspector automatically assigned PointFollower.SkeletonRenderer"); + } + } + + var skeletonRendererReference = skeletonRenderer.objectReferenceValue as SkeletonRenderer; + if (skeletonRendererReference != null) { + if (skeletonRendererReference.gameObject == targetPointFollower.gameObject) { + skeletonRenderer.objectReferenceValue = null; + EditorUtility.DisplayDialog("Invalid assignment.", "PointFollower can only follow a skeleton on a separate GameObject.\n\nCreate a new GameObject for your PointFollower, or choose a SkeletonRenderer from a different GameObject.", "Ok"); + } + } + + if (!targetPointFollower.IsValid) { + needsReset = true; + } + + var current = Event.current; + bool wasUndo = (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed"); + if (wasUndo) + targetPointFollower.Initialize(); + + serializedObject.ApplyModifiedProperties(); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs.meta new file mode 100644 index 0000000..2106156 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/PointFollowerInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7c7e838a8ec295a4e9c53602f690f42f +timeCreated: 1518163038 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs new file mode 100644 index 0000000..c332324 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs @@ -0,0 +1,139 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEditor; +using UnityEngine; +using Spine; + +namespace Spine.Unity.Editor { + + [CustomEditor(typeof(SkeletonAnimation))] + [CanEditMultipleObjects] + public class SkeletonAnimationInspector : SkeletonRendererInspector { + protected SerializedProperty animationName, loop, timeScale, autoReset; + protected bool wasAnimationParameterChanged = false; + protected bool requireRepaint; + readonly GUIContent LoopLabel = new GUIContent("Loop", "Whether or not .AnimationName should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected."); + readonly GUIContent TimeScaleLabel = new GUIContent("Time Scale", "The rate at which animations progress over time. 1 means normal speed. 0.5 means 50% speed."); + + protected override void OnEnable () { + base.OnEnable(); + animationName = serializedObject.FindProperty("_animationName"); + loop = serializedObject.FindProperty("loop"); + timeScale = serializedObject.FindProperty("timeScale"); + } + + protected override void DrawInspectorGUI (bool multi) { + base.DrawInspectorGUI(multi); + if (!TargetIsValid) return; + bool sameData = SpineInspectorUtility.TargetsUseSameData(serializedObject); + + foreach (var o in targets) + TrySetAnimation(o as SkeletonAnimation); + + EditorGUILayout.Space(); + if (!sameData) { + EditorGUILayout.DelayedTextField(animationName); + } else { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(animationName); + wasAnimationParameterChanged |= EditorGUI.EndChangeCheck(); // Value used in the next update. + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(loop, LoopLabel); + wasAnimationParameterChanged |= EditorGUI.EndChangeCheck(); // Value used in the next update. + EditorGUILayout.PropertyField(timeScale, TimeScaleLabel); + foreach (var o in targets) { + var component = o as SkeletonAnimation; + component.timeScale = Mathf.Max(component.timeScale, 0); + } + + EditorGUILayout.Space(); + SkeletonRootMotionParameter(); + + serializedObject.ApplyModifiedProperties(); + + if (!isInspectingPrefab) { + if (requireRepaint) { + UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); + requireRepaint = false; + } + } + } + + protected void TrySetAnimation (SkeletonAnimation skeletonAnimation) { + if (skeletonAnimation == null) return; + if (!skeletonAnimation.valid || skeletonAnimation.AnimationState == null) + return; + + TrackEntry current = skeletonAnimation.AnimationState.GetCurrent(0); + if (!isInspectingPrefab) { + string activeAnimation = (current != null) ? current.Animation.Name : ""; + bool activeLoop = (current != null) ? current.Loop : false; + bool animationParameterChanged = this.wasAnimationParameterChanged && + ((activeAnimation != animationName.stringValue) || (activeLoop != loop.boolValue)); + if (animationParameterChanged) { + this.wasAnimationParameterChanged = false; + var skeleton = skeletonAnimation.Skeleton; + var state = skeletonAnimation.AnimationState; + + if (!Application.isPlaying) { + if (state != null) state.ClearTrack(0); + skeleton.SetToSetupPose(); + } + + Spine.Animation animationToUse = skeleton.Data.FindAnimation(animationName.stringValue); + + if (!Application.isPlaying) { + if (animationToUse != null) { + skeletonAnimation.AnimationState.SetAnimation(0, animationToUse, loop.boolValue); + } + skeletonAnimation.Update(0); + skeletonAnimation.LateUpdate(); + requireRepaint = true; + } else { + if (animationToUse != null) + state.SetAnimation(0, animationToUse, loop.boolValue); + else + state.ClearTrack(0); + } + } + + // Reflect animationName serialized property in the inspector even if SetAnimation API was used. + if (Application.isPlaying) { + if (current != null && current.Animation != null) { + if (skeletonAnimation.AnimationName != animationName.stringValue) + animationName.stringValue = current.Animation.Name; + } + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs.meta new file mode 100644 index 0000000..1ca7941 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonAnimationInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 39fbfef61034ca045b5aa80088e1e8a4 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs new file mode 100644 index 0000000..f9a1c2d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs @@ -0,0 +1,159 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using Spine.Unity.Examples; + +namespace Spine.Unity.Editor { + + // This script is not intended for use with code. See spine-unity documentation page for additional information. + [CustomEditor(typeof(SkeletonGraphicCustomMaterials))] + public class SkeletonGraphicCustomMaterialsInspector : UnityEditor.Editor { + List componentCustomMaterialOverrides, _customMaterialOverridesPrev; + List componentCustomTextureOverrides, _customTextureOverridesPrev; + SkeletonGraphicCustomMaterials component; + + const BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic; + MethodInfo RemoveCustomMaterialOverrides, RemoveCustomTextureOverrides, SetCustomMaterialOverrides, SetCustomTextureOverrides; + + #region SkeletonGraphic context menu + [MenuItem("CONTEXT/SkeletonGraphic/Add Basic Serialized Custom Materials")] + static void AddSkeletonGraphicCustomMaterials (MenuCommand menuCommand) { + var skeletonGraphic = (SkeletonGraphic)menuCommand.context; + var newComponent = skeletonGraphic.gameObject.AddComponent(); + Undo.RegisterCreatedObjectUndo(newComponent, "Add Basic Serialized Custom Materials"); + } + + [MenuItem("CONTEXT/SkeletonGraphic/Add Basic Serialized Custom Materials", true)] + static bool AddSkeletonGraphicCustomMaterials_Validate (MenuCommand menuCommand) { + var skeletonGraphic = (SkeletonGraphic)menuCommand.context; + return (skeletonGraphic.GetComponent() == null); + } + #endregion + + void OnEnable () { + Type cm = typeof(SkeletonGraphicCustomMaterials); + RemoveCustomMaterialOverrides = cm.GetMethod("RemoveCustomMaterialOverrides", PrivateInstance); + RemoveCustomTextureOverrides = cm.GetMethod("RemoveCustomTextureOverrides", PrivateInstance); + SetCustomMaterialOverrides = cm.GetMethod("SetCustomMaterialOverrides", PrivateInstance); + SetCustomTextureOverrides = cm.GetMethod("SetCustomTextureOverrides", PrivateInstance); + } + + public override void OnInspectorGUI () { + component = (SkeletonGraphicCustomMaterials)target; + var skeletonGraphic = component.skeletonGraphic; + + // Draw the default inspector + DrawDefaultInspector(); + + if (serializedObject.isEditingMultipleObjects) + return; + + if (componentCustomMaterialOverrides == null) { + Type cm = typeof(SkeletonGraphicCustomMaterials); + componentCustomMaterialOverrides = cm.GetField("customMaterialOverrides", PrivateInstance).GetValue(component) as List; + componentCustomTextureOverrides = cm.GetField("customTextureOverrides", PrivateInstance).GetValue(component) as List; + if (componentCustomMaterialOverrides == null) { + Debug.Log("Reflection failed."); + return; + } + } + + // Fill with current values at start + if (_customMaterialOverridesPrev == null || _customTextureOverridesPrev == null) { + _customMaterialOverridesPrev = CopyList(componentCustomMaterialOverrides); + _customTextureOverridesPrev = CopyList(componentCustomTextureOverrides); + } + + // Compare new values with saved. If change is detected: + // store new values, restore old values, remove overrides, restore new values, restore overrides. + + // 1. Store new values + var customMaterialOverridesNew = CopyList(componentCustomMaterialOverrides); + var customTextureOverridesNew = CopyList(componentCustomTextureOverrides); + + // Detect changes + if (!_customMaterialOverridesPrev.SequenceEqual(customMaterialOverridesNew) || + !_customTextureOverridesPrev.SequenceEqual(customTextureOverridesNew)) { + // 2. Restore old values + componentCustomMaterialOverrides.Clear(); + componentCustomTextureOverrides.Clear(); + componentCustomMaterialOverrides.AddRange(_customMaterialOverridesPrev); + componentCustomTextureOverrides.AddRange(_customTextureOverridesPrev); + + // 3. Remove overrides + RemoveCustomMaterials(); + + // 4. Restore new values + componentCustomMaterialOverrides.Clear(); + componentCustomTextureOverrides.Clear(); + componentCustomMaterialOverrides.AddRange(customMaterialOverridesNew); + componentCustomTextureOverrides.AddRange(customTextureOverridesNew); + + // 5. Restore overrides + SetCustomMaterials(); + + if (skeletonGraphic != null) + skeletonGraphic.LateUpdate(); + } + + _customMaterialOverridesPrev = CopyList(componentCustomMaterialOverrides); + _customTextureOverridesPrev = CopyList(componentCustomTextureOverrides); + + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent("Clear and Reapply Changes", tooltip: "Removes all non-serialized overrides in the SkeletonGraphic and reapplies the overrides on this component."))) { + if (skeletonGraphic != null) { + skeletonGraphic.CustomMaterialOverride.Clear(); + skeletonGraphic.CustomTextureOverride.Clear(); + RemoveCustomMaterials(); + SetCustomMaterials(); + skeletonGraphic.LateUpdate(); + } + } + } + + void RemoveCustomMaterials () { + RemoveCustomMaterialOverrides.Invoke(component, null); + RemoveCustomTextureOverrides.Invoke(component, null); + } + + void SetCustomMaterials () { + SetCustomMaterialOverrides.Invoke(component, null); + SetCustomTextureOverrides.Invoke(component, null); + } + + static List CopyList (List list) { + return list.GetRange(0, list.Count); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs.meta new file mode 100644 index 0000000..4a5d351 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicCustomMaterialsInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 349bf125947e3aa4bb78690fec69ea17 +timeCreated: 1588789940 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs new file mode 100644 index 0000000..e1406ca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs @@ -0,0 +1,436 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using UnityEditor; + +namespace Spine.Unity.Editor { + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(SkeletonGraphic))] + [CanEditMultipleObjects] + public class SkeletonGraphicInspector : UnityEditor.Editor { + + const string SeparatorSlotNamesFieldName = "separatorSlotNames"; + const string ReloadButtonString = "Reload"; + protected GUIContent SkeletonDataAssetLabel; + static GUILayoutOption reloadButtonWidth; + static GUILayoutOption ReloadButtonWidth { get { return reloadButtonWidth = reloadButtonWidth ?? GUILayout.Width(GUI.skin.label.CalcSize(new GUIContent(ReloadButtonString)).x + 20); } } + static GUIStyle ReloadButtonStyle { get { return EditorStyles.miniButton; } } + + SerializedProperty material, color; + SerializedProperty skeletonDataAsset, initialSkinName; + SerializedProperty startingAnimation, startingLoop, timeScale, freeze, updateWhenInvisible, unscaledTime, tintBlack; + SerializedProperty initialFlipX, initialFlipY; + SerializedProperty meshGeneratorSettings; + SerializedProperty allowMultipleCanvasRenderers, separatorSlotNames, enableSeparatorSlots, updateSeparatorPartLocation; + SerializedProperty raycastTarget; + + SkeletonGraphic thisSkeletonGraphic; + protected bool isInspectingPrefab; + protected bool slotsReapplyRequired = false; + protected bool forceReloadQueued = false; + + protected bool TargetIsValid { + get { + if (serializedObject.isEditingMultipleObjects) { + foreach (var o in targets) { + var component = (SkeletonGraphic)o; + if (!component.IsValid) + return false; + } + return true; + } + else { + var component = (SkeletonGraphic)target; + return component.IsValid; + } + } + } + + void OnEnable () { +#if NEW_PREFAB_SYSTEM + isInspectingPrefab = false; +#else + isInspectingPrefab = (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab); +#endif + SpineEditorUtilities.ConfirmInitialization(); + + // Labels + SkeletonDataAssetLabel = new GUIContent("SkeletonData Asset", Icons.spine); + + var so = this.serializedObject; + thisSkeletonGraphic = target as SkeletonGraphic; + + // MaskableGraphic + material = so.FindProperty("m_Material"); + color = so.FindProperty("m_Color"); + raycastTarget = so.FindProperty("m_RaycastTarget"); + + // SkeletonRenderer + skeletonDataAsset = so.FindProperty("skeletonDataAsset"); + initialSkinName = so.FindProperty("initialSkinName"); + + initialFlipX = so.FindProperty("initialFlipX"); + initialFlipY = so.FindProperty("initialFlipY"); + + // SkeletonAnimation + startingAnimation = so.FindProperty("startingAnimation"); + startingLoop = so.FindProperty("startingLoop"); + timeScale = so.FindProperty("timeScale"); + unscaledTime = so.FindProperty("unscaledTime"); + freeze = so.FindProperty("freeze"); + updateWhenInvisible = so.FindProperty("updateWhenInvisible"); + + meshGeneratorSettings = so.FindProperty("meshGenerator").FindPropertyRelative("settings"); + meshGeneratorSettings.isExpanded = SkeletonRendererInspector.advancedFoldout; + + allowMultipleCanvasRenderers = so.FindProperty("allowMultipleCanvasRenderers"); + updateSeparatorPartLocation = so.FindProperty("updateSeparatorPartLocation"); + enableSeparatorSlots = so.FindProperty("enableSeparatorSlots"); + + separatorSlotNames = so.FindProperty("separatorSlotNames"); + separatorSlotNames.isExpanded = true; + } + + public override void OnInspectorGUI () { + + if (UnityEngine.Event.current.type == EventType.Layout) { + if (forceReloadQueued) { + forceReloadQueued = false; + foreach (var c in targets) { + SpineEditorUtilities.ReloadSkeletonDataAssetAndComponent(c as SkeletonGraphic); + } + } + else { + foreach (var c in targets) { + var component = c as SkeletonGraphic; + if (!component.IsValid) { + SpineEditorUtilities.ReinitializeComponent(component); + if (!component.IsValid) continue; + } + } + } + } + + bool wasChanged = false; + EditorGUI.BeginChangeCheck(); + + using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox)) { + SpineInspectorUtility.PropertyFieldFitLabel(skeletonDataAsset, SkeletonDataAssetLabel); + if (GUILayout.Button(ReloadButtonString, ReloadButtonStyle, ReloadButtonWidth)) + forceReloadQueued = true; + } + + EditorGUILayout.PropertyField(material); + EditorGUILayout.PropertyField(color); + + if (thisSkeletonGraphic.skeletonDataAsset == null) { + EditorGUILayout.HelpBox("You need to assign a SkeletonDataAsset first.", MessageType.Info); + serializedObject.ApplyModifiedProperties(); + serializedObject.Update(); + return; + } + + string errorMessage = null; + if (SpineEditorUtilities.Preferences.componentMaterialWarning && + MaterialChecks.IsMaterialSetupProblematic(thisSkeletonGraphic, ref errorMessage)) { + EditorGUILayout.HelpBox(errorMessage, MessageType.Error, true); + } + + bool isSingleRendererOnly = (!allowMultipleCanvasRenderers.hasMultipleDifferentValues && allowMultipleCanvasRenderers.boolValue == false); + bool isSeparationEnabledButNotMultipleRenderers = + isSingleRendererOnly && (!enableSeparatorSlots.hasMultipleDifferentValues && enableSeparatorSlots.boolValue == true); + bool meshRendersIncorrectlyWithSingleRenderer = + isSingleRendererOnly && SkeletonHasMultipleSubmeshes(); + + if (isSeparationEnabledButNotMultipleRenderers || meshRendersIncorrectlyWithSingleRenderer) + meshGeneratorSettings.isExpanded = true; + + using (new SpineInspectorUtility.BoxScope()) { + + EditorGUILayout.PropertyField(meshGeneratorSettings, SpineInspectorUtility.TempContent("Advanced..."), includeChildren: true); + SkeletonRendererInspector.advancedFoldout = meshGeneratorSettings.isExpanded; + + if (meshGeneratorSettings.isExpanded) { + EditorGUILayout.Space(); + using (new SpineInspectorUtility.IndentScope()) { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PropertyField(allowMultipleCanvasRenderers, SpineInspectorUtility.TempContent("Multiple CanvasRenderers")); + + if (GUILayout.Button(new GUIContent("Trim Renderers", "Remove currently unused CanvasRenderer GameObjects. These will be regenerated whenever needed."), + EditorStyles.miniButton, GUILayout.Width(100f))) { + + foreach (var skeletonGraphic in targets) { + ((SkeletonGraphic)skeletonGraphic).TrimRenderers(); + } + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.PropertyField(updateWhenInvisible); + + // warning box + if (isSeparationEnabledButNotMultipleRenderers) { + using (new SpineInspectorUtility.BoxScope()) { + meshGeneratorSettings.isExpanded = true; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("'Multiple Canvas Renderers' must be enabled\nwhen 'Enable Separation' is enabled.", Icons.warning), GUILayout.Height(42), GUILayout.Width(340)); + } + } + else if (meshRendersIncorrectlyWithSingleRenderer) { + using (new SpineInspectorUtility.BoxScope()) { + meshGeneratorSettings.isExpanded = true; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("This mesh uses multiple atlas pages. You\n" + + "need to enable 'Multiple Canvas Renderers'\n" + + "for correct rendering. Consider packing\n" + + "attachments to a single atlas page if possible.", Icons.warning), GUILayout.Height(60), GUILayout.Width(340)); + } + } + } + + EditorGUILayout.Space(); + SeparatorsField(separatorSlotNames, enableSeparatorSlots, updateSeparatorPartLocation); + } + } + + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(initialSkinName); + { + var rect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, EditorGUIUtility.singleLineHeight); + EditorGUI.PrefixLabel(rect, SpineInspectorUtility.TempContent("Initial Flip")); + rect.x += EditorGUIUtility.labelWidth; + rect.width = 30f; + SpineInspectorUtility.ToggleLeft(rect, initialFlipX, SpineInspectorUtility.TempContent("X", tooltip: "initialFlipX")); + rect.x += 35f; + SpineInspectorUtility.ToggleLeft(rect, initialFlipY, SpineInspectorUtility.TempContent("Y", tooltip: "initialFlipY")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Animation", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(startingAnimation); + EditorGUILayout.PropertyField(startingLoop); + EditorGUILayout.PropertyField(timeScale); + EditorGUILayout.PropertyField(unscaledTime, SpineInspectorUtility.TempContent(unscaledTime.displayName, tooltip: "If checked, this will use Time.unscaledDeltaTime to make this update independent of game Time.timeScale. Instance SkeletonGraphic.timeScale will still be applied.")); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(freeze); + EditorGUILayout.Space(); + SkeletonRendererInspector.SkeletonRootMotionParameter(targets); + EditorGUILayout.Space(); + EditorGUILayout.LabelField("UI", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(raycastTarget); + + EditorGUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight + 5)); + EditorGUILayout.PrefixLabel("Match RectTransform with Mesh"); + if (GUILayout.Button("Match", EditorStyles.miniButton, GUILayout.Width(65f))) { + foreach (var skeletonGraphic in targets) { + MatchRectTransformWithBounds((SkeletonGraphic)skeletonGraphic); + } + } + EditorGUILayout.EndHorizontal(); + + if (TargetIsValid && !isInspectingPrefab) { + EditorGUILayout.Space(); + if (SpineInspectorUtility.CenteredButton(new GUIContent("Add Skeleton Utility", Icons.skeletonUtility), 21, true, 200f)) + foreach (var t in targets) { + var component = t as Component; + if (component.GetComponent() == null) { + component.gameObject.AddComponent(); + } + } + } + + wasChanged |= EditorGUI.EndChangeCheck(); + + if (wasChanged) { + serializedObject.ApplyModifiedProperties(); + slotsReapplyRequired = true; + } + + if (slotsReapplyRequired && UnityEngine.Event.current.type == EventType.Repaint) { + foreach (var target in targets) { + var skeletonGraphic = (SkeletonGraphic)target; + skeletonGraphic.ReapplySeparatorSlotNames(); + skeletonGraphic.LateUpdate(); + SceneView.RepaintAll(); + } + slotsReapplyRequired = false; + } + } + + protected bool SkeletonHasMultipleSubmeshes () { + foreach (var target in targets) { + var skeletonGraphic = (SkeletonGraphic)target; + if (skeletonGraphic.HasMultipleSubmeshInstructions()) + return true; + } + return false; + } + + public static void SetSeparatorSlotNames (SkeletonRenderer skeletonRenderer, string[] newSlotNames) { + var field = SpineInspectorUtility.GetNonPublicField(typeof(SkeletonRenderer), SeparatorSlotNamesFieldName); + field.SetValue(skeletonRenderer, newSlotNames); + } + + public static string[] GetSeparatorSlotNames (SkeletonRenderer skeletonRenderer) { + var field = SpineInspectorUtility.GetNonPublicField(typeof(SkeletonRenderer), SeparatorSlotNamesFieldName); + return field.GetValue(skeletonRenderer) as string[]; + } + + public static void SeparatorsField (SerializedProperty separatorSlotNames, SerializedProperty enableSeparatorSlots, + SerializedProperty updateSeparatorPartLocation) { + + bool multi = separatorSlotNames.serializedObject.isEditingMultipleObjects; + bool hasTerminalSlot = false; + if (!multi) { + var sr = separatorSlotNames.serializedObject.targetObject as ISkeletonComponent; + var skeleton = sr.Skeleton; + int lastSlot = skeleton.Slots.Count - 1; + if (skeleton != null) { + for (int i = 0, n = separatorSlotNames.arraySize; i < n; i++) { + int index = skeleton.FindSlotIndex(separatorSlotNames.GetArrayElementAtIndex(i).stringValue); + if (index == 0 || index == lastSlot) { + hasTerminalSlot = true; + break; + } + } + } + } + + string terminalSlotWarning = hasTerminalSlot ? " (!)" : ""; + + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { + const string SeparatorsDescription = "Stored names of slots where the Skeleton's render will be split into different batches. This is used by separate components that split the render into different MeshRenderers or GameObjects."; + if (separatorSlotNames.isExpanded) { + EditorGUILayout.PropertyField(separatorSlotNames, SpineInspectorUtility.TempContent(separatorSlotNames.displayName + terminalSlotWarning, Icons.slotRoot, SeparatorsDescription), true); + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("+", GUILayout.MaxWidth(28f), GUILayout.MaxHeight(15f))) { + separatorSlotNames.arraySize++; + } + GUILayout.EndHorizontal(); + } + else + EditorGUILayout.PropertyField(separatorSlotNames, new GUIContent(separatorSlotNames.displayName + string.Format("{0} [{1}]", terminalSlotWarning, separatorSlotNames.arraySize), SeparatorsDescription), true); + + EditorGUILayout.PropertyField(enableSeparatorSlots, SpineInspectorUtility.TempContent("Enable Separation", tooltip: "Whether to enable separation at the above separator slots.")); + EditorGUILayout.PropertyField(updateSeparatorPartLocation, SpineInspectorUtility.TempContent("Update Part Location", tooltip:"Update separator part GameObject location to match the position of the SkeletonGraphic. This can be helpful when re-parenting parts to a different GameObject.")); + } + } + + #region Menus + [MenuItem("CONTEXT/SkeletonGraphic/Match RectTransform with Mesh Bounds")] + static void MatchRectTransformWithBounds (MenuCommand command) { + var skeletonGraphic = (SkeletonGraphic)command.context; + MatchRectTransformWithBounds(skeletonGraphic); + } + + static void MatchRectTransformWithBounds (SkeletonGraphic skeletonGraphic) { + if (!skeletonGraphic.MatchRectTransformWithBounds()) + Debug.Log("Mesh was not previously generated."); + } + + [MenuItem("GameObject/Spine/SkeletonGraphic (UnityUI)", false, 15)] + static public void SkeletonGraphicCreateMenuItem () { + var parentGameObject = Selection.activeObject as GameObject; + var parentTransform = parentGameObject == null ? null : parentGameObject.GetComponent(); + + if (parentTransform == null) + Debug.LogWarning("Your new SkeletonGraphic will not be visible until it is placed under a Canvas"); + + var gameObject = NewSkeletonGraphicGameObject("New SkeletonGraphic"); + gameObject.transform.SetParent(parentTransform, false); + EditorUtility.FocusProjectWindow(); + Selection.activeObject = gameObject; + EditorGUIUtility.PingObject(Selection.activeObject); + } + + // SpineEditorUtilities.InstantiateDelegate. Used by drag and drop. + public static Component SpawnSkeletonGraphicFromDrop (SkeletonDataAsset data) { + return InstantiateSkeletonGraphic(data); + } + + public static SkeletonGraphic InstantiateSkeletonGraphic (SkeletonDataAsset skeletonDataAsset, string skinName) { + return InstantiateSkeletonGraphic(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName)); + } + + public static SkeletonGraphic InstantiateSkeletonGraphic (SkeletonDataAsset skeletonDataAsset, Skin skin = null) { + string spineGameObjectName = string.Format("SkeletonGraphic ({0})", skeletonDataAsset.name.Replace("_SkeletonData", "")); + var go = NewSkeletonGraphicGameObject(spineGameObjectName); + var graphic = go.GetComponent(); + graphic.skeletonDataAsset = skeletonDataAsset; + + SkeletonData data = skeletonDataAsset.GetSkeletonData(true); + + if (data == null) { + for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) { + string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]); + skeletonDataAsset.atlasAssets[i] = (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAssetBase)); + } + + data = skeletonDataAsset.GetSkeletonData(true); + } + + skin = skin ?? data.DefaultSkin ?? data.Skins.Items[0]; + graphic.MeshGenerator.settings.zSpacing = SpineEditorUtilities.Preferences.defaultZSpacing; + + graphic.startingLoop = SpineEditorUtilities.Preferences.defaultInstantiateLoop; + graphic.Initialize(false); + if (skin != null) graphic.Skeleton.SetSkin(skin); + graphic.initialSkinName = skin.Name; + graphic.Skeleton.UpdateWorldTransform(); + graphic.UpdateMesh(); + return graphic; + } + + static GameObject NewSkeletonGraphicGameObject (string gameObjectName) { + var go = EditorInstantiation.NewGameObject(gameObjectName, true, typeof(RectTransform), typeof(CanvasRenderer), typeof(SkeletonGraphic)); + var graphic = go.GetComponent(); + graphic.material = SkeletonGraphicInspector.DefaultSkeletonGraphicMaterial; + return go; + } + + public static Material DefaultSkeletonGraphicMaterial { + get { + var guids = AssetDatabase.FindAssets("SkeletonGraphicDefault t:material"); + if (guids.Length <= 0) return null; + + var firstAssetPath = AssetDatabase.GUIDToAssetPath(guids[0]); + if (string.IsNullOrEmpty(firstAssetPath)) return null; + + var firstMaterial = AssetDatabase.LoadAssetAtPath(firstAssetPath); + return firstMaterial; + } + } + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs.meta new file mode 100644 index 0000000..5fced2e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonGraphicInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0d81cc76b52fcdf499b2db252a317726 +timeCreated: 1455570945 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs new file mode 100644 index 0000000..c322a8e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs @@ -0,0 +1,153 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Contributed by: Mitch Thompson + +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + [CustomEditor(typeof(SkeletonMecanim))] + [CanEditMultipleObjects] + public class SkeletonMecanimInspector : SkeletonRendererInspector { + public static bool mecanimSettingsFoldout; + + protected SerializedProperty autoReset; + protected SerializedProperty useCustomMixMode; + protected SerializedProperty layerMixModes; + protected SerializedProperty layerBlendModes; + + protected override void OnEnable () { + base.OnEnable(); + SerializedProperty mecanimTranslator = serializedObject.FindProperty("translator"); + autoReset = mecanimTranslator.FindPropertyRelative("autoReset"); + useCustomMixMode = mecanimTranslator.FindPropertyRelative("useCustomMixMode"); + layerMixModes = mecanimTranslator.FindPropertyRelative("layerMixModes"); + layerBlendModes = mecanimTranslator.FindPropertyRelative("layerBlendModes"); + } + + protected override void DrawInspectorGUI (bool multi) { + + AddRootMotionComponentIfEnabled(); + + base.DrawInspectorGUI(multi); + + using (new SpineInspectorUtility.BoxScope()) { + mecanimSettingsFoldout = EditorGUILayout.Foldout(mecanimSettingsFoldout, "Mecanim Translator"); + if (mecanimSettingsFoldout) { + EditorGUILayout.PropertyField(autoReset, new GUIContent("Auto Reset", + "When set to true, the skeleton state is mixed out to setup-" + + "pose when an animation finishes, according to the " + + "animation's keyed items.")); + + EditorGUILayout.PropertyField(useCustomMixMode, new GUIContent("Custom MixMode", + "When disabled, the recommended MixMode is used according to the layer blend mode. Enable to specify a custom MixMode for each Mecanim layer.")); + + if (useCustomMixMode.hasMultipleDifferentValues || useCustomMixMode.boolValue == true) { + DrawLayerSettings(); + EditorGUILayout.Space(); + } + } + } + } + + protected void AddRootMotionComponentIfEnabled () { + foreach (var t in targets) { + var component = t as Component; + var animator = component.GetComponent(); + if (animator != null && animator.applyRootMotion) { + if (component.GetComponent() == null) { + component.gameObject.AddComponent(); + } + } + } + } + + protected void DrawLayerSettings () { + string[] layerNames = GetLayerNames(); + float widthLayerColumn = 140; + float widthMixColumn = 84; + + using (new GUILayout.HorizontalScope()) { + var rect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, EditorGUIUtility.singleLineHeight); + rect.width = widthLayerColumn; + EditorGUI.LabelField(rect, SpineInspectorUtility.TempContent("Mecanim Layer"), EditorStyles.boldLabel); + + var savedIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + + rect.position += new Vector2(rect.width, 0); + rect.width = widthMixColumn; + EditorGUI.LabelField(rect, SpineInspectorUtility.TempContent("Mix Mode"), EditorStyles.boldLabel); + + EditorGUI.indentLevel = savedIndent; + } + + using (new SpineInspectorUtility.IndentScope()) { + int layerCount = layerMixModes.arraySize; + for (int i = 0; i < layerCount; ++i) { + using (new GUILayout.HorizontalScope()) { + string layerName = i < layerNames.Length ? layerNames[i] : ("Layer " + i); + + var rect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, EditorGUIUtility.singleLineHeight); + rect.width = widthLayerColumn; + EditorGUI.PrefixLabel(rect, SpineInspectorUtility.TempContent(layerName)); + + var savedIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + + var mixMode = layerMixModes.GetArrayElementAtIndex(i); + rect.position += new Vector2(rect.width, 0); + rect.width = widthMixColumn; + EditorGUI.PropertyField(rect, mixMode, GUIContent.none); + + EditorGUI.indentLevel = savedIndent; + } + } + } + } + + protected string[] GetLayerNames () { + int maxLayerCount = 0; + int maxIndex = 0; + for (int i = 0; i < targets.Length; ++i) { + var skeletonMecanim = ((SkeletonMecanim)targets[i]); + int count = skeletonMecanim.Translator.MecanimLayerCount; + if (count > maxLayerCount) { + maxLayerCount = count; + maxIndex = i; + } + } + if (maxLayerCount == 0) + return new string[0]; + var skeletonMecanimMaxLayers = ((SkeletonMecanim)targets[maxIndex]); + return skeletonMecanimMaxLayers.Translator.MecanimLayerNames; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs.meta new file mode 100644 index 0000000..9ef306e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6a9ca5213a3a4614c9a9f2e60909bc33 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs new file mode 100644 index 0000000..bcdbbaa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs @@ -0,0 +1,81 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + [CustomEditor(typeof(SkeletonMecanimRootMotion))] + [CanEditMultipleObjects] + public class SkeletonMecanimRootMotionInspector : SkeletonRootMotionBaseInspector { + protected SerializedProperty mecanimLayerFlags; + + protected GUIContent mecanimLayersLabel; + + protected override void OnEnable () { + base.OnEnable(); + mecanimLayerFlags = serializedObject.FindProperty("mecanimLayerFlags"); + + mecanimLayersLabel = new UnityEngine.GUIContent("Mecanim Layers", "Mecanim layers to apply root motion at. Defaults to the first Mecanim layer."); + } + + override public void OnInspectorGUI () { + + base.MainPropertyFields(); + MecanimLayerMaskPropertyField(); + + base.OptionalPropertyFields(); + serializedObject.ApplyModifiedProperties(); + } + + protected string[] GetLayerNames () { + int maxLayerCount = 0; + int maxIndex = 0; + for (int i = 0; i < targets.Length; ++i) { + var skeletonMecanim = ((SkeletonMecanimRootMotion)targets[i]).SkeletonMecanim; + int count = skeletonMecanim.Translator.MecanimLayerCount; + if (count > maxLayerCount) { + maxLayerCount = count; + maxIndex = i; + } + } + if (maxLayerCount == 0) + return new string[0]; + var skeletonMecanimMaxLayers = ((SkeletonMecanimRootMotion)targets[maxIndex]).SkeletonMecanim; + return skeletonMecanimMaxLayers.Translator.MecanimLayerNames; + } + + protected void MecanimLayerMaskPropertyField () { + string[] layerNames = GetLayerNames(); + if (layerNames.Length > 0) + mecanimLayerFlags.intValue = EditorGUILayout.MaskField( + mecanimLayersLabel, mecanimLayerFlags.intValue, layerNames); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs.meta new file mode 100644 index 0000000..04c6dcf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonMecanimRootMotionInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4613924c50d66cf458f0db803776dd2f +timeCreated: 1593175106 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs new file mode 100644 index 0000000..44c9f4a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs @@ -0,0 +1,165 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#define SPINE_OPTIONAL_MATERIALOVERRIDE + +// Contributed by: Lost Polygon + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using Spine.Unity.Examples; + +namespace Spine.Unity.Editor { + + // This script is not intended for use with code. See the readme.txt file in SkeletonRendererCustomMaterials folder to learn more. + [CustomEditor(typeof(SkeletonRendererCustomMaterials))] + public class SkeletonRendererCustomMaterialsInspector : UnityEditor.Editor { + List componentCustomMaterialOverrides, _customMaterialOverridesPrev; + List componentCustomSlotMaterials, _customSlotMaterialsPrev; + SkeletonRendererCustomMaterials component; + + const BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic; + MethodInfo RemoveCustomMaterialOverrides, RemoveCustomSlotMaterials, SetCustomMaterialOverrides, SetCustomSlotMaterials; + + #region SkeletonRenderer context menu + [MenuItem("CONTEXT/SkeletonRenderer/Add Basic Serialized Custom Materials")] + static void AddSkeletonRendererCustomMaterials (MenuCommand menuCommand) { + var skeletonRenderer = (SkeletonRenderer)menuCommand.context; + var newComponent = skeletonRenderer.gameObject.AddComponent(); + Undo.RegisterCreatedObjectUndo(newComponent, "Add Basic Serialized Custom Materials"); + } + + [MenuItem("CONTEXT/SkeletonRenderer/Add Basic Serialized Custom Materials", true)] + static bool AddSkeletonRendererCustomMaterials_Validate (MenuCommand menuCommand) { + var skeletonRenderer = (SkeletonRenderer)menuCommand.context; + return (skeletonRenderer.GetComponent() == null); + } + #endregion + + void OnEnable () { + Type cm = typeof(SkeletonRendererCustomMaterials); + RemoveCustomMaterialOverrides = cm.GetMethod("RemoveCustomMaterialOverrides", PrivateInstance); + RemoveCustomSlotMaterials = cm.GetMethod("RemoveCustomSlotMaterials", PrivateInstance); + SetCustomMaterialOverrides = cm.GetMethod("SetCustomMaterialOverrides", PrivateInstance); + SetCustomSlotMaterials = cm.GetMethod("SetCustomSlotMaterials", PrivateInstance); + } + + public override void OnInspectorGUI () { + component = (SkeletonRendererCustomMaterials)target; + var skeletonRenderer = component.skeletonRenderer; + + // Draw the default inspector + DrawDefaultInspector(); + + if (serializedObject.isEditingMultipleObjects) + return; + + if (componentCustomMaterialOverrides == null) { + Type cm = typeof(SkeletonRendererCustomMaterials); + componentCustomMaterialOverrides = cm.GetField("customMaterialOverrides", PrivateInstance).GetValue(component) as List; + componentCustomSlotMaterials = cm.GetField("customSlotMaterials", PrivateInstance).GetValue(component) as List; + if (componentCustomMaterialOverrides == null) { + Debug.Log("Reflection failed."); + return; + } + } + + // Fill with current values at start + if (_customMaterialOverridesPrev == null || _customSlotMaterialsPrev == null) { + _customMaterialOverridesPrev = CopyList(componentCustomMaterialOverrides); + _customSlotMaterialsPrev = CopyList(componentCustomSlotMaterials); + } + + // Compare new values with saved. If change is detected: + // store new values, restore old values, remove overrides, restore new values, restore overrides. + + // 1. Store new values + var customMaterialOverridesNew = CopyList(componentCustomMaterialOverrides); + var customSlotMaterialsNew = CopyList(componentCustomSlotMaterials); + + // Detect changes + if (!_customMaterialOverridesPrev.SequenceEqual(customMaterialOverridesNew) || + !_customSlotMaterialsPrev.SequenceEqual(customSlotMaterialsNew)) { + // 2. Restore old values + componentCustomMaterialOverrides.Clear(); + componentCustomSlotMaterials.Clear(); + componentCustomMaterialOverrides.AddRange(_customMaterialOverridesPrev); + componentCustomSlotMaterials.AddRange(_customSlotMaterialsPrev); + + // 3. Remove overrides + RemoveCustomMaterials(); + + // 4. Restore new values + componentCustomMaterialOverrides.Clear(); + componentCustomSlotMaterials.Clear(); + componentCustomMaterialOverrides.AddRange(customMaterialOverridesNew); + componentCustomSlotMaterials.AddRange(customSlotMaterialsNew); + + // 5. Restore overrides + SetCustomMaterials(); + + if (skeletonRenderer != null) + skeletonRenderer.LateUpdate(); + } + + _customMaterialOverridesPrev = CopyList(componentCustomMaterialOverrides); + _customSlotMaterialsPrev = CopyList(componentCustomSlotMaterials); + + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent("Clear and Reapply Changes", tooltip: "Removes all non-serialized overrides in the SkeletonRenderer and reapplies the overrides on this component."))) { + if (skeletonRenderer != null) { + #if SPINE_OPTIONAL_MATERIALOVERRIDE + skeletonRenderer.CustomMaterialOverride.Clear(); + #endif + skeletonRenderer.CustomSlotMaterials.Clear(); + RemoveCustomMaterials(); + SetCustomMaterials(); + skeletonRenderer.LateUpdate(); + } + } + } + + void RemoveCustomMaterials () { + RemoveCustomMaterialOverrides.Invoke(component, null); + RemoveCustomSlotMaterials.Invoke(component, null); + } + + void SetCustomMaterials () { + SetCustomMaterialOverrides.Invoke(component, null); + SetCustomSlotMaterials.Invoke(component, null); + } + + static List CopyList (List list) { + return list.GetRange(0, list.Count); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs.meta new file mode 100644 index 0000000..1e37a56 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererCustomMaterialsInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e70f7f2a241d6d34aafd6a4a52a368d0 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs new file mode 100644 index 0000000..d668691 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs @@ -0,0 +1,593 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#else +#define NO_PREFAB_MESH +#endif + +#if UNITY_2018_1_OR_NEWER +#define PER_MATERIAL_PROPERTY_BLOCKS +#endif + +#if UNITY_2017_1_OR_NEWER +#define BUILT_IN_SPRITE_MASK_COMPONENT +#endif + +using UnityEditor; +using System.Collections.Generic; +using UnityEngine; +using System.Reflection; + +namespace Spine.Unity.Editor { + using Event = UnityEngine.Event; + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(SkeletonRenderer))] + [CanEditMultipleObjects] + public class SkeletonRendererInspector : UnityEditor.Editor { + public static bool advancedFoldout; + + const string SeparatorSlotNamesFieldName = "separatorSlotNames"; + + protected SerializedProperty skeletonDataAsset, initialSkinName; + protected SerializedProperty initialFlipX, initialFlipY; + protected SerializedProperty updateWhenInvisible, singleSubmesh, separatorSlotNames, clearStateOnDisable, immutableTriangles, fixDrawOrder; + protected SerializedProperty normals, tangents, zSpacing, pmaVertexColors, tintBlack; // MeshGenerator settings + protected SerializedProperty maskInteraction; + protected SerializedProperty maskMaterialsNone, maskMaterialsInside, maskMaterialsOutside; + protected SpineInspectorUtility.SerializedSortingProperties sortingProperties; + + protected bool isInspectingPrefab; + protected bool forceReloadQueued = false; + protected bool setMaskNoneMaterialsQueued = false; + protected bool setInsideMaskMaterialsQueued = false; + protected bool setOutsideMaskMaterialsQueued = false; + protected bool deleteInsideMaskMaterialsQueued = false; + protected bool deleteOutsideMaskMaterialsQueued = false; + + protected GUIContent SkeletonDataAssetLabel, SkeletonUtilityButtonContent; + protected GUIContent PMAVertexColorsLabel, ClearStateOnDisableLabel, ZSpacingLabel, ImmubleTrianglesLabel, TintBlackLabel, UpdateWhenInvisibleLabel, SingleSubmeshLabel, FixDrawOrderLabel; + protected GUIContent NormalsLabel, TangentsLabel, MaskInteractionLabel; + protected GUIContent MaskMaterialsHeadingLabel, MaskMaterialsNoneLabel, MaskMaterialsInsideLabel, MaskMaterialsOutsideLabel; + protected GUIContent SetMaterialButtonLabel, ClearMaterialButtonLabel, DeleteMaterialButtonLabel; + + const string ReloadButtonString = "Reload"; + static GUILayoutOption reloadButtonWidth; + static GUILayoutOption ReloadButtonWidth { get { return reloadButtonWidth = reloadButtonWidth ?? GUILayout.Width(GUI.skin.label.CalcSize(new GUIContent(ReloadButtonString)).x + 20); } } + static GUIStyle ReloadButtonStyle { get { return EditorStyles.miniButton; } } + + protected bool TargetIsValid { + get { + if (serializedObject.isEditingMultipleObjects) { + foreach (var o in targets) { + var component = (SkeletonRenderer)o; + if (!component.valid) + return false; + } + return true; + } else { + var component = (SkeletonRenderer)target; + return component.valid; + } + } + } + + protected virtual void OnEnable () { +#if NEW_PREFAB_SYSTEM + isInspectingPrefab = false; +#else + isInspectingPrefab = (PrefabUtility.GetPrefabType(target) == PrefabType.Prefab); +#endif + SpineEditorUtilities.ConfirmInitialization(); + + // Labels + SkeletonDataAssetLabel = new GUIContent("SkeletonData Asset", Icons.spine); + SkeletonUtilityButtonContent = new GUIContent("Add Skeleton Utility", Icons.skeletonUtility); + ImmubleTrianglesLabel = new GUIContent("Immutable Triangles", "Enable to optimize rendering for skeletons that never change attachment visbility"); + PMAVertexColorsLabel = new GUIContent("PMA Vertex Colors", "Use this if you are using the default Spine/Skeleton shader or any premultiply-alpha shader."); + ClearStateOnDisableLabel = new GUIContent("Clear State On Disable", "Use this if you are pooling or enabling/disabling your Spine GameObject."); + ZSpacingLabel = new GUIContent("Z Spacing", "A value other than 0 adds a space between each rendered attachment to prevent Z Fighting when using shaders that read or write to the depth buffer. Large values may cause unwanted parallax and spaces depending on camera setup."); + NormalsLabel = new GUIContent("Add Normals", "Use this if your shader requires vertex normals. A more efficient solution for 2D setups is to modify the shader to assume a single normal value for the whole mesh."); + TangentsLabel = new GUIContent("Solve Tangents", "Calculates the tangents per frame. Use this if you are using lit shaders (usually with normal maps) that require vertex tangents."); + TintBlackLabel = new GUIContent("Tint Black (!)", "Adds black tint vertex data to the mesh as UV2 and UV3. Black tinting requires that the shader interpret UV2 and UV3 as black tint colors for this effect to work. You may also use the default [Spine/Skeleton Tint Black] shader.\n\nIf you only need to tint the whole skeleton and not individual parts, the [Spine/Skeleton Tint] shader is recommended for better efficiency and changing/animating the _Black material property via MaterialPropertyBlock."); + SingleSubmeshLabel = new GUIContent("Use Single Submesh", "Simplifies submesh generation by assuming you are only using one Material and need only one submesh. This is will disable multiple materials, render separation, and custom slot materials."); + UpdateWhenInvisibleLabel = new GUIContent("Update When Invisible", "Update mode used when the MeshRenderer becomes invisible. Update mode is automatically reset to UpdateMode.FullUpdate when the mesh becomes visible again."); + FixDrawOrderLabel = new GUIContent("Fix Draw Order", "Applies only when 3+ submeshes are used (2+ materials with alternating order, e.g. \"A B A\"). If true, GPU instancing will be disabled at all materials and MaterialPropertyBlocks are assigned at each material to prevent aggressive batching of submeshes by e.g. the LWRP renderer, leading to incorrect draw order (e.g. \"A1 B A2\" changed to \"A1A2 B\"). You can disable this parameter when everything is drawn correctly to save the additional performance cost. Note: the GPU instancing setting will remain disabled at affected material assets after exiting play mode, you have to enable it manually if you accidentally enabled this parameter."); + MaskInteractionLabel = new GUIContent("Mask Interaction", "SkeletonRenderer's interaction with a Sprite Mask."); + MaskMaterialsHeadingLabel = new GUIContent("Mask Interaction Materials", "Materials used for different interaction with sprite masks."); + MaskMaterialsNoneLabel = new GUIContent("Normal Materials", "Normal materials used when Mask Interaction is set to None."); + MaskMaterialsInsideLabel = new GUIContent("Inside Mask", "Materials used when Mask Interaction is set to Inside Mask."); + MaskMaterialsOutsideLabel = new GUIContent("Outside Mask", "Materials used when Mask Interaction is set to Outside Mask."); + SetMaterialButtonLabel = new GUIContent("Set", "Prepares material references for switching to the corresponding Mask Interaction mode at runtime. Creates the required materials if they do not exist."); + ClearMaterialButtonLabel = new GUIContent("Clear", "Clears unused material references. Note: when switching to the corresponding Mask Interaction mode at runtime, a new material is generated on the fly."); + DeleteMaterialButtonLabel = new GUIContent("Delete", "Clears unused material references and deletes the corresponding assets. Note: when switching to the corresponding Mask Interaction mode at runtime, a new material is generated on the fly."); + + var so = this.serializedObject; + skeletonDataAsset = so.FindProperty("skeletonDataAsset"); + initialSkinName = so.FindProperty("initialSkinName"); + initialFlipX = so.FindProperty("initialFlipX"); + initialFlipY = so.FindProperty("initialFlipY"); + normals = so.FindProperty("addNormals"); + tangents = so.FindProperty("calculateTangents"); + immutableTriangles = so.FindProperty("immutableTriangles"); + pmaVertexColors = so.FindProperty("pmaVertexColors"); + clearStateOnDisable = so.FindProperty("clearStateOnDisable"); + tintBlack = so.FindProperty("tintBlack"); + updateWhenInvisible = so.FindProperty("updateWhenInvisible"); + singleSubmesh = so.FindProperty("singleSubmesh"); + fixDrawOrder = so.FindProperty("fixDrawOrder"); + maskInteraction = so.FindProperty("maskInteraction"); + maskMaterialsNone = so.FindProperty("maskMaterials.materialsMaskDisabled"); + maskMaterialsInside = so.FindProperty("maskMaterials.materialsInsideMask"); + maskMaterialsOutside = so.FindProperty("maskMaterials.materialsOutsideMask"); + + separatorSlotNames = so.FindProperty("separatorSlotNames"); + separatorSlotNames.isExpanded = true; + + zSpacing = so.FindProperty("zSpacing"); + + SerializedObject renderersSerializedObject = SpineInspectorUtility.GetRenderersSerializedObject(serializedObject); // Allows proper multi-edit behavior. + sortingProperties = new SpineInspectorUtility.SerializedSortingProperties(renderersSerializedObject); + } + + public void OnSceneGUI () { + var skeletonRenderer = (SkeletonRenderer)target; + var skeleton = skeletonRenderer.Skeleton; + var transform = skeletonRenderer.transform; + if (skeleton == null) return; + + SpineHandles.DrawBones(transform, skeleton); + } + + override public void OnInspectorGUI () { + bool multi = serializedObject.isEditingMultipleObjects; + DrawInspectorGUI(multi); + HandleSkinChange(); + if (serializedObject.ApplyModifiedProperties() || SpineInspectorUtility.UndoRedoPerformed(Event.current) || + AreAnyMaskMaterialsMissing()) { + if (!Application.isPlaying) { + foreach (var o in targets) + SpineEditorUtilities.ReinitializeComponent((SkeletonRenderer)o); + SceneView.RepaintAll(); + } + } + } + + protected virtual void DrawInspectorGUI (bool multi) { + // Initialize. + if (Event.current.type == EventType.Layout) { + if (forceReloadQueued) { + forceReloadQueued = false; + foreach (var c in targets) { + SpineEditorUtilities.ReloadSkeletonDataAssetAndComponent(c as SkeletonRenderer); + } + } else { + foreach (var c in targets) { + var component = c as SkeletonRenderer; + if (!component.valid) { + SpineEditorUtilities.ReinitializeComponent(component); + if (!component.valid) continue; + } + } + } + + #if BUILT_IN_SPRITE_MASK_COMPONENT + if (setMaskNoneMaterialsQueued) { + setMaskNoneMaterialsQueued = false; + foreach (var c in targets) + EditorSetMaskMaterials(c as SkeletonRenderer, SpriteMaskInteraction.None); + } + if (setInsideMaskMaterialsQueued) { + setInsideMaskMaterialsQueued = false; + foreach (var c in targets) + EditorSetMaskMaterials(c as SkeletonRenderer, SpriteMaskInteraction.VisibleInsideMask); + } + if (setOutsideMaskMaterialsQueued) { + setOutsideMaskMaterialsQueued = false; + foreach (var c in targets) + EditorSetMaskMaterials(c as SkeletonRenderer, SpriteMaskInteraction.VisibleOutsideMask); + } + + if (deleteInsideMaskMaterialsQueued) { + deleteInsideMaskMaterialsQueued = false; + foreach (var c in targets) + EditorDeleteMaskMaterials(c as SkeletonRenderer, SpriteMaskInteraction.VisibleInsideMask); + } + if (deleteOutsideMaskMaterialsQueued) { + deleteOutsideMaskMaterialsQueued = false; + foreach (var c in targets) + EditorDeleteMaskMaterials(c as SkeletonRenderer, SpriteMaskInteraction.VisibleOutsideMask); + } + #endif + +#if NO_PREFAB_MESH + if (isInspectingPrefab) { + foreach (var c in targets) { + var component = (SkeletonRenderer)c; + MeshFilter meshFilter = component.GetComponent(); + if (meshFilter != null && meshFilter.sharedMesh != null) + meshFilter.sharedMesh = null; + } + } +#endif + } + + bool valid = TargetIsValid; + + // Fields. + if (multi) { + using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox)) { + SpineInspectorUtility.PropertyFieldFitLabel(skeletonDataAsset, SkeletonDataAssetLabel); + if (GUILayout.Button(ReloadButtonString, ReloadButtonStyle, ReloadButtonWidth)) + forceReloadQueued = true; + } + + if (valid) EditorGUILayout.PropertyField(initialSkinName, SpineInspectorUtility.TempContent("Initial Skin")); + + } else { + var component = (SkeletonRenderer)target; + + using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox)) { + SpineInspectorUtility.PropertyFieldFitLabel(skeletonDataAsset, SkeletonDataAssetLabel); + if (component.valid) { + if (GUILayout.Button(ReloadButtonString, ReloadButtonStyle, ReloadButtonWidth)) + forceReloadQueued = true; + } + } + + if (component.skeletonDataAsset == null) { + EditorGUILayout.HelpBox("Skeleton Data Asset required", MessageType.Warning); + return; + } + + if (!SpineEditorUtilities.SkeletonDataAssetIsValid(component.skeletonDataAsset)) { + EditorGUILayout.HelpBox("Skeleton Data Asset error. Please check Skeleton Data Asset.", MessageType.Error); + return; + } + + if (valid) + EditorGUILayout.PropertyField(initialSkinName, SpineInspectorUtility.TempContent("Initial Skin")); + + } + + EditorGUILayout.Space(); + + // Sorting Layers + SpineInspectorUtility.SortingPropertyFields(sortingProperties, applyModifiedProperties: true); + + if (maskInteraction != null) EditorGUILayout.PropertyField(maskInteraction, MaskInteractionLabel); + + if (!valid) + return; + + string errorMessage = null; + if (SpineEditorUtilities.Preferences.componentMaterialWarning && + MaterialChecks.IsMaterialSetupProblematic((SkeletonRenderer)this.target, ref errorMessage)) { + EditorGUILayout.HelpBox(errorMessage, MessageType.Error, true); + } + + // More Render Options... + using (new SpineInspectorUtility.BoxScope()) { + EditorGUI.BeginChangeCheck(); + + EditorGUILayout.BeginHorizontal(GUILayout.Height(EditorGUIUtility.singleLineHeight + 5)); + advancedFoldout = EditorGUILayout.Foldout(advancedFoldout, "Advanced"); + if (advancedFoldout) { + EditorGUILayout.Space(); + if (GUILayout.Button("Debug", EditorStyles.miniButton, GUILayout.Width(65f))) + SkeletonDebugWindow.Init(); + } else { + EditorGUILayout.Space(); + } + EditorGUILayout.EndHorizontal(); + + if (advancedFoldout) { + + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.HorizontalScope()) { + SpineInspectorUtility.ToggleLeftLayout(initialFlipX); + SpineInspectorUtility.ToggleLeftLayout(initialFlipY); + EditorGUILayout.Space(); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Renderer Settings", EditorStyles.boldLabel); + using (new SpineInspectorUtility.LabelWidthScope()) { + // Optimization options + if (updateWhenInvisible != null) EditorGUILayout.PropertyField(updateWhenInvisible, UpdateWhenInvisibleLabel); + + if (singleSubmesh != null) EditorGUILayout.PropertyField(singleSubmesh, SingleSubmeshLabel); + #if PER_MATERIAL_PROPERTY_BLOCKS + if (fixDrawOrder != null) EditorGUILayout.PropertyField(fixDrawOrder, FixDrawOrderLabel); + #endif + if (immutableTriangles != null) EditorGUILayout.PropertyField(immutableTriangles, ImmubleTrianglesLabel); + EditorGUILayout.PropertyField(clearStateOnDisable, ClearStateOnDisableLabel); + EditorGUILayout.Space(); + } + + SeparatorsField(separatorSlotNames); + EditorGUILayout.Space(); + + // Render options + const float MinZSpacing = -0.1f; + const float MaxZSpacing = 0f; + EditorGUILayout.Slider(zSpacing, MinZSpacing, MaxZSpacing, ZSpacingLabel); + EditorGUILayout.Space(); + + using (new SpineInspectorUtility.LabelWidthScope()) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Vertex Data", SpineInspectorUtility.UnityIcon()), EditorStyles.boldLabel); + if (pmaVertexColors != null) EditorGUILayout.PropertyField(pmaVertexColors, PMAVertexColorsLabel); + EditorGUILayout.PropertyField(tintBlack, TintBlackLabel); + + // Optional fields. May be disabled in SkeletonRenderer. + if (normals != null) EditorGUILayout.PropertyField(normals, NormalsLabel); + if (tangents != null) EditorGUILayout.PropertyField(tangents, TangentsLabel); + } + + #if BUILT_IN_SPRITE_MASK_COMPONENT + EditorGUILayout.Space(); + if (maskMaterialsNone.arraySize > 0 || maskMaterialsInside.arraySize > 0 || maskMaterialsOutside.arraySize > 0) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Mask Interaction Materials", SpineInspectorUtility.UnityIcon()), EditorStyles.boldLabel); + bool differentMaskModesSelected = maskInteraction.hasMultipleDifferentValues; + int activeMaskInteractionValue = differentMaskModesSelected ? -1 : maskInteraction.intValue; + + bool ignoredParam = true; + MaskMaterialsEditingField(ref setMaskNoneMaterialsQueued, ref ignoredParam, maskMaterialsNone, MaskMaterialsNoneLabel, + differentMaskModesSelected, allowDelete : false, isActiveMaterial : activeMaskInteractionValue == (int)SpriteMaskInteraction.None); + MaskMaterialsEditingField(ref setInsideMaskMaterialsQueued, ref deleteInsideMaskMaterialsQueued, maskMaterialsInside, MaskMaterialsInsideLabel, + differentMaskModesSelected, allowDelete: true, isActiveMaterial: activeMaskInteractionValue == (int)SpriteMaskInteraction.VisibleInsideMask); + MaskMaterialsEditingField(ref setOutsideMaskMaterialsQueued, ref deleteOutsideMaskMaterialsQueued, maskMaterialsOutside, MaskMaterialsOutsideLabel, + differentMaskModesSelected, allowDelete : true, isActiveMaterial: activeMaskInteractionValue == (int)SpriteMaskInteraction.VisibleOutsideMask); + } + #endif + + EditorGUILayout.Space(); + + if (valid && !isInspectingPrefab) { + if (multi) { + // Support multi-edit SkeletonUtility button. + // EditorGUILayout.Space(); + // bool addSkeletonUtility = GUILayout.Button(buttonContent, GUILayout.Height(30)); + // foreach (var t in targets) { + // var component = t as Component; + // if (addSkeletonUtility && component.GetComponent() == null) + // component.gameObject.AddComponent(); + // } + } else { + var component = (Component)target; + if (component.GetComponent() == null) { + if (SpineInspectorUtility.CenteredButton(SkeletonUtilityButtonContent, 21, true, 200f)) + component.gameObject.AddComponent(); + } + } + } + + EditorGUILayout.Space(); + } + } + + if (EditorGUI.EndChangeCheck()) + SceneView.RepaintAll(); + } + } + + protected void SkeletonRootMotionParameter() { + SkeletonRootMotionParameter(targets); + } + + public static void SkeletonRootMotionParameter(Object[] targets) { + int rootMotionComponentCount = 0; + foreach (var t in targets) { + var component = t as Component; + if (component.GetComponent() != null) { + ++rootMotionComponentCount; + } + } + bool allHaveRootMotion = rootMotionComponentCount == targets.Length; + bool anyHaveRootMotion = rootMotionComponentCount > 0; + + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.PrefixLabel("Root Motion"); + + if (!allHaveRootMotion) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Add Component", Icons.constraintTransform), GUILayout.MaxWidth(130), GUILayout.Height(18))) { + foreach (var t in targets) { + var component = t as Component; + if (component.GetComponent() == null) { + component.gameObject.AddComponent(); + } + } + } + } + if (anyHaveRootMotion) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Remove Component", Icons.constraintTransform), GUILayout.MaxWidth(140), GUILayout.Height(18))) { + foreach (var t in targets) { + var component = t as Component; + var rootMotionComponent = component.GetComponent(); + if (rootMotionComponent != null) { + DestroyImmediate(rootMotionComponent); + } + } + } + } + } + } + + public static void SetSeparatorSlotNames (SkeletonRenderer skeletonRenderer, string[] newSlotNames) { + var field = SpineInspectorUtility.GetNonPublicField(typeof(SkeletonRenderer), SeparatorSlotNamesFieldName); + field.SetValue(skeletonRenderer, newSlotNames); + } + + public static string[] GetSeparatorSlotNames (SkeletonRenderer skeletonRenderer) { + var field = SpineInspectorUtility.GetNonPublicField(typeof(SkeletonRenderer), SeparatorSlotNamesFieldName); + return field.GetValue(skeletonRenderer) as string[]; + } + + public static void SeparatorsField (SerializedProperty separatorSlotNames) { + bool multi = separatorSlotNames.serializedObject.isEditingMultipleObjects; + bool hasTerminalSlot = false; + if (!multi) { + var sr = separatorSlotNames.serializedObject.targetObject as ISkeletonComponent; + var skeleton = sr.Skeleton; + int lastSlot = skeleton.Slots.Count - 1; + if (skeleton != null) { + for (int i = 0, n = separatorSlotNames.arraySize; i < n; i++) { + int index = skeleton.FindSlotIndex(separatorSlotNames.GetArrayElementAtIndex(i).stringValue); + if (index == 0 || index == lastSlot) { + hasTerminalSlot = true; + break; + } + } + } + } + + string terminalSlotWarning = hasTerminalSlot ? " (!)" : ""; + + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { + const string SeparatorsDescription = "Stored names of slots where the Skeleton's render will be split into different batches. This is used by separate components that split the render into different MeshRenderers or GameObjects."; + if (separatorSlotNames.isExpanded) { + EditorGUILayout.PropertyField(separatorSlotNames, SpineInspectorUtility.TempContent(separatorSlotNames.displayName + terminalSlotWarning, Icons.slotRoot, SeparatorsDescription), true); + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("+", GUILayout.MaxWidth(28f), GUILayout.MaxHeight(15f))) { + separatorSlotNames.arraySize++; + } + GUILayout.EndHorizontal(); + + EditorGUILayout.Space(); + } else + EditorGUILayout.PropertyField(separatorSlotNames, new GUIContent(separatorSlotNames.displayName + string.Format("{0} [{1}]", terminalSlotWarning, separatorSlotNames.arraySize), SeparatorsDescription), true); + } + } + + public void MaskMaterialsEditingField(ref bool wasSetRequested, ref bool wasDeleteRequested, + SerializedProperty maskMaterials, GUIContent label, + bool differentMaskModesSelected, bool allowDelete, bool isActiveMaterial) { + using (new EditorGUILayout.HorizontalScope()) { + + EditorGUILayout.LabelField(label, isActiveMaterial ? EditorStyles.boldLabel : EditorStyles.label, GUILayout.MinWidth(80f), GUILayout.MaxWidth(140)); + EditorGUILayout.LabelField(maskMaterials.hasMultipleDifferentValues ? "-" : maskMaterials.arraySize.ToString(), EditorStyles.miniLabel, GUILayout.Width(42f)); + + bool enableSetButton = differentMaskModesSelected || maskMaterials.arraySize == 0; + bool enableClearButtons = differentMaskModesSelected || (maskMaterials.arraySize != 0 && !isActiveMaterial); + + EditorGUI.BeginDisabledGroup(!enableSetButton); + if (GUILayout.Button(SetMaterialButtonLabel, EditorStyles.miniButtonLeft, GUILayout.Width(46f))) { + wasSetRequested = true; + } + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginDisabledGroup(!enableClearButtons); + { + if (GUILayout.Button(ClearMaterialButtonLabel, allowDelete ? EditorStyles.miniButtonMid : EditorStyles.miniButtonRight, GUILayout.Width(46f))) { + maskMaterials.ClearArray(); + } + else if (allowDelete && GUILayout.Button(DeleteMaterialButtonLabel, EditorStyles.miniButtonRight, GUILayout.Width(46f))) { + wasDeleteRequested = true; + } + if (!allowDelete) + GUILayout.Space(46f); + } + EditorGUI.EndDisabledGroup(); + } + } + + void HandleSkinChange() { + if (!Application.isPlaying && Event.current.type == EventType.Layout && !initialSkinName.hasMultipleDifferentValues) { + bool mismatchDetected = false; + string newSkinName = initialSkinName.stringValue; + foreach (var o in targets) { + mismatchDetected |= UpdateIfSkinMismatch((SkeletonRenderer)o, newSkinName); + } + + if (mismatchDetected) { + mismatchDetected = false; + UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); + } + } + } + + static bool UpdateIfSkinMismatch (SkeletonRenderer skeletonRenderer, string componentSkinName) { + if (!skeletonRenderer.valid || skeletonRenderer.EditorSkipSkinSync) return false; + + var skin = skeletonRenderer.Skeleton.Skin; + string skeletonSkinName = skin != null ? skin.Name : null; + bool defaultCase = skin == null && string.IsNullOrEmpty(componentSkinName); + bool fieldMatchesSkin = defaultCase || string.Equals(componentSkinName, skeletonSkinName, System.StringComparison.Ordinal); + + if (!fieldMatchesSkin) { + Skin skinToSet = string.IsNullOrEmpty(componentSkinName) ? null : skeletonRenderer.Skeleton.Data.FindSkin(componentSkinName); + skeletonRenderer.Skeleton.SetSkin(skinToSet); + skeletonRenderer.Skeleton.SetSlotsToSetupPose(); + + // Note: the UpdateIfSkinMismatch concept shall be replaced with e.g. an OnValidate based + // solution or in a separate commit. The current solution does not repaint the Game view because + // it is first applying values and in the next editor pass is calling this skin-changing method. + if (skeletonRenderer is SkeletonAnimation) + ((SkeletonAnimation) skeletonRenderer).Update(0f); + else if (skeletonRenderer is SkeletonMecanim) + ((SkeletonMecanim) skeletonRenderer).Update(); + + skeletonRenderer.LateUpdate(); + return true; + } + return false; + } + + bool AreAnyMaskMaterialsMissing() { + #if BUILT_IN_SPRITE_MASK_COMPONENT + foreach (var o in targets) { + var component = (SkeletonRenderer)o; + if (!component.valid) + continue; + if (SpineMaskUtilities.AreMaskMaterialsMissing(component)) + return true; + } + #endif + return false; + } + + #if BUILT_IN_SPRITE_MASK_COMPONENT + static void EditorSetMaskMaterials(SkeletonRenderer component, SpriteMaskInteraction maskType) + { + if (component == null) return; + if (!SpineEditorUtilities.SkeletonDataAssetIsValid(component.SkeletonDataAsset)) return; + SpineMaskUtilities.EditorInitMaskMaterials(component, component.maskMaterials, maskType); + } + + static void EditorDeleteMaskMaterials(SkeletonRenderer component, SpriteMaskInteraction maskType) { + if (component == null) return; + if (!SpineEditorUtilities.SkeletonDataAssetIsValid(component.SkeletonDataAsset)) return; + SpineMaskUtilities.EditorDeleteMaskMaterials(component.maskMaterials, maskType); + } + #endif + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs.meta new file mode 100644 index 0000000..d7791c6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRendererInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d0fc5db9788bce4418ad3252d43faa8a +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs new file mode 100644 index 0000000..8314eb0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs @@ -0,0 +1,113 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + [CustomEditor(typeof(SkeletonRootMotionBase))] + [CanEditMultipleObjects] + public class SkeletonRootMotionBaseInspector : UnityEditor.Editor { + protected SerializedProperty rootMotionBoneName; + protected SerializedProperty transformPositionX; + protected SerializedProperty transformPositionY; + protected SerializedProperty rootMotionScaleX; + protected SerializedProperty rootMotionScaleY; + protected SerializedProperty rootMotionTranslateXPerY; + protected SerializedProperty rootMotionTranslateYPerX; + protected SerializedProperty rigidBody2D; + protected SerializedProperty rigidBody; + + protected GUIContent rootMotionBoneNameLabel; + protected GUIContent transformPositionXLabel; + protected GUIContent transformPositionYLabel; + protected GUIContent rootMotionScaleXLabel; + protected GUIContent rootMotionScaleYLabel; + protected GUIContent rootMotionTranslateXPerYLabel; + protected GUIContent rootMotionTranslateYPerXLabel; + protected GUIContent rigidBody2DLabel; + protected GUIContent rigidBodyLabel; + + protected virtual void OnEnable () { + + rootMotionBoneName = serializedObject.FindProperty("rootMotionBoneName"); + transformPositionX = serializedObject.FindProperty("transformPositionX"); + transformPositionY = serializedObject.FindProperty("transformPositionY"); + rootMotionScaleX = serializedObject.FindProperty("rootMotionScaleX"); + rootMotionScaleY = serializedObject.FindProperty("rootMotionScaleY"); + rootMotionTranslateXPerY = serializedObject.FindProperty("rootMotionTranslateXPerY"); + rootMotionTranslateYPerX = serializedObject.FindProperty("rootMotionTranslateYPerX"); + rigidBody2D = serializedObject.FindProperty("rigidBody2D"); + rigidBody = serializedObject.FindProperty("rigidBody"); + + rootMotionBoneNameLabel = new UnityEngine.GUIContent("Root Motion Bone", "The bone to take the motion from."); + transformPositionXLabel = new UnityEngine.GUIContent("X", "Root transform position (X)"); + transformPositionYLabel = new UnityEngine.GUIContent("Y", "Use the Y-movement of the bone."); + rootMotionScaleXLabel = new UnityEngine.GUIContent("Root Motion Scale (X)", "Scale applied to the horizontal root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired distance."); + rootMotionScaleYLabel = new UnityEngine.GUIContent("Root Motion Scale (Y)", "Scale applied to the vertical root motion delta. Can be used for delta compensation to e.g. stretch a jump to the desired distance."); + rootMotionTranslateXPerYLabel = new UnityEngine.GUIContent("Root Motion Translate (X)", "Added X translation per root motion Y delta. Can be used for delta compensation when scaling is not enough, to e.g. offset a horizontal jump to a vertically different goal."); + rootMotionTranslateYPerXLabel = new UnityEngine.GUIContent("Root Motion Translate (Y)", "Added Y translation per root motion X delta. Can be used for delta compensation when scaling is not enough, to e.g. offset a horizontal jump to a vertically different goal."); + rigidBody2DLabel = new UnityEngine.GUIContent("Rigidbody2D", + "Optional Rigidbody2D: Assign a Rigidbody2D here if you want " + + " to apply the root motion to the rigidbody instead of the Transform." + + "\n\n" + + "Note that animation and physics updates are not always in sync." + + "Some jitter may result at certain framerates."); + rigidBodyLabel = new UnityEngine.GUIContent("Rigidbody", + "Optional Rigidbody: Assign a Rigidbody here if you want " + + " to apply the root motion to the rigidbody instead of the Transform." + + "\n\n" + + "Note that animation and physics updates are not always in sync." + + "Some jitter may result at certain framerates."); + } + + public override void OnInspectorGUI () { + MainPropertyFields(); + OptionalPropertyFields(); + serializedObject.ApplyModifiedProperties(); + } + + protected virtual void MainPropertyFields () { + EditorGUILayout.PropertyField(rootMotionBoneName, rootMotionBoneNameLabel); + EditorGUILayout.PropertyField(transformPositionX, transformPositionXLabel); + EditorGUILayout.PropertyField(transformPositionY, transformPositionYLabel); + + EditorGUILayout.PropertyField(rootMotionScaleX, rootMotionScaleXLabel); + EditorGUILayout.PropertyField(rootMotionScaleY, rootMotionScaleYLabel); + + EditorGUILayout.PropertyField(rootMotionTranslateXPerY, rootMotionTranslateXPerYLabel); + EditorGUILayout.PropertyField(rootMotionTranslateYPerX, rootMotionTranslateYPerXLabel); + } + + protected virtual void OptionalPropertyFields () { + EditorGUILayout.PropertyField(rigidBody2D, rigidBody2DLabel); + EditorGUILayout.PropertyField(rigidBody, rigidBodyLabel); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs.meta new file mode 100644 index 0000000..0304448 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionBaseInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f2cba83baf6afdf44a996e40017c6325 +timeCreated: 1593175106 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs new file mode 100644 index 0000000..2c96506 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs @@ -0,0 +1,79 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + [CustomEditor(typeof(SkeletonRootMotion))] + [CanEditMultipleObjects] + public class SkeletonRootMotionInspector : SkeletonRootMotionBaseInspector { + protected SerializedProperty animationTrackFlags; + protected GUIContent animationTrackFlagsLabel; + + string[] TrackNames; + + protected override void OnEnable () { + base.OnEnable(); + + animationTrackFlags = serializedObject.FindProperty("animationTrackFlags"); + animationTrackFlagsLabel = new UnityEngine.GUIContent("Animation Tracks", + "Animation tracks to apply root motion at. Defaults to the first" + + " animation track (index 0)."); + } + + override public void OnInspectorGUI () { + + base.MainPropertyFields(); + AnimationTracksPropertyField(); + + base.OptionalPropertyFields(); + serializedObject.ApplyModifiedProperties(); + } + + protected void AnimationTracksPropertyField () { + + if (TrackNames == null) { + InitTrackNames(); + + } + + animationTrackFlags.intValue = EditorGUILayout.MaskField( + animationTrackFlagsLabel, animationTrackFlags.intValue, TrackNames); + } + + protected void InitTrackNames () { + int numEntries = 32; + TrackNames = new string[numEntries]; + for (int i = 0; i < numEntries; ++i) { + TrackNames[i] = string.Format("Track {0}", i); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs.meta new file mode 100644 index 0000000..7c357a8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonRootMotionInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e4836100aed984c4a9af11d39c63cb6b +timeCreated: 1593183609 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs new file mode 100644 index 0000000..b4e12b6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs @@ -0,0 +1,541 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Contributed by: Mitch Thompson + +#if UNITY_2019_2_OR_NEWER +#define HINGE_JOINT_NEW_BEHAVIOUR +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using Spine; + +namespace Spine.Unity.Editor { + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(SkeletonUtilityBone)), CanEditMultipleObjects] + public class SkeletonUtilityBoneInspector : UnityEditor.Editor { + SerializedProperty mode, boneName, zPosition, position, rotation, scale, overrideAlpha, hierarchy, parentReference; + GUIContent hierarchyLabel; + + //multi selected flags + bool containsFollows, containsOverrides, multiObject; + + //single selected helpers + SkeletonUtilityBone utilityBone; + SkeletonUtility skeletonUtility; + bool canCreateHingeChain = false; + + Dictionary> boundingBoxTable = new Dictionary>(); + + void OnEnable () { + mode = this.serializedObject.FindProperty("mode"); + boneName = this.serializedObject.FindProperty("boneName"); + zPosition = this.serializedObject.FindProperty("zPosition"); + position = this.serializedObject.FindProperty("position"); + rotation = this.serializedObject.FindProperty("rotation"); + scale = this.serializedObject.FindProperty("scale"); + overrideAlpha = this.serializedObject.FindProperty("overrideAlpha"); + hierarchy = this.serializedObject.FindProperty("hierarchy"); + hierarchyLabel = new GUIContent("Skeleton Utility Parent"); + parentReference = this.serializedObject.FindProperty("parentReference"); + + utilityBone = (SkeletonUtilityBone)target; + skeletonUtility = utilityBone.hierarchy; + EvaluateFlags(); + + if (!utilityBone.valid && skeletonUtility != null) { + if (skeletonUtility.skeletonRenderer != null) + skeletonUtility.skeletonRenderer.Initialize(false); + if (skeletonUtility.skeletonGraphic != null) + skeletonUtility.skeletonGraphic.Initialize(false); + } + + canCreateHingeChain = CanCreateHingeChain(); + boundingBoxTable.Clear(); + + if (multiObject) return; + if (utilityBone.bone == null) return; + + var skeleton = utilityBone.bone.Skeleton; + int slotCount = skeleton.Slots.Count; + Skin skin = skeleton.Skin; + if (skeleton.Skin == null) + skin = skeleton.Data.DefaultSkin; + + for(int i = 0; i < slotCount; i++){ + Slot slot = skeletonUtility.Skeleton.Slots.Items[i]; + if (slot.Bone == utilityBone.bone) { + var slotAttachments = new List(); + int slotIndex = skeleton.FindSlotIndex(slot.Data.Name); + skin.GetAttachments(slotIndex, slotAttachments); + + var boundingBoxes = new List(); + foreach (var att in slotAttachments) { + var boundingBoxAttachment = att.Attachment as BoundingBoxAttachment; + if (boundingBoxAttachment != null) + boundingBoxes.Add(boundingBoxAttachment); + } + + if (boundingBoxes.Count > 0) + boundingBoxTable.Add(slot, boundingBoxes); + } + } + } + + void EvaluateFlags () { + if (Selection.objects.Length == 1) { + containsFollows = utilityBone.mode == SkeletonUtilityBone.Mode.Follow; + containsOverrides = utilityBone.mode == SkeletonUtilityBone.Mode.Override; + } else { + int boneCount = 0; + foreach (Object o in Selection.objects) { + var go = o as GameObject; + if (go != null) { + SkeletonUtilityBone sub = go.GetComponent(); + if (sub != null) { + boneCount++; + containsFollows |= (sub.mode == SkeletonUtilityBone.Mode.Follow); + containsOverrides |= (sub.mode == SkeletonUtilityBone.Mode.Override); + } + } + } + + multiObject |= (boneCount > 1); + } + } + + public override void OnInspectorGUI () { + serializedObject.Update(); + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(mode); + if (EditorGUI.EndChangeCheck()) { + containsOverrides = mode.enumValueIndex == 1; + containsFollows = mode.enumValueIndex == 0; + } + + using (new EditorGUI.DisabledGroupScope(multiObject)) { + string str = boneName.stringValue; + if (str == "") + str = ""; + if (multiObject) + str = ""; + + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.PrefixLabel("Bone"); + if (GUILayout.Button(str, EditorStyles.popup)) { + BoneSelectorContextMenu(str, ((SkeletonUtilityBone)target).hierarchy.Skeleton.Bones, "", TargetBoneSelected); + } + } + } + + EditorGUILayout.PropertyField(zPosition); + EditorGUILayout.PropertyField(position); + EditorGUILayout.PropertyField(rotation); + EditorGUILayout.PropertyField(scale); + + using (new EditorGUI.DisabledGroupScope(containsFollows)) { + EditorGUILayout.PropertyField(overrideAlpha); + EditorGUILayout.PropertyField(parentReference); + EditorGUILayout.PropertyField(hierarchy, hierarchyLabel); + } + + EditorGUILayout.Space(); + + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || utilityBone.bone == null || utilityBone.bone.Children.Count == 0)) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Add Child Bone", Icons.bone), GUILayout.MinWidth(120), GUILayout.Height(24))) + BoneSelectorContextMenu("", utilityBone.bone.Children, "", SpawnChildBoneSelected); + } + using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || utilityBone.bone == null || containsOverrides)) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Add Override", Icons.poseBones), GUILayout.MinWidth(120), GUILayout.Height(24))) + SpawnOverride(); + } + EditorGUILayout.Space(); + } + EditorGUILayout.Space(); + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + using (new EditorGUI.DisabledGroupScope(multiObject || !utilityBone.valid || !canCreateHingeChain)) { + if (GUILayout.Button(SpineInspectorUtility.TempContent("Create 3D Hinge Chain", Icons.hingeChain), GUILayout.MinWidth(120), GUILayout.Height(24))) + CreateHingeChain(); + if (GUILayout.Button(SpineInspectorUtility.TempContent("Create 2D Hinge Chain", Icons.hingeChain), GUILayout.MinWidth(120), GUILayout.Height(24))) + CreateHingeChain2D(); + } + EditorGUILayout.Space(); + } + + using (new EditorGUI.DisabledGroupScope(multiObject || boundingBoxTable.Count == 0)) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Bounding Boxes", Icons.boundingBox), EditorStyles.boldLabel); + + foreach (var entry in boundingBoxTable){ + Slot slot = entry.Key; + var boundingBoxes = entry.Value; + + EditorGUI.indentLevel++; + EditorGUILayout.LabelField(slot.Data.Name); + EditorGUI.indentLevel++; + { + foreach (var box in boundingBoxes) { + using (new GUILayout.HorizontalScope()) { + GUILayout.Space(30); + string buttonLabel = box.IsWeighted() ? box.Name + " (!)" : box.Name; + if (GUILayout.Button(buttonLabel, GUILayout.Width(200))) { + utilityBone.bone.Skeleton.UpdateWorldTransform(); + var bbTransform = utilityBone.transform.Find("[BoundingBox]" + box.Name); // Use FindChild in older versions of Unity. + if (bbTransform != null) { + var originalCollider = bbTransform.GetComponent(); + if (originalCollider != null) + SkeletonUtility.SetColliderPointsLocal(originalCollider, slot, box); + else + SkeletonUtility.AddBoundingBoxAsComponent(box, slot, bbTransform.gameObject); + } else { + var newPolygonCollider = SkeletonUtility.AddBoundingBoxGameObject(null, box, slot, utilityBone.transform); + bbTransform = newPolygonCollider.transform; + } + EditorGUIUtility.PingObject(bbTransform); + } + } + + } + } + EditorGUI.indentLevel--; + EditorGUI.indentLevel--; + } + } + + BoneFollowerInspector.RecommendRigidbodyButton(utilityBone); + + serializedObject.ApplyModifiedProperties(); + } + + static void BoneSelectorContextMenu (string current, ExposedList bones, string topValue, GenericMenu.MenuFunction2 callback) { + var menu = new GenericMenu(); + + if (topValue != "") + menu.AddItem(new GUIContent(topValue), current == topValue, callback, null); + + for (int i = 0; i < bones.Count; i++) + menu.AddItem(new GUIContent(bones.Items[i].Data.Name), bones.Items[i].Data.Name == current, callback, bones.Items[i]); + + menu.ShowAsContext(); + } + + void TargetBoneSelected (object obj) { + if (obj == null) { + boneName.stringValue = ""; + serializedObject.ApplyModifiedProperties(); + } else { + var bone = (Bone)obj; + boneName.stringValue = bone.Data.Name; + serializedObject.ApplyModifiedProperties(); + utilityBone.Reset(); + } + } + + void SpawnChildBoneSelected (object obj) { + if (obj == null) { + // Add recursively + foreach (var bone in utilityBone.bone.Children) { + GameObject go = skeletonUtility.SpawnBoneRecursively(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); + SkeletonUtilityBone[] newUtilityBones = go.GetComponentsInChildren(); + foreach (SkeletonUtilityBone utilBone in newUtilityBones) + SkeletonUtilityInspector.AttachIcon(utilBone); + } + } else { + var bone = (Bone)obj; + GameObject go = skeletonUtility.SpawnBone(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); + SkeletonUtilityInspector.AttachIcon(go.GetComponent()); + Selection.activeGameObject = go; + EditorGUIUtility.PingObject(go); + } + } + + void SpawnOverride () { + GameObject go = skeletonUtility.SpawnBone(utilityBone.bone, utilityBone.transform.parent, SkeletonUtilityBone.Mode.Override, utilityBone.position, utilityBone.rotation, utilityBone.scale); + go.name = go.name + " [Override]"; + SkeletonUtilityInspector.AttachIcon(go.GetComponent()); + Selection.activeGameObject = go; + EditorGUIUtility.PingObject(go); + } + + bool CanCreateHingeChain () { + if (utilityBone == null) + return false; + if (utilityBone.GetComponent() != null || utilityBone.GetComponent() != null) + return false; + if (utilityBone.bone != null && utilityBone.bone.Children.Count == 0) + return false; + + var rigidbodies = utilityBone.GetComponentsInChildren(); + var rigidbodies2D = utilityBone.GetComponentsInChildren(); + return rigidbodies.Length <= 0 && rigidbodies2D.Length <= 0; + } + + void CreateHingeChain2D () { + var kinematicParentUtilityBone = utilityBone.transform.parent.GetComponent(); + if (kinematicParentUtilityBone == null) { + UnityEditor.EditorUtility.DisplayDialog("No parent SkeletonUtilityBone found!", "Please select the first physically moving chain node, having a parent GameObject with a SkeletonUtilityBone component attached.", "OK"); + return; + } + + float mass = 10; + const float rotationLimit = 20.0f; + + SetSkeletonUtilityToFlipByRotation(); + + kinematicParentUtilityBone.mode = SkeletonUtilityBone.Mode.Follow; + kinematicParentUtilityBone.position = kinematicParentUtilityBone.rotation = kinematicParentUtilityBone.scale = kinematicParentUtilityBone.zPosition = true; + + GameObject commonParentObject = new GameObject(skeletonUtility.name + " HingeChain Parent " + utilityBone.name); + var commonParentActivateOnFlip = commonParentObject.AddComponent(); + commonParentActivateOnFlip.skeletonRenderer = skeletonUtility.skeletonRenderer; + commonParentActivateOnFlip.skeletonGraphic = skeletonUtility.skeletonGraphic; + + // HingeChain Parent + // Needs to be on top hierarchy level (not attached to the moving skeleton at least) for physics to apply proper momentum. + GameObject normalChainParentObject = new GameObject("HingeChain"); + normalChainParentObject.transform.SetParent(commonParentObject.transform); + commonParentActivateOnFlip.activeOnNormalX = normalChainParentObject; + + //var followRotationComponent = normalChainParentObject.AddComponent(); + //followRotationComponent.reference = skeletonUtility.boneRoot; + + // Follower Kinematic Rigidbody + GameObject followerKinematicObject = new GameObject(kinematicParentUtilityBone.name + " Follower"); + followerKinematicObject.transform.parent = normalChainParentObject.transform; + var followerRigidbody = followerKinematicObject.AddComponent(); + followerRigidbody.mass = mass; + followerRigidbody.isKinematic = true; + followerKinematicObject.AddComponent().reference = kinematicParentUtilityBone.transform; + followerKinematicObject.transform.position = kinematicParentUtilityBone.transform.position; + followerKinematicObject.transform.rotation = kinematicParentUtilityBone.transform.rotation; + + // Child Bones + var utilityBones = utilityBone.GetComponentsInChildren(); + var childBoneParentReference = followerKinematicObject.transform; + for (int i = 0; i < utilityBones.Length; ++i) { + var childBone = utilityBones[i]; + mass *= 0.75f; + childBone.parentReference = (i == 0) ? kinematicParentUtilityBone.transform : childBoneParentReference; + childBone.transform.SetParent(normalChainParentObject.transform, true); // we need a flat hierarchy of all Joint objects in Unity. + AttachRigidbodyAndCollider2D(childBone); + childBone.mode = SkeletonUtilityBone.Mode.Override; + childBone.scale = childBone.position = childBone.zPosition = false; + + HingeJoint2D joint = childBone.gameObject.AddComponent(); + joint.connectedBody = childBoneParentReference.GetComponent(); + joint.useLimits = true; + ApplyJoint2DAngleLimits(joint, rotationLimit, childBoneParentReference, childBone.transform); + + childBone.GetComponent().mass = mass; + childBoneParentReference = childBone.transform; + } + + Duplicate2DHierarchyForFlippedChains(normalChainParentObject, commonParentActivateOnFlip, skeletonUtility.transform, rotationLimit); + UnityEditor.Selection.activeGameObject = commonParentObject; + } + + void ApplyJoint2DAngleLimits (HingeJoint2D joint, float rotationLimit, Transform parentBone, Transform bone) { + #if HINGE_JOINT_NEW_BEHAVIOUR + float referenceAngle = (parentBone.eulerAngles.z - bone.eulerAngles.z + 360f) % 360f; + float minAngle = referenceAngle - rotationLimit; + float maxAngle = referenceAngle + rotationLimit; + if (maxAngle > 270f) { + minAngle -= 360f; + maxAngle -= 360f; + } + if (minAngle < -90f) { + minAngle += 360f; + maxAngle += 360f; + } +#else + float minAngle = - rotationLimit; + float maxAngle = rotationLimit; +#endif + joint.limits = new JointAngleLimits2D { + min = minAngle, + max = maxAngle + }; + } + + void Duplicate2DHierarchyForFlippedChains (GameObject normalChainParentObject, ActivateBasedOnFlipDirection commonParentActivateOnFlip, + Transform skeletonUtilityRoot, float rotationLimit) { + + GameObject mirroredChain = GameObject.Instantiate(normalChainParentObject, normalChainParentObject.transform.position, + normalChainParentObject.transform.rotation, commonParentActivateOnFlip.transform); + mirroredChain.name = normalChainParentObject.name + " FlippedX"; + + commonParentActivateOnFlip.activeOnFlippedX = mirroredChain; + + var followerKinematicObject = mirroredChain.GetComponentInChildren(); + followerKinematicObject.followFlippedX = true; + FlipBone2DHorizontal(followerKinematicObject.transform, skeletonUtilityRoot); + + var childBoneJoints = mirroredChain.GetComponentsInChildren(); + Transform prevRotatedChild = null; + Transform parentTransformForAngles = followerKinematicObject.transform; + for (int i = 0; i < childBoneJoints.Length; ++i) { + var joint = childBoneJoints[i]; + FlipBone2DHorizontal(joint.transform, skeletonUtilityRoot); + ApplyJoint2DAngleLimits(joint, rotationLimit, parentTransformForAngles, joint.transform); + + GameObject rotatedChild = GameObject.Instantiate(joint.gameObject, joint.transform, true); + rotatedChild.name = joint.name + " rotated"; + var rotationEulerAngles = rotatedChild.transform.localEulerAngles; + rotationEulerAngles.x = 180; + rotatedChild.transform.localEulerAngles = rotationEulerAngles; + DestroyImmediate(rotatedChild.GetComponent()); + DestroyImmediate(rotatedChild.GetComponent()); + DestroyImmediate(rotatedChild.GetComponent()); + + DestroyImmediate(joint.gameObject.GetComponent()); + + if (i > 0) { + var utilityBone = rotatedChild.GetComponent(); + utilityBone.parentReference = prevRotatedChild; + } + prevRotatedChild = rotatedChild.transform; + parentTransformForAngles = joint.transform; + } + + mirroredChain.SetActive(false); + } + + void FlipBone2DHorizontal(Transform bone, Transform mirrorPosition) { + Vector3 position = bone.position; + position.x = 2 * mirrorPosition.position.x - position.x; // = mirrorPosition + (mirrorPosition - bone.position) + bone.position = position; + + Vector3 boneZ = bone.forward; + Vector3 boneX = bone.right; + boneX.x *= -1; + + bone.rotation = Quaternion.LookRotation(boneZ, Vector3.Cross(boneZ, boneX)); + } + + void CreateHingeChain () { + var kinematicParentUtilityBone = utilityBone.transform.parent.GetComponent(); + if (kinematicParentUtilityBone == null) { + UnityEditor.EditorUtility.DisplayDialog("No parent SkeletonUtilityBone found!", "Please select the first physically moving chain node, having a parent GameObject with a SkeletonUtilityBone component attached.", "OK"); + return; + } + + SetSkeletonUtilityToFlipByRotation(); + + kinematicParentUtilityBone.mode = SkeletonUtilityBone.Mode.Follow; + kinematicParentUtilityBone.position = kinematicParentUtilityBone.rotation = kinematicParentUtilityBone.scale = kinematicParentUtilityBone.zPosition = true; + + // HingeChain Parent + // Needs to be on top hierarchy level (not attached to the moving skeleton at least) for physics to apply proper momentum. + GameObject chainParentObject = new GameObject(skeletonUtility.name + " HingeChain Parent " + utilityBone.name); + var followRotationComponent = chainParentObject.AddComponent(); + followRotationComponent.reference = skeletonUtility.boneRoot; + + // Follower Kinematic Rigidbody + GameObject followerKinematicObject = new GameObject(kinematicParentUtilityBone.name + " Follower"); + followerKinematicObject.transform.parent = chainParentObject.transform; + var followerRigidbody = followerKinematicObject.AddComponent(); + followerRigidbody.mass = 10; + followerRigidbody.isKinematic = true; + followerKinematicObject.AddComponent().reference = kinematicParentUtilityBone.transform; + followerKinematicObject.transform.position = kinematicParentUtilityBone.transform.position; + followerKinematicObject.transform.rotation = kinematicParentUtilityBone.transform.rotation; + + // Child Bones + var utilityBones = utilityBone.GetComponentsInChildren(); + var childBoneParentReference = followerKinematicObject.transform; + foreach (var childBone in utilityBones) { + childBone.parentReference = childBoneParentReference; + childBone.transform.SetParent(chainParentObject.transform, true); // we need a flat hierarchy of all Joint objects in Unity. + AttachRigidbodyAndCollider(childBone); + childBone.mode = SkeletonUtilityBone.Mode.Override; + + HingeJoint joint = childBone.gameObject.AddComponent(); + joint.axis = Vector3.forward; + joint.connectedBody = childBoneParentReference.GetComponent(); + joint.useLimits = true; + joint.limits = new JointLimits { + min = -20, + max = 20 + }; + childBone.GetComponent().mass = childBoneParentReference.transform.GetComponent().mass * 0.75f; + + childBoneParentReference = childBone.transform; + } + UnityEditor.Selection.activeGameObject = chainParentObject; + } + + void SetSkeletonUtilityToFlipByRotation () { + if (!skeletonUtility.flipBy180DegreeRotation) { + skeletonUtility.flipBy180DegreeRotation = true; + Debug.Log("Set SkeletonUtility " + skeletonUtility.name + " to flip by rotation instead of negative scale (required).", skeletonUtility); + } + } + + static void AttachRigidbodyAndCollider (SkeletonUtilityBone utilBone, bool enableCollider = false) { + if (utilBone.GetComponent() == null) { + if (utilBone.bone.Data.Length == 0) { + SphereCollider sphere = utilBone.gameObject.AddComponent(); + sphere.radius = 0.1f; + sphere.enabled = enableCollider; + } else { + float length = utilBone.bone.Data.Length; + BoxCollider box = utilBone.gameObject.AddComponent(); + box.size = new Vector3(length, length / 3f, 0.2f); + box.center = new Vector3(length / 2f, 0, 0); + box.enabled = enableCollider; + } + } + utilBone.gameObject.AddComponent(); + } + + static void AttachRigidbodyAndCollider2D(SkeletonUtilityBone utilBone, bool enableCollider = false) { + if (utilBone.GetComponent() == null) { + if (utilBone.bone.Data.Length == 0) { + var sphere = utilBone.gameObject.AddComponent(); + sphere.radius = 0.1f; + sphere.enabled = enableCollider; + } + else { + float length = utilBone.bone.Data.Length; + var box = utilBone.gameObject.AddComponent(); + box.size = new Vector3(length, length / 3f, 0.2f); + box.offset = new Vector3(length / 2f, 0, 0); + box.enabled = enableCollider; + } + } + utilBone.gameObject.AddComponent(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs.meta new file mode 100644 index 0000000..81de4d6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityBoneInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b3ae20b4bcc31f645afd6f5b64f82473 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs new file mode 100644 index 0000000..d20f00f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs @@ -0,0 +1,192 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using UnityEditor; +using UnityEditor.AnimatedValues; +using System.Collections.Generic; +using Spine; +using System.Reflection; + +namespace Spine.Unity.Editor { + using Icons = SpineEditorUtilities.Icons; + + [CustomEditor(typeof(SkeletonUtility))] + public class SkeletonUtilityInspector : UnityEditor.Editor { + + SkeletonUtility skeletonUtility; + Skeleton skeleton; + SkeletonRenderer skeletonRenderer; + SkeletonGraphic skeletonGraphic; + +#if !NEW_PREFAB_SYSTEM + bool isPrefab; + #endif + + readonly GUIContent SpawnHierarchyButtonLabel = new GUIContent("Spawn Hierarchy", Icons.skeleton); + + void OnEnable () { + skeletonUtility = (SkeletonUtility)target; + skeletonRenderer = skeletonUtility.skeletonRenderer; + skeletonGraphic = skeletonUtility.skeletonGraphic; + skeleton = skeletonUtility.Skeleton; + + if (skeleton == null) { + if (skeletonRenderer != null) { + skeletonRenderer.Initialize(false); + skeletonRenderer.LateUpdate(); + } + else if (skeletonGraphic != null) { + skeletonGraphic.Initialize(false); + skeletonGraphic.LateUpdate(); + } + skeleton = skeletonUtility.Skeleton; + } + + if ((skeletonRenderer != null && !skeletonRenderer.valid) || + (skeletonGraphic != null && !skeletonGraphic.IsValid)) return; + + #if !NEW_PREFAB_SYSTEM + isPrefab |= PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab; + #endif + } + + public override void OnInspectorGUI () { + + #if !NEW_PREFAB_SYSTEM + if (isPrefab) { + GUILayout.Label(new GUIContent("Cannot edit Prefabs", Icons.warning)); + return; + } + #endif + + serializedObject.Update(); + + if ((skeletonRenderer != null && !skeletonRenderer.valid) || + (skeletonGraphic != null && !skeletonGraphic.IsValid)) { + GUILayout.Label(new GUIContent("Spine Component invalid. Check Skeleton Data Asset.", Icons.warning)); + return; + } + + EditorGUILayout.PropertyField(serializedObject.FindProperty("boneRoot"), SpineInspectorUtility.TempContent("Skeleton Root")); + EditorGUILayout.PropertyField(serializedObject.FindProperty("flipBy180DegreeRotation"), SpineInspectorUtility.TempContent("Flip by Rotation", null, + "If true, Skeleton.ScaleX and Skeleton.ScaleY are followed " + + "by 180 degree rotation. If false, negative Transform scale is used. " + + "Note that using negative scale is consistent with previous behaviour (hence the default), " + + "however causes serious problems with rigidbodies and physics. Therefore, it is recommended to " + + "enable this parameter where possible. When creating hinge chains for a chain of skeleton bones " + + "via SkeletonUtilityBone, it is mandatory to have this parameter enabled.")); + + bool hasRootBone = skeletonUtility.boneRoot != null; + + if (!hasRootBone) + EditorGUILayout.HelpBox("No hierarchy found. Use Spawn Hierarchy to generate GameObjects for bones.", MessageType.Info); + + using (new EditorGUI.DisabledGroupScope(hasRootBone)) { + if (SpineInspectorUtility.LargeCenteredButton(SpawnHierarchyButtonLabel)) + SpawnHierarchyContextMenu(); + } + + if (hasRootBone) { + if (SpineInspectorUtility.CenteredButton(new GUIContent("Remove Hierarchy"))) { + Undo.RegisterCompleteObjectUndo(skeletonUtility, "Remove Hierarchy"); + Undo.DestroyObjectImmediate(skeletonUtility.boneRoot.gameObject); + skeletonUtility.boneRoot = null; + } + } + + serializedObject.ApplyModifiedProperties(); + } + + void SpawnHierarchyContextMenu () { + var menu = new GenericMenu(); + + menu.AddItem(new GUIContent("Follow all bones"), false, SpawnFollowHierarchy); + menu.AddItem(new GUIContent("Follow (Root Only)"), false, SpawnFollowHierarchyRootOnly); + menu.AddSeparator(""); + menu.AddItem(new GUIContent("Override all bones"), false, SpawnOverrideHierarchy); + menu.AddItem(new GUIContent("Override (Root Only)"), false, SpawnOverrideHierarchyRootOnly); + + menu.ShowAsContext(); + } + + public static void AttachIcon (SkeletonUtilityBone boneComponent) { + Skeleton skeleton = boneComponent.hierarchy.Skeleton; + Texture2D icon = boneComponent.bone.Data.Length == 0 ? Icons.nullBone : Icons.boneNib; + + foreach (IkConstraint c in skeleton.IkConstraints) + if (c.Target == boneComponent.bone) { + icon = Icons.constraintNib; + break; + } + + typeof(EditorGUIUtility).InvokeMember("SetIconForObject", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new object[2] { + boneComponent.gameObject, + icon + }); + } + + static void AttachIconsToChildren (Transform root) { + if (root != null) { + var utilityBones = root.GetComponentsInChildren(); + foreach (var utilBone in utilityBones) + AttachIcon(utilBone); + } + } + + void SpawnFollowHierarchy () { + Undo.RegisterCompleteObjectUndo(skeletonUtility, "Spawn Hierarchy"); + Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Follow, true, true, true); + AttachIconsToChildren(skeletonUtility.boneRoot); + } + + void SpawnFollowHierarchyRootOnly () { + Undo.RegisterCompleteObjectUndo(skeletonUtility, "Spawn Root"); + Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Follow, true, true, true); + AttachIconsToChildren(skeletonUtility.boneRoot); + } + + void SpawnOverrideHierarchy () { + Undo.RegisterCompleteObjectUndo(skeletonUtility, "Spawn Hierarchy"); + Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Override, true, true, true); + AttachIconsToChildren(skeletonUtility.boneRoot); + } + + void SpawnOverrideHierarchyRootOnly () { + Undo.RegisterCompleteObjectUndo(skeletonUtility, "Spawn Root"); + Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Override, true, true, true); + AttachIconsToChildren(skeletonUtility.boneRoot); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs.meta new file mode 100644 index 0000000..44e13b1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Components/SkeletonUtilityInspector.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a5b90df955eb8c2429ac67c8b2de6c5c +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI.meta new file mode 100644 index 0000000..d730a55 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: bfaea6b7e7f52bc46b8d1c3cb5e9eaa1 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png new file mode 100644 index 0000000..4792130 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png.meta new file mode 100644 index 0000000..ef7eb69 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/AtlasAsset Icon.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 3fc714a0dc1cf6b4b959e073fff2844e +timeCreated: 1508165143 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png new file mode 100644 index 0000000..61c0f18 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png.meta new file mode 100644 index 0000000..22239ca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/SkeletonDataAsset Icon.png.meta @@ -0,0 +1,46 @@ +fileFormatVersion: 2 +guid: 68defdbc95b30a74a9ad396bfc9a2277 +TextureImporter: + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png new file mode 100644 index 0000000..f44d38e Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png.meta new file mode 100644 index 0000000..dcf6806 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animation.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 52b12ec801461494185a4d3dc66f3d1d +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png new file mode 100644 index 0000000..6107546 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png.meta new file mode 100644 index 0000000..1bbca1c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-animationRoot.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 3d1be4ea889f3a14b864352fe49a1bde +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png new file mode 100644 index 0000000..4e14f98 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png.meta new file mode 100644 index 0000000..1316c3d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-attachment.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 04ae56b3698d3e844844cfcef2f009e7 +timeCreated: 1494928093 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png new file mode 100644 index 0000000..ec66a6a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png.meta new file mode 100644 index 0000000..f0cbaea --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-bone.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 8322793223a533a4ca8be6f430256dfc +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png new file mode 100644 index 0000000..87373b8 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png.meta new file mode 100644 index 0000000..a0b91be --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boneNib.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 97a43f11e00735147a9dc3dff6d68191 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png new file mode 100644 index 0000000..82beedf Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png.meta new file mode 100644 index 0000000..0e5d628 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-boundingBox.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 955aed20030d0504b8a9c6934a5cb47a +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png new file mode 100644 index 0000000..398137c Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png.meta new file mode 100644 index 0000000..9cb5d0c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-clipping.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: f5fff1b5caee03642ab77c9984b4bb6a +timeCreated: 1497479335 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png new file mode 100644 index 0000000..1c93d75 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png.meta new file mode 100644 index 0000000..1e11b1d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintIK.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 02822eb69e09dd947b434ab81e3d938f +timeCreated: 1494878353 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png new file mode 100644 index 0000000..175bcb0 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png.meta new file mode 100644 index 0000000..a692728 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintNib.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: de1a4f5ad4bdf1a4ea072c4d59ba87d8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png new file mode 100644 index 0000000..9663b85 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png.meta new file mode 100644 index 0000000..4459669 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintPath.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: c1aae98dd56b14c4b8c25360000b7e9e +timeCreated: 1494878353 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png new file mode 100644 index 0000000..2264aaa Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png.meta new file mode 100644 index 0000000..181bb92 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraintTransform.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 4709175437c21f64bab9b061f98a49fc +timeCreated: 1494878353 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png new file mode 100644 index 0000000..9c61ee5 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png.meta new file mode 100644 index 0000000..306364d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-constraints.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: ed0736a1eb519ef42b4892d1db2426b3 +timeCreated: 1494878353 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png new file mode 100644 index 0000000..4547f25 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png.meta new file mode 100644 index 0000000..0bf19db --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-event.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: d226a80acc775714aa78b85e16a00e9b +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png new file mode 100644 index 0000000..a27af1c Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png.meta new file mode 100644 index 0000000..e61da1e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-hingeChain.png.meta @@ -0,0 +1,47 @@ +fileFormatVersion: 2 +guid: 2c2c6d283dcf3654baf40001c982891c +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png new file mode 100644 index 0000000..663d113 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png.meta new file mode 100644 index 0000000..421c654 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-image.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 2b3a6f35bbaa8414eb51a344743ee641 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png new file mode 100644 index 0000000..1035553 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png.meta new file mode 100644 index 0000000..2b49d8b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-mesh.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: a309a2e14638a204091b915126910f45 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png new file mode 100644 index 0000000..9a6d738 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png.meta new file mode 100644 index 0000000..29da564 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-null.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: d1de1604dfe4cb64c9d31246a8e43c78 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png new file mode 100644 index 0000000..604ae0d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png.meta new file mode 100644 index 0000000..8aebfb7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-path.png.meta @@ -0,0 +1,59 @@ +fileFormatVersion: 2 +guid: dbc817a6c9e9c5747b7f6261bf5d1d09 +timeCreated: 1482240904 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 7 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + allowsAlphaSplitting: 0 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png new file mode 100644 index 0000000..0e5099f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png.meta new file mode 100644 index 0000000..9df5c2a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-point.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: d7a76922e4dd9fa429da15c018ff127f +timeCreated: 1524196821 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png new file mode 100644 index 0000000..102700a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png.meta new file mode 100644 index 0000000..800466b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-poseBones.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: da6f6d414e43aac46a57cc5a87208db4 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png new file mode 100644 index 0000000..b5d5adf Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png.meta new file mode 100644 index 0000000..9c2a1a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeleton.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: f2216037084d99d4481810cb521ed96f +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png new file mode 100644 index 0000000..ce4d937 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png.meta new file mode 100644 index 0000000..3a77fd7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skeletonUtility.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 5bb0631368b462047869d8788673cb48 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png new file mode 100644 index 0000000..4dc8e7f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png.meta new file mode 100644 index 0000000..f02b09c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skin.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: bfd9f3d2607e9e44c97384d7575a17dc +timeCreated: 1494878353 +licenseType: Free +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 0 + linearTexture: 1 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 2 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Android + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: WebGL + maxTextureSize: 1024 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png new file mode 100644 index 0000000..17bfef0 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png.meta new file mode 100644 index 0000000..92955a9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinPlaceholder.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 04c82a4acf7b5244e947f2709ec3a6cf +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png new file mode 100644 index 0000000..31857cf Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png.meta new file mode 100644 index 0000000..b8ce214 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-skinsRoot.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 8bd14c7643597a74ba2edc10a5e4c4ed +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png new file mode 100644 index 0000000..ca93872 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png.meta new file mode 100644 index 0000000..66d52b0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slot.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 0338faf3e7d93e2478fcbc022d13e081 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png new file mode 100644 index 0000000..dfca413 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png.meta new file mode 100644 index 0000000..3d9fdd7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-slotRoot.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 4a1646cf39026224c85ecba92d7d6948 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png new file mode 100644 index 0000000..7fd5473 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png.meta new file mode 100644 index 0000000..811e17a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-spine.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 4e7c964fa5e07024c8bf1debecc3b7c8 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png new file mode 100644 index 0000000..ec7c9e6 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png.meta new file mode 100644 index 0000000..fa37928 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-subMeshRenderer.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: f31c0c0d608e8ba4f9a1afb032092287 +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png new file mode 100644 index 0000000..05e3f4c Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png.meta new file mode 100644 index 0000000..87c616f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-warning.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 754d724c1bd750048852e8cf3d4a05ee +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png new file mode 100644 index 0000000..fa8f190 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png.meta new file mode 100644 index 0000000..e25807b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/GUI/icon-weights.png.meta @@ -0,0 +1,53 @@ +fileFormatVersion: 2 +guid: 0b1bcb09fa228d049ba3c9ea6a57e1ee +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + linearTexture: 1 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -3 + maxTextureSize: 1024 + textureSettings: + filterMode: -1 + aniso: 1 + mipBias: -1 + wrapMode: 1 + nPOTScale: 0 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 1 + textureType: 2 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets.meta new file mode 100644 index 0000000..39eef80 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a018d561e5df35848bcabbe2809c7549 +folderAsset: yes +timeCreated: 1580402759 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png new file mode 100644 index 0000000..b40be5a Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png.meta new file mode 100644 index 0000000..8153700 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMAPresetTemplate.png.meta @@ -0,0 +1,82 @@ +fileFormatVersion: 2 +guid: 77f055f38c1115f42a2df16b0428c4e6 +timeCreated: 1580402818 +licenseType: Pro +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset new file mode 100644 index 0000000..adc152d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset @@ -0,0 +1,454 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!181963792 &2655988077585873504 +Preset: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: PMATexturePreset + m_TargetType: + m_NativeTypeID: 1006 + m_ManagedTypePPtr: {fileID: 0} + m_ManagedTypeFallback: + m_Properties: + - target: {fileID: 0} + propertyPath: m_ExternalObjects.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapMode + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_EnableMipMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_sRGBTexture + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_LinearTexture + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_FadeOut + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_BorderMipMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapsPreserveCoverage + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaTestReferenceValue + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapFadeDistanceStart + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapFadeDistanceEnd + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_ConvertToNormalMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_ExternalNormalMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_HeightScale + value: 0.25 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_NormalMapFilter + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_IsReadable + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_StreamingMipmaps + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_StreamingMipmapsPriority + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_GrayScaleToAlpha + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_GenerateCubemap + value: 6 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CubemapConvolution + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SeamlessCubemap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureFormat + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_FilterMode + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_Aniso + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_MipBias + value: -100 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapU + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapV + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapW + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_NPOTScale + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_Lightmap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteMode + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteExtrude + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteMeshType + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_Alignment + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePivot.x + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePivot.y + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePixelsToUnits + value: 100 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.w + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteGenerateFallbackPhysicsShape + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaUsage + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaIsTransparency + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteTessellationDetail + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureType + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureShape + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SingleChannelComponent + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MaxTextureSizeSet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CompressionQualitySet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureFormatSet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.size + value: 4 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_BuildTarget + value: DefaultTexturePlatform + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_BuildTarget + value: Standalone + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_BuildTarget + value: iPhone + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[2].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_BuildTarget + value: Android + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[3].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Sprites.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Outline.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_PhysicsShape.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Bones.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_SpriteID + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Vertices.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Indices.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Edges.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Weights.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePackingTag + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PSDRemoveMatte + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PSDShowRemoveMatteOption + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_UserData + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AssetBundleName + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AssetBundleVariant + value: + objectReference: {fileID: 0} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset.meta new file mode 100644 index 0000000..8c4a8e8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/PMATexturePreset.preset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 665f49f3e2dc7b645b6577f14455f445 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset new file mode 100644 index 0000000..60212d4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset @@ -0,0 +1,390 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!181963792 &2655988077585873504 +Preset: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: StraightAlphaPreset + m_TargetType: + m_NativeTypeID: 1006 + m_ManagedTypePPtr: {fileID: 0} + m_ManagedTypeFallback: + m_Properties: + - target: {fileID: 0} + propertyPath: m_ExternalObjects.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapMode + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_EnableMipMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_sRGBTexture + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_LinearTexture + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_FadeOut + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_BorderMipMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapsPreserveCoverage + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaTestReferenceValue + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapFadeDistanceStart + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MipMapFadeDistanceEnd + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_ConvertToNormalMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_ExternalNormalMap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_HeightScale + value: 0.25 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_NormalMapFilter + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_IsReadable + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_StreamingMipmaps + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_StreamingMipmapsPriority + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_GrayScaleToAlpha + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_GenerateCubemap + value: 6 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CubemapConvolution + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SeamlessCubemap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureFormat + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_FilterMode + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_Aniso + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_MipBias + value: -100 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapU + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapV + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureSettings.m_WrapW + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_NPOTScale + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_Lightmap + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteMode + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteExtrude + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteMeshType + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_Alignment + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePivot.x + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePivot.y + value: 0.5 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePixelsToUnits + value: 100 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteBorder.w + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteGenerateFallbackPhysicsShape + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaUsage + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AlphaIsTransparency + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteTessellationDetail + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureType + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureShape + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SingleChannelComponent + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_MaxTextureSizeSet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_CompressionQualitySet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_TextureFormatSet + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.size + value: 2 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_BuildTarget + value: DefaultTexturePlatform + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[0].m_ForceMaximumCompressionQuality_BC6H_BC7 + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_BuildTarget + value: Standalone + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_MaxTextureSize + value: 2048 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_ResizeAlgorithm + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_TextureFormat + value: -1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_TextureCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_CompressionQuality + value: 50 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_CrunchedCompression + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_AllowsAlphaSplitting + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_Overridden + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_AndroidETC2FallbackOverride + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PlatformSettings.Array.data[1].m_ForceMaximumCompressionQuality_BC6H_BC7 + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Sprites.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Outline.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_PhysicsShape.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Bones.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_SpriteID + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_InternalID + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Vertices.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Indices.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Edges.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_Weights.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpriteSheet.m_SecondaryTextures.Array.size + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_SpritePackingTag + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PSDRemoveMatte + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_PSDShowRemoveMatteOption + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_UserData + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AssetBundleName + value: + objectReference: {fileID: 0} + - target: {fileID: 0} + propertyPath: m_AssetBundleVariant + value: + objectReference: {fileID: 0} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset.meta new file mode 100644 index 0000000..b64d04e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPreset.preset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b3fe5ce49a7c8c041a9d60e4f7f403de +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png new file mode 100644 index 0000000..4db601f Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png differ diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png.meta new file mode 100644 index 0000000..721d7ca --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/ImporterPresets/StraightAlphaPresetTemplate.png.meta @@ -0,0 +1,82 @@ +fileFormatVersion: 2 +guid: ade885c25e49d7740b5c00d4e10a6197 +timeCreated: 1580402818 +licenseType: Pro +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 4 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + - buildTarget: Standalone + maxTextureSize: 2048 + textureFormat: -1 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs new file mode 100644 index 0000000..605a2e3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs @@ -0,0 +1,47 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Spine.Unity.Editor { + public static class Menus { + [MenuItem("GameObject/Spine/SkeletonRenderer", false, 10)] + static public void CreateSkeletonRendererGameObject () { + EditorInstantiation.InstantiateEmptySpineGameObject("New SkeletonRenderer", true); + } + + [MenuItem("GameObject/Spine/SkeletonAnimation", false, 10)] + static public void CreateSkeletonAnimationGameObject () { + EditorInstantiation.InstantiateEmptySpineGameObject("New SkeletonAnimation", true); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs.meta new file mode 100644 index 0000000..d33433f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Menus.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: cf21125cbd8928844a85a3ad9002693b +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources.meta new file mode 100644 index 0000000..8d1a705 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 24903fdac57ee784b9597fcb751ec22f +folderAsset: yes +timeCreated: 1444565388 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt new file mode 100644 index 0000000..1a3c1a3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt @@ -0,0 +1 @@ +DO NOT MOVE OR DELETE THIS FILE \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt.meta new file mode 100644 index 0000000..7569884 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Resources/SpineAssetDatabaseMarker.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 57281c00bdd90ad4392f811f2b9f0da1 +timeCreated: 1444565392 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders.meta new file mode 100644 index 0000000..007cc76 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 10e0b626d7ae7394a934ee9f2fb81b5a +folderAsset: yes +timeCreated: 1527569604 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs new file mode 100644 index 0000000..4b0d582 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs @@ -0,0 +1,226 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using Spine.Unity; + +using SpineInspectorUtility = Spine.Unity.Editor.SpineInspectorUtility; + +public class SpineShaderWithOutlineGUI : ShaderGUI { + + protected MaterialEditor _materialEditor; + bool _showAdvancedOutlineSettings = false; + bool _showStencilSettings = false; + + MaterialProperty _OutlineWidth = null; + MaterialProperty _OutlineColor = null; + MaterialProperty _OutlineReferenceTexWidth = null; + MaterialProperty _ThresholdEnd = null; + MaterialProperty _OutlineSmoothness = null; + MaterialProperty _Use8Neighbourhood = null; + MaterialProperty _OutlineMipLevel = null; + MaterialProperty _StencilComp = null; + MaterialProperty _StencilRef = null; + + static GUIContent _EnableOutlineText = new GUIContent("Outline", "Enable outline rendering. Draws an outline by sampling 4 or 8 neighbourhood pixels at a given distance specified via 'Outline Width'."); + static GUIContent _OutlineWidthText = new GUIContent("Outline Width", ""); + static GUIContent _OutlineColorText = new GUIContent("Outline Color", ""); + static GUIContent _OutlineReferenceTexWidthText = new GUIContent("Reference Texture Width", ""); + static GUIContent _ThresholdEndText = new GUIContent("Outline Threshold", ""); + static GUIContent _OutlineSmoothnessText = new GUIContent("Outline Smoothness", ""); + static GUIContent _Use8NeighbourhoodText = new GUIContent("Sample 8 Neighbours", ""); + static GUIContent _OutlineMipLevelText = new GUIContent("Outline Mip Level", ""); + static GUIContent _StencilCompText = new GUIContent("Stencil Comparison", ""); + static GUIContent _StencilRefText = new GUIContent("Stencil Reference", ""); + + static GUIContent _OutlineAdvancedText = new GUIContent("Advanced", ""); + static GUIContent _ShowStencilText = new GUIContent("Stencil", "Stencil parameters for mask interaction."); + + protected const string ShaderOutlineNamePrefix = "Spine/Outline/"; + protected const string ShaderNormalNamePrefix = "Spine/"; + protected const string ShaderWithoutStandardVariantSuffix = "OutlineOnly"; + + #region ShaderGUI + + public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] properties) { + FindProperties(properties); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly + _materialEditor = materialEditor; + + base.OnGUI(materialEditor, properties); + EditorGUILayout.Space(); + RenderStencilProperties(); + EditorGUILayout.Space(); + RenderOutlineProperties(); + } + + #endregion + + #region Virtual Interface + + protected virtual void FindProperties (MaterialProperty[] props) { + + _OutlineWidth = FindProperty("_OutlineWidth", props, false); + _OutlineReferenceTexWidth = FindProperty("_OutlineReferenceTexWidth", props, false); + _OutlineColor = FindProperty("_OutlineColor", props, false); + _ThresholdEnd = FindProperty("_ThresholdEnd", props, false); + _OutlineSmoothness = FindProperty("_OutlineSmoothness", props, false); + _Use8Neighbourhood = FindProperty("_Use8Neighbourhood", props, false); + _OutlineMipLevel = FindProperty("_OutlineMipLevel", props, false); + + _StencilComp = FindProperty("_StencilComp", props, false); + _StencilRef = FindProperty("_StencilRef", props, false); + if (_StencilRef == null) + _StencilRef = FindProperty("_Stencil", props, false); + } + + protected virtual void RenderStencilProperties () { + if (_StencilComp == null) + return; // not a shader supporting custom stencil operations + + // Use default labelWidth + EditorGUIUtility.labelWidth = 0f; + _showStencilSettings = EditorGUILayout.Foldout(_showStencilSettings, _ShowStencilText); + if (_showStencilSettings) { + using (new SpineInspectorUtility.IndentScope()) { + _materialEditor.ShaderProperty(_StencilComp, _StencilCompText); + _materialEditor.ShaderProperty(_StencilRef, _StencilRefText); + } + } + } + + protected virtual void RenderOutlineProperties () { + + if (_OutlineWidth == null) + return; // not an outline shader + + // Use default labelWidth + EditorGUIUtility.labelWidth = 0f; + + bool mixedValue; + bool hasOutlineVariant = !IsShaderWithoutStandardVariantShader(_materialEditor, out mixedValue); + bool isOutlineEnabled = true; + if (hasOutlineVariant) { + isOutlineEnabled = IsOutlineEnabled(_materialEditor, out mixedValue); + EditorGUI.showMixedValue = mixedValue; + EditorGUI.BeginChangeCheck(); + + var origFontStyle = EditorStyles.label.fontStyle; + EditorStyles.label.fontStyle = FontStyle.Bold; + isOutlineEnabled = EditorGUILayout.Toggle(_EnableOutlineText, isOutlineEnabled); + EditorStyles.label.fontStyle = origFontStyle; + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) { + foreach (Material material in _materialEditor.targets) { + SwitchShaderToOutlineSettings(material, isOutlineEnabled); + } + } + } + else { + var origFontStyle = EditorStyles.label.fontStyle; + EditorStyles.label.fontStyle = FontStyle.Bold; + EditorGUILayout.LabelField(_EnableOutlineText); + EditorStyles.label.fontStyle = origFontStyle; + } + + if (isOutlineEnabled) { + _materialEditor.ShaderProperty(_OutlineWidth, _OutlineWidthText); + _materialEditor.ShaderProperty(_OutlineColor, _OutlineColorText); + + _showAdvancedOutlineSettings = EditorGUILayout.Foldout(_showAdvancedOutlineSettings, _OutlineAdvancedText); + if (_showAdvancedOutlineSettings) { + using (new SpineInspectorUtility.IndentScope()) { + _materialEditor.ShaderProperty(_OutlineReferenceTexWidth, _OutlineReferenceTexWidthText); + _materialEditor.ShaderProperty(_ThresholdEnd, _ThresholdEndText); + _materialEditor.ShaderProperty(_OutlineSmoothness, _OutlineSmoothnessText); + _materialEditor.ShaderProperty(_Use8Neighbourhood, _Use8NeighbourhoodText); + _materialEditor.ShaderProperty(_OutlineMipLevel, _OutlineMipLevelText); + } + } + } + } + + #endregion + + #region Private Functions + + void SwitchShaderToOutlineSettings (Material material, bool enableOutline) { + + var shaderName = material.shader.name; + bool isSetToOutlineShader = shaderName.Contains(ShaderOutlineNamePrefix); + if (isSetToOutlineShader && !enableOutline) { + shaderName = shaderName.Replace(ShaderOutlineNamePrefix, ShaderNormalNamePrefix); + _materialEditor.SetShader(Shader.Find(shaderName), false); + return; + } + else if (!isSetToOutlineShader && enableOutline) { + shaderName = shaderName.Replace(ShaderNormalNamePrefix, ShaderOutlineNamePrefix); + _materialEditor.SetShader(Shader.Find(shaderName), false); + return; + } + } + + static bool IsOutlineEnabled (MaterialEditor editor, out bool mixedValue) { + mixedValue = false; + bool isAnyEnabled = false; + foreach (Material material in editor.targets) { + if (material.shader.name.Contains(ShaderOutlineNamePrefix)) { + isAnyEnabled = true; + } + else if (isAnyEnabled) { + mixedValue = true; + } + } + return isAnyEnabled; + } + + static bool IsShaderWithoutStandardVariantShader (MaterialEditor editor, out bool mixedValue) { + mixedValue = false; + bool isAnyShaderWithoutVariant = false; + foreach (Material material in editor.targets) { + if (material.shader.name.Contains(ShaderWithoutStandardVariantSuffix)) { + isAnyShaderWithoutVariant = true; + } + else if (isAnyShaderWithoutVariant) { + mixedValue = true; + } + } + return isAnyShaderWithoutVariant; + } + + static bool BoldToggleField (GUIContent label, bool value) { + FontStyle origFontStyle = EditorStyles.label.fontStyle; + EditorStyles.label.fontStyle = FontStyle.Bold; + value = EditorGUILayout.Toggle(label, value, EditorStyles.toggle); + EditorStyles.label.fontStyle = origFontStyle; + return value; + } + + #endregion +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs.meta new file mode 100644 index 0000000..394bd69 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineShaderWithOutlineGUI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: efbbf90926e217c40831926fce374905 +timeCreated: 1573666328 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs new file mode 100644 index 0000000..53215cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs @@ -0,0 +1,1201 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using Spine.Unity; + +using SpineInspectorUtility = Spine.Unity.Editor.SpineInspectorUtility; + +public class SpineSpriteShaderGUI : SpineShaderWithOutlineGUI { + static readonly string kShaderVertexLit = "Spine/Sprite/Vertex Lit"; + static readonly string kShaderPixelLit = "Spine/Sprite/Pixel Lit"; + static readonly string kShaderUnlit = "Spine/Sprite/Unlit"; + + static readonly string kShaderVertexLitOutline = "Spine/Outline/Sprite/Vertex Lit"; + static readonly string kShaderPixelLitOutline = "Spine/Outline/Sprite/Pixel Lit"; + static readonly string kShaderUnlitOutline = "Spine/Outline/Sprite/Unlit"; + + static readonly string kShaderLitLW = "Lightweight Render Pipeline/Spine/Sprite"; + static readonly string kShaderLitURP = "Universal Render Pipeline/Spine/Sprite"; + static readonly string kShaderLitURP2D = "Universal Render Pipeline/2D/Spine/Sprite"; + static readonly int kSolidQueue = 2000; + static readonly int kAlphaTestQueue = 2450; + static readonly int kTransparentQueue = 3000; + + private enum eBlendMode { + PreMultipliedAlpha, + StandardAlpha, + Opaque, + Additive, + SoftAdditive, + Multiply, + Multiplyx2, + }; + + private enum eLightMode { + VertexLit, + PixelLit, + Unlit, + LitLightweight, + LitUniversal, + LitUniversal2D + }; + + private enum eCulling { + Off = 0, + Front = 1, + Back = 2, + }; + + private enum eNormalsMode { + MeshNormals = -1, + FixedNormalsViewSpace = 0, + FixedNormalsModelSpace = 1, + FixedNormalsWorldSpace = 2 + }; + + private enum eDiffuseRampMode { + NoRampSpecified = -1, + FullRangeHard = 0, + FullRangeSoft = 1, + OldHard = 2, + OldSoft = 3, + + DefaultRampMode = OldHard + }; + + MaterialProperty _mainTexture = null; + MaterialProperty _color = null; + MaterialProperty _maskTexture = null; + + MaterialProperty _pixelSnap = null; + + MaterialProperty _writeToDepth = null; + MaterialProperty _depthAlphaCutoff = null; + MaterialProperty _shadowAlphaCutoff = null; + MaterialProperty _renderQueue = null; + MaterialProperty _culling = null; + MaterialProperty _customRenderQueue = null; + + MaterialProperty _overlayColor = null; + MaterialProperty _hue = null; + MaterialProperty _saturation = null; + MaterialProperty _brightness = null; + + MaterialProperty _rimPower = null; + MaterialProperty _rimColor = null; + + MaterialProperty _bumpMap = null; + MaterialProperty _bumpScale = null; + MaterialProperty _diffuseRamp = null; + MaterialProperty _fixedNormal = null; + + MaterialProperty _blendTexture = null; + MaterialProperty _blendTextureLerp = null; + + MaterialProperty _emissionMap = null; + MaterialProperty _emissionColor = null; + MaterialProperty _emissionPower = null; + + MaterialProperty _metallic = null; + MaterialProperty _metallicGlossMap = null; + MaterialProperty _smoothness = null; + MaterialProperty _smoothnessScale = null; + + static GUIContent _albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); + static GUIContent _maskText = new GUIContent("Light Mask", "Light mask texture (secondary Sprite texture)"); + static GUIContent _altAlbedoText = new GUIContent("Secondary Albedo", "When a secondary albedo texture is set the albedo will be a blended mix of the two textures based on the blend value."); + static GUIContent _metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); + static GUIContent _smoothnessText = new GUIContent("Smoothness", "Smoothness value"); + static GUIContent _smoothnessScaleText = new GUIContent("Smoothness", "Smoothness scale factor"); + static GUIContent _normalMapText = new GUIContent("Normal Map", "Normal Map"); + static GUIContent _emissionText = new GUIContent("Emission", "Emission (RGB)"); + static GUIContent _emissionPowerText = new GUIContent("Emission Power"); + static GUIContent _emissionToggleText = new GUIContent("Emission", "Enable Emission."); + static GUIContent _diffuseRampText = new GUIContent("Diffuse Ramp", "A black and white gradient can be used to create a 'Toon Shading' effect."); + static GUIContent _depthText = new GUIContent("Write to Depth", "Write to Depth Buffer by clipping alpha."); + static GUIContent _depthAlphaCutoffText = new GUIContent("Depth Alpha Cutoff", "Threshold for depth write alpha cutoff"); + static GUIContent _shadowAlphaCutoffText = new GUIContent("Shadow Alpha Cutoff", "Threshold for shadow alpha cutoff"); + static GUIContent _receiveShadowsText = new GUIContent("Receive Shadows", "When enabled, other GameObjects can cast shadows onto this GameObject. 'Write to Depth' has to be enabled in Lightweight RP."); + static GUIContent _fixedNormalText = new GUIContent("Fixed Normals", "If this is ticked instead of requiring mesh normals a Fixed Normal will be used instead (it's quicker and can result in better looking lighting effects on 2d objects)."); + static GUIContent _fixedNormalDirectionText = new GUIContent("Fixed Normal Direction", "Should normally be (0,0,1) if in view-space or (0,0,-1) if in model-space."); + static GUIContent _adjustBackfaceTangentText = new GUIContent("Adjust Back-face Tangents", "Tick only if you are going to rotate the sprite to face away from the camera, the tangents will be flipped when this is the case to make lighting correct."); + static GUIContent _sphericalHarmonicsText = new GUIContent("Light Probes & Ambient", "Enable to use spherical harmonics to aplpy ambient light and/or light probes. In vertex-lit mode this will be approximated from scenes ambient trilight settings."); + static GUIContent _lightingModeText = new GUIContent("Lighting Mode", "Lighting Mode"); + static GUIContent[] _lightingModeOptions = { + new GUIContent("Vertex Lit"), + new GUIContent("Pixel Lit"), + new GUIContent("Unlit"), + new GUIContent("Lit Lightweight"), + new GUIContent("Lit Universal"), + new GUIContent("Lit Universal2D") + }; + static GUIContent _blendModeText = new GUIContent("Blend Mode", "Blend Mode"); + static GUIContent[] _blendModeOptions = { + new GUIContent("Pre-Multiplied Alpha"), + new GUIContent("Standard Alpha"), + new GUIContent("Opaque"), + new GUIContent("Additive"), + new GUIContent("Soft Additive"), + new GUIContent("Multiply"), + new GUIContent("Multiply x2") + }; + static GUIContent _rendererQueueText = new GUIContent("Render Queue Offset"); + static GUIContent _cullingModeText = new GUIContent("Culling Mode"); + static GUIContent[] _cullingModeOptions = { new GUIContent("Off"), new GUIContent("Front"), new GUIContent("Back") }; + static GUIContent _pixelSnapText = new GUIContent("Pixel Snap"); + //static GUIContent _customRenderTypetagsText = new GUIContent("Use Custom RenderType tags"); + static GUIContent _fixedNormalSpaceText = new GUIContent("Fixed Normal Space"); + static GUIContent[] _fixedNormalSpaceOptions = { new GUIContent("View-Space"), new GUIContent("Model-Space"), new GUIContent("World-Space") }; + static GUIContent _rimLightingToggleText = new GUIContent("Rim Lighting", "Enable Rim Lighting."); + static GUIContent _rimColorText = new GUIContent("Rim Color"); + static GUIContent _rimPowerText = new GUIContent("Rim Power"); + static GUIContent _specularToggleText = new GUIContent("Specular", "Enable Specular."); + static GUIContent _colorAdjustmentToggleText = new GUIContent("Color Adjustment", "Enable material color adjustment."); + static GUIContent _colorAdjustmentColorText = new GUIContent("Overlay Color"); + static GUIContent _colorAdjustmentHueText = new GUIContent("Hue"); + static GUIContent _colorAdjustmentSaturationText = new GUIContent("Saturation"); + static GUIContent _colorAdjustmentBrightnessText = new GUIContent("Brightness"); + static GUIContent _fogToggleText = new GUIContent("Fog", "Enable Fog rendering on this renderer."); + static GUIContent _meshRequiresTangentsText = new GUIContent("Note: Material requires a mesh with tangents."); + static GUIContent _meshRequiresNormalsText = new GUIContent("Note: Material requires a mesh with normals."); + static GUIContent _meshRequiresNormalsAndTangentsText = new GUIContent("Note: Material requires a mesh with Normals and Tangents."); + static GUIContent[] _fixedDiffuseRampModeOptions = { new GUIContent("Hard"), new GUIContent("Soft"), new GUIContent("Old Hard"), new GUIContent("Old Soft") }; + + const string _primaryMapsText = "Main Maps"; + const string _depthLabelText = "Depth"; + const string _shadowsText = "Shadows"; + const string _customRenderType = "Use Custom RenderType"; + + #region ShaderGUI + + public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] properties) { + FindProperties(properties); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly + _materialEditor = materialEditor; + ShaderPropertiesGUI(); + } + + public override void AssignNewShaderToMaterial (Material material, Shader oldShader, Shader newShader) { + base.AssignNewShaderToMaterial(material, oldShader, newShader); + + //If not originally a sprite shader set default keywords + if (oldShader.name != kShaderVertexLit && oldShader.name != kShaderPixelLit && oldShader.name != kShaderUnlit && + oldShader.name != kShaderVertexLitOutline && oldShader.name != kShaderPixelLitOutline && oldShader.name != kShaderUnlitOutline && + oldShader.name != kShaderLitLW && + oldShader.name != kShaderLitURP && + oldShader.name != kShaderLitURP2D) { + SetDefaultSpriteKeywords(material, newShader); + } + + SetMaterialKeywords(material); + } + + #endregion + + #region Virtual Interface + + protected override void FindProperties (MaterialProperty[] props) { + base.FindProperties(props); + + _mainTexture = FindProperty("_MainTex", props); + _maskTexture = FindProperty("_MaskTex", props, false); + _color = FindProperty("_Color", props); + + _pixelSnap = FindProperty("PixelSnap", props); + + _writeToDepth = FindProperty("_ZWrite", props, false); + _depthAlphaCutoff = FindProperty("_Cutoff", props); + _shadowAlphaCutoff = FindProperty("_ShadowAlphaCutoff", props); + _renderQueue = FindProperty("_RenderQueue", props); + _culling = FindProperty("_Cull", props); + _customRenderQueue = FindProperty("_CustomRenderQueue", props); + + _bumpMap = FindProperty("_BumpMap", props, false); + _bumpScale = FindProperty("_BumpScale", props, false); + _diffuseRamp = FindProperty("_DiffuseRamp", props, false); + _fixedNormal = FindProperty("_FixedNormal", props, false); + _blendTexture = FindProperty("_BlendTex", props, false); + _blendTextureLerp = FindProperty("_BlendAmount", props, false); + + _overlayColor = FindProperty("_OverlayColor", props, false); + _hue = FindProperty("_Hue", props, false); + _saturation = FindProperty("_Saturation", props, false); + _brightness = FindProperty("_Brightness", props, false); + + _rimPower = FindProperty("_RimPower", props, false); + _rimColor = FindProperty("_RimColor", props, false); + + _emissionMap = FindProperty("_EmissionMap", props, false); + _emissionColor = FindProperty("_EmissionColor", props, false); + _emissionPower = FindProperty("_EmissionPower", props, false); + + _metallic = FindProperty("_Metallic", props, false); + _metallicGlossMap = FindProperty("_MetallicGlossMap", props, false); + _smoothness = FindProperty("_Glossiness", props, false); + _smoothnessScale = FindProperty("_GlossMapScale", props, false); + } + + static bool BoldToggleField (GUIContent label, bool value) { + FontStyle origFontStyle = EditorStyles.label.fontStyle; + EditorStyles.label.fontStyle = FontStyle.Bold; + value = EditorGUILayout.Toggle(label, value, EditorStyles.toggle); + EditorStyles.label.fontStyle = origFontStyle; + return value; + } + + protected virtual void ShaderPropertiesGUI () { + // Use default labelWidth + EditorGUIUtility.labelWidth = 0f; + + RenderMeshInfoBox(); + + // Detect any changes to the material + bool dataChanged = RenderModes(); + + GUILayout.Label(_primaryMapsText, EditorStyles.boldLabel); + { + dataChanged |= RenderTextureProperties(); + } + + GUILayout.Label(_depthLabelText, EditorStyles.boldLabel); + { + dataChanged |= RenderDepthProperties(); + } + + GUILayout.Label(_shadowsText, EditorStyles.boldLabel); + { + dataChanged |= RenderShadowsProperties(); + } + + if (_metallic != null) { + dataChanged |= RenderSpecularProperties(); + } + + if (_emissionMap != null && _emissionColor != null) { + dataChanged |= RenderEmissionProperties(); + } + + if (_fixedNormal != null) { + dataChanged |= RenderNormalsProperties(); + } + + if (_fixedNormal != null) { + dataChanged |= RenderSphericalHarmonicsProperties(); + } + + { + dataChanged |= RenderFogProperties(); + } + + { + dataChanged |= RenderColorProperties(); + } + + if (_rimColor != null) { + dataChanged |= RenderRimLightingProperties(); + } + + { + EditorGUILayout.Space(); + RenderStencilProperties(); + } + + { + EditorGUILayout.Space(); + RenderOutlineProperties(); + } + + if (dataChanged) { + MaterialChanged(_materialEditor); + } + } + + protected virtual bool RenderModes () { + bool dataChanged = false; + + //Lighting Mode + { + EditorGUI.BeginChangeCheck(); + + eLightMode lightMode = GetMaterialLightMode((Material)_materialEditor.target); + EditorGUI.showMixedValue = false; + foreach (Material material in _materialEditor.targets) { + if (lightMode != GetMaterialLightMode(material)) { + EditorGUI.showMixedValue = true; + break; + } + } + + lightMode = (eLightMode)EditorGUILayout.Popup(_lightingModeText, (int)lightMode, _lightingModeOptions); + if (EditorGUI.EndChangeCheck()) { + foreach (Material material in _materialEditor.targets) { + switch (lightMode) { + case eLightMode.VertexLit: + if (material.shader.name != kShaderVertexLit) + _materialEditor.SetShader(Shader.Find(kShaderVertexLit), false); + break; + case eLightMode.PixelLit: + if (material.shader.name != kShaderPixelLit) + _materialEditor.SetShader(Shader.Find(kShaderPixelLit), false); + break; + case eLightMode.Unlit: + if (material.shader.name != kShaderUnlit) + _materialEditor.SetShader(Shader.Find(kShaderUnlit), false); + break; + case eLightMode.LitLightweight: + if (material.shader.name != kShaderLitLW) + _materialEditor.SetShader(Shader.Find(kShaderLitLW), false); + break; + case eLightMode.LitUniversal: + if (material.shader.name != kShaderLitURP) + _materialEditor.SetShader(Shader.Find(kShaderLitURP), false); + break; + case eLightMode.LitUniversal2D: + if (material.shader.name != kShaderLitURP2D) + _materialEditor.SetShader(Shader.Find(kShaderLitURP2D), false); + break; + } + } + + dataChanged = true; + } + } + + //Blend Mode + { + eBlendMode blendMode = GetMaterialBlendMode((Material)_materialEditor.target); + EditorGUI.showMixedValue = false; + foreach (Material material in _materialEditor.targets) { + if (blendMode != GetMaterialBlendMode(material)) { + EditorGUI.showMixedValue = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + blendMode = (eBlendMode)EditorGUILayout.Popup(_blendModeText, (int)blendMode, _blendModeOptions); + if (EditorGUI.EndChangeCheck()) { + foreach (Material mat in _materialEditor.targets) { + SetBlendMode(mat, blendMode); + } + + dataChanged = true; + } + + if (QualitySettings.activeColorSpace == ColorSpace.Linear && + !EditorGUI.showMixedValue && blendMode == eBlendMode.PreMultipliedAlpha) { + EditorGUILayout.HelpBox(MaterialChecks.kPMANotSupportedLinearMessage, MessageType.Error, true); + } + } + + EditorGUI.BeginDisabledGroup(true); + _materialEditor.RenderQueueField(); + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = _renderQueue.hasMixedValue; + int renderQueue = EditorGUILayout.IntField(_rendererQueueText, (int)_renderQueue.floatValue); + if (EditorGUI.EndChangeCheck()) { + SetInt("_RenderQueue", renderQueue); + dataChanged = true; + } + + EditorGUI.BeginChangeCheck(); + var culling = (eCulling)Mathf.RoundToInt(_culling.floatValue); + EditorGUI.showMixedValue = _culling.hasMixedValue; + culling = (eCulling)EditorGUILayout.Popup(_cullingModeText, (int)culling, _cullingModeOptions); + if (EditorGUI.EndChangeCheck()) { + SetInt("_Cull", (int)culling); + dataChanged = true; + } + + EditorGUI.showMixedValue = false; + + EditorGUI.BeginChangeCheck(); + _materialEditor.ShaderProperty(_pixelSnap, _pixelSnapText); + dataChanged |= EditorGUI.EndChangeCheck(); + + return dataChanged; + } + + protected virtual bool RenderTextureProperties () { + bool dataChanged = false; + + EditorGUI.BeginChangeCheck(); + + _materialEditor.TexturePropertySingleLine(_albedoText, _mainTexture, _color); + + if (_bumpMap != null) + _materialEditor.TexturePropertySingleLine(_normalMapText, _bumpMap, _bumpMap.textureValue != null ? _bumpScale : null); + + if (_maskTexture != null) + _materialEditor.TexturePropertySingleLine(_maskText, _maskTexture); + + dataChanged |= RenderDiffuseRampProperties(); + + dataChanged |= EditorGUI.EndChangeCheck(); + + if (_blendTexture != null) { + EditorGUI.BeginChangeCheck(); + _materialEditor.TexturePropertySingleLine(_altAlbedoText, _blendTexture, _blendTextureLerp); + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_TEXTURE_BLEND", _blendTexture != null); + dataChanged = true; + } + } + + EditorGUI.BeginChangeCheck(); + _materialEditor.TextureScaleOffsetProperty(_mainTexture); + dataChanged |= EditorGUI.EndChangeCheck(); + + EditorGUI.showMixedValue = false; + + return dataChanged; + } + + protected virtual bool RenderDepthProperties () { + bool dataChanged = false; + + EditorGUI.BeginChangeCheck(); + + bool showDepthAlphaCutoff = true; + // e.g. Pixel Lit shader always has ZWrite enabled + if (_writeToDepth != null) { + bool mixedValue = _writeToDepth.hasMixedValue; + EditorGUI.showMixedValue = mixedValue; + bool writeTodepth = EditorGUILayout.Toggle(_depthText, _writeToDepth.floatValue != 0.0f); + + if (EditorGUI.EndChangeCheck()) { + SetInt("_ZWrite", writeTodepth ? 1 : 0); + _depthAlphaCutoff.floatValue = writeTodepth ? 0.5f : 0.0f; + mixedValue = false; + dataChanged = true; + } + + showDepthAlphaCutoff = writeTodepth && !mixedValue && GetMaterialBlendMode((Material)_materialEditor.target) != eBlendMode.Opaque; + } + if (showDepthAlphaCutoff) { + EditorGUI.BeginChangeCheck(); + _materialEditor.RangeProperty(_depthAlphaCutoff, _depthAlphaCutoffText.text); + dataChanged |= EditorGUI.EndChangeCheck(); + } + + { + bool useCustomRenderType = _customRenderQueue.floatValue > 0.0f; + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = _customRenderQueue.hasMixedValue; + useCustomRenderType = EditorGUILayout.Toggle(_customRenderType, useCustomRenderType); + if (EditorGUI.EndChangeCheck()) { + dataChanged = true; + + _customRenderQueue.floatValue = useCustomRenderType ? 1.0f : 0.0f; + + foreach (Material material in _materialEditor.targets) { + eBlendMode blendMode = GetMaterialBlendMode(material); + + switch (blendMode) { + case eBlendMode.Opaque: + { + SetRenderType(material, "Opaque", useCustomRenderType); + } + break; + default: + { + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderType); + } + break; + } + } + } + } + + EditorGUI.showMixedValue = false; + + return dataChanged; + } + + protected virtual bool RenderNormalsProperties () { + bool dataChanged = false; + + eNormalsMode normalsMode = GetMaterialNormalsMode((Material)_materialEditor.target); + bool mixedNormalsMode = false; + foreach (Material material in _materialEditor.targets) { + if (normalsMode != GetMaterialNormalsMode(material)) { + mixedNormalsMode = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedNormalsMode; + bool fixedNormals = BoldToggleField(_fixedNormalText, normalsMode != eNormalsMode.MeshNormals); + + if (EditorGUI.EndChangeCheck()) { + normalsMode = fixedNormals ? eNormalsMode.FixedNormalsViewSpace : eNormalsMode.MeshNormals; + SetNormalsMode(_materialEditor, normalsMode, false); + _fixedNormal.vectorValue = new Vector4(0.0f, 0.0f, normalsMode == eNormalsMode.FixedNormalsViewSpace ? 1.0f : -1.0f, 1.0f); + mixedNormalsMode = false; + dataChanged = true; + } + + if (fixedNormals) { + //Show drop down for normals space + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedNormalsMode; + normalsMode = (eNormalsMode)EditorGUILayout.Popup(_fixedNormalSpaceText, (int)normalsMode, _fixedNormalSpaceOptions); + if (EditorGUI.EndChangeCheck()) { + SetNormalsMode((Material)_materialEditor.target, normalsMode, GetMaterialFixedNormalsBackfaceRenderingOn((Material)_materialEditor.target)); + + foreach (Material material in _materialEditor.targets) { + SetNormalsMode(material, normalsMode, GetMaterialFixedNormalsBackfaceRenderingOn(material)); + } + + //Reset fixed normal to default (Vector3.forward for model-space, -Vector3.forward for view-space). + _fixedNormal.vectorValue = new Vector4(0.0f, 0.0f, normalsMode == eNormalsMode.FixedNormalsViewSpace ? 1.0f : -1.0f, 1.0f); + + mixedNormalsMode = false; + dataChanged = true; + } + + //Show fixed normal + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = _fixedNormal.hasMixedValue; + Vector3 normal = EditorGUILayout.Vector3Field(_fixedNormalDirectionText, _fixedNormal.vectorValue); + if (EditorGUI.EndChangeCheck()) { + _fixedNormal.vectorValue = new Vector4(normal.x, normal.y, normal.z, 1.0f); + dataChanged = true; + } + + //Show adjust for back face rendering + { + bool fixBackFaceRendering = GetMaterialFixedNormalsBackfaceRenderingOn((Material)_materialEditor.target); + bool mixedBackFaceRendering = false; + foreach (Material material in _materialEditor.targets) { + if (fixBackFaceRendering != GetMaterialFixedNormalsBackfaceRenderingOn(material)) { + mixedBackFaceRendering = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedBackFaceRendering; + bool backRendering = EditorGUILayout.Toggle(_adjustBackfaceTangentText, fixBackFaceRendering); + + if (EditorGUI.EndChangeCheck()) { + SetNormalsMode(_materialEditor, normalsMode, backRendering); + dataChanged = true; + } + } + + } + + EditorGUI.showMixedValue = false; + + return dataChanged; + } + + protected virtual bool RenderDiffuseRampProperties () { + bool dataChanged = false; + + eDiffuseRampMode rampMode = GetMaterialDiffuseRampMode((Material)_materialEditor.target); + bool mixedRampMode = false; + foreach (Material material in _materialEditor.targets) { + if (rampMode != GetMaterialDiffuseRampMode(material)) { + mixedRampMode = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedRampMode; + EditorGUILayout.BeginHorizontal(); + + if (_diffuseRamp != null) + _materialEditor.TexturePropertySingleLine(_diffuseRampText, _diffuseRamp); + + if (EditorGUI.EndChangeCheck()) { + if (rampMode == eDiffuseRampMode.NoRampSpecified) + rampMode = eDiffuseRampMode.DefaultRampMode; + + SetDiffuseRampMode(_materialEditor, rampMode); + mixedRampMode = false; + dataChanged = true; + } + + if (_diffuseRamp != null && _diffuseRamp.textureValue != null) { + //Show drop down for ramp mode + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedRampMode; + rampMode = (eDiffuseRampMode)EditorGUILayout.Popup((int)rampMode, _fixedDiffuseRampModeOptions); + if (EditorGUI.EndChangeCheck()) { + SetDiffuseRampMode(_materialEditor, rampMode); + mixedRampMode = false; + dataChanged = true; + } + } + EditorGUILayout.EndHorizontal(); + + EditorGUI.showMixedValue = false; + + return dataChanged; + } + + protected virtual bool RenderShadowsProperties () { + bool dataChanged = false; + + EditorGUI.BeginChangeCheck(); + _materialEditor.RangeProperty(_shadowAlphaCutoff, _shadowAlphaCutoffText.text); + dataChanged = EditorGUI.EndChangeCheck(); + bool areMixedShaders = false; + bool hasReceiveShadowsParameter = IsLWRPShader(_materialEditor, out areMixedShaders) || + IsURP3DShader(_materialEditor, out areMixedShaders); + + if (hasReceiveShadowsParameter) { + EditorGUI.BeginChangeCheck(); + bool mixedValue; + bool enableReceive = !IsKeywordEnabled(_materialEditor, "_RECEIVE_SHADOWS_OFF", out mixedValue); + EditorGUI.showMixedValue = mixedValue; + enableReceive = EditorGUILayout.Toggle(_receiveShadowsText, enableReceive); + + EditorGUI.showMixedValue = false; + + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_RECEIVE_SHADOWS_OFF", !enableReceive); + dataChanged = true; + } + } + + return dataChanged; + } + + protected virtual bool RenderSphericalHarmonicsProperties () { + + bool areMixedShaders = false; + bool isLWRPShader = IsLWRPShader(_materialEditor, out areMixedShaders); + bool isURP3DShader = IsURP3DShader(_materialEditor, out areMixedShaders); + bool isURP2DShader = IsURP2DShader(_materialEditor, out areMixedShaders); + bool hasSHParameter = !(isLWRPShader || isURP3DShader || isURP2DShader); + if (!hasSHParameter) + return false; + + EditorGUI.BeginChangeCheck(); + bool mixedValue; + bool enabled = IsKeywordEnabled(_materialEditor, "_SPHERICAL_HARMONICS", out mixedValue); + EditorGUI.showMixedValue = mixedValue; + enabled = BoldToggleField(_sphericalHarmonicsText, enabled); + EditorGUI.showMixedValue = false; + + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_SPHERICAL_HARMONICS", enabled); + return true; + } + + return false; + } + + protected virtual bool RenderFogProperties () { + + bool areMixedShaders = false; + bool isURP2DShader = IsURP2DShader(_materialEditor, out areMixedShaders); + + if (isURP2DShader && !areMixedShaders) + return false; + + EditorGUI.BeginChangeCheck(); + bool mixedValue; + bool fog = IsKeywordEnabled(_materialEditor, "_FOG", out mixedValue); + EditorGUI.showMixedValue = mixedValue; + fog = BoldToggleField(_fogToggleText, fog); + EditorGUI.showMixedValue = false; + + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_FOG", fog); + return true; + } + + return false; + } + + protected virtual bool RenderColorProperties () { + bool dataChanged = false; + + EditorGUI.BeginChangeCheck(); + bool mixedValue; + bool colorAdjust = IsKeywordEnabled(_materialEditor, "_COLOR_ADJUST", out mixedValue); + EditorGUI.showMixedValue = mixedValue; + colorAdjust = BoldToggleField(_colorAdjustmentToggleText, colorAdjust); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_COLOR_ADJUST", colorAdjust); + mixedValue = false; + dataChanged = true; + } + + if (colorAdjust && !mixedValue) { + EditorGUI.BeginChangeCheck(); + _materialEditor.ColorProperty(_overlayColor, _colorAdjustmentColorText.text); + _materialEditor.RangeProperty(_hue, _colorAdjustmentHueText.text); + _materialEditor.RangeProperty(_saturation, _colorAdjustmentSaturationText.text); + _materialEditor.RangeProperty(_brightness, _colorAdjustmentBrightnessText.text); + dataChanged |= EditorGUI.EndChangeCheck(); + } + + return dataChanged; + } + + protected virtual bool RenderSpecularProperties () { + bool dataChanged = false; + + bool mixedSpecularValue; + bool specular = IsKeywordEnabled(_materialEditor, "_SPECULAR", out mixedSpecularValue); + bool mixedSpecularGlossMapValue; + bool specularGlossMap = IsKeywordEnabled(_materialEditor, "_SPECULAR_GLOSSMAP", out mixedSpecularGlossMapValue); + bool mixedValue = mixedSpecularValue || mixedSpecularGlossMapValue; + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedValue; + bool specularEnabled = BoldToggleField(_specularToggleText, specular || specularGlossMap); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) { + foreach (Material material in _materialEditor.targets) { + bool hasGlossMap = material.GetTexture("_MetallicGlossMap") != null; + SetKeyword(material, "_SPECULAR", specularEnabled && !hasGlossMap); + SetKeyword(material, "_SPECULAR_GLOSSMAP", specularEnabled && hasGlossMap); + } + + mixedValue = false; + dataChanged = true; + } + + if (specularEnabled && !mixedValue) { + EditorGUI.BeginChangeCheck(); + bool hasGlossMap = _metallicGlossMap.textureValue != null; + _materialEditor.TexturePropertySingleLine(_metallicMapText, _metallicGlossMap, hasGlossMap ? null : _metallic); + if (EditorGUI.EndChangeCheck()) { + hasGlossMap = _metallicGlossMap.textureValue != null; + SetKeyword(_materialEditor, "_SPECULAR", !hasGlossMap); + SetKeyword(_materialEditor, "_SPECULAR_GLOSSMAP", hasGlossMap); + + dataChanged = true; + } + + const int indentation = 2; + _materialEditor.ShaderProperty(hasGlossMap ? _smoothnessScale : _smoothness, hasGlossMap ? _smoothnessScaleText : _smoothnessText, indentation); + } + + return dataChanged; + } + + protected virtual bool RenderEmissionProperties () { + bool dataChanged = false; + + bool mixedValue; + bool emission = IsKeywordEnabled(_materialEditor, "_EMISSION", out mixedValue); + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedValue; + emission = BoldToggleField(_emissionToggleText, emission); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_EMISSION", emission); + mixedValue = false; + dataChanged = true; + } + + if (emission && !mixedValue) { + EditorGUI.BeginChangeCheck(); + +#if UNITY_2018_1_OR_NEWER + _materialEditor.TexturePropertyWithHDRColor(_emissionText, _emissionMap, _emissionColor, true); +#else + _materialEditor.TexturePropertyWithHDRColor(_emissionText, _emissionMap, _emissionColor, new ColorPickerHDRConfig(0, 1, 0.01010101f, 3), true); +#endif + _materialEditor.FloatProperty(_emissionPower, _emissionPowerText.text); + dataChanged |= EditorGUI.EndChangeCheck(); + } + + return dataChanged; + } + + protected virtual bool RenderRimLightingProperties () { + bool dataChanged = false; + + bool mixedValue; + bool rimLighting = IsKeywordEnabled(_materialEditor, "_RIM_LIGHTING", out mixedValue); + + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = mixedValue; + rimLighting = BoldToggleField(_rimLightingToggleText, rimLighting); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) { + SetKeyword(_materialEditor, "_RIM_LIGHTING", rimLighting); + mixedValue = false; + dataChanged = true; + } + + if (rimLighting && !mixedValue) { + EditorGUI.BeginChangeCheck(); + _materialEditor.ColorProperty(_rimColor, _rimColorText.text); + _materialEditor.FloatProperty(_rimPower, _rimPowerText.text); + dataChanged |= EditorGUI.EndChangeCheck(); + } + + return dataChanged; + } + + #endregion + + #region Private Functions + + void RenderMeshInfoBox () { + var material = (Material)_materialEditor.target; + bool requiresNormals = _fixedNormal != null && GetMaterialNormalsMode(material) == eNormalsMode.MeshNormals; + bool requiresTangents = material.HasProperty("_BumpMap") && material.GetTexture("_BumpMap") != null; + + if (requiresNormals || requiresTangents) { + GUILayout.Label(requiresNormals && requiresTangents ? _meshRequiresNormalsAndTangentsText : requiresNormals ? _meshRequiresNormalsText : _meshRequiresTangentsText, GUI.skin.GetStyle("helpBox")); + } + } + + void SetInt (string propertyName, int value) { + foreach (Material material in _materialEditor.targets) { + material.SetInt(propertyName, value); + } + } + + void SetDefaultSpriteKeywords (Material material, Shader shader) { + //Disable emission by default (is set on by default in standard shader) + SetKeyword(material, "_EMISSION", false); + //Start with preMultiply alpha by default + SetBlendMode(material, eBlendMode.PreMultipliedAlpha); + SetDiffuseRampMode(material, eDiffuseRampMode.DefaultRampMode); + //Start with mesh normals by default + SetNormalsMode(material, eNormalsMode.MeshNormals, false); + if (_fixedNormal != null) + _fixedNormal.vectorValue = new Vector4(0.0f, 0.0f, 1.0f, 1.0f); + //Start with spherical harmonics disabled? + SetKeyword(material, "_SPHERICAL_HARMONICS", false); + //Start with specular disabled + SetKeyword(material, "_SPECULAR", false); + SetKeyword(material, "_SPECULAR_GLOSSMAP", false); + //Start with Culling disabled + material.SetInt("_Cull", (int)eCulling.Off); + //Start with Z writing disabled + if (material.HasProperty("_ZWrite")) + material.SetInt("_ZWrite", 0); + } + + //Z write is on then + + static void SetRenderType (Material material, string renderType, bool useCustomRenderQueue) { + //Want a check box to say if should use Sprite render queue (for custom writing depth and normals) + bool zWrite = HasZWriteEnabled(material); + + if (useCustomRenderQueue) { + //If sprite has fixed normals then assign custom render type so we can write its correct normal with soft edges + eNormalsMode normalsMode = GetMaterialNormalsMode(material); + + switch (normalsMode) { + case eNormalsMode.FixedNormalsViewSpace: + renderType = "SpriteViewSpaceFixedNormal"; + break; + case eNormalsMode.FixedNormalsModelSpace: + renderType = "SpriteModelSpaceFixedNormal"; + break; + case eNormalsMode.MeshNormals: + { + //If sprite doesn't write to depth assign custom render type so we can write its depth with soft edges + if (!zWrite) { + renderType = "Sprite"; + } + } + break; + } + } + + //If we don't write to depth set tag so custom shaders can write to depth themselves + material.SetOverrideTag("AlphaDepth", zWrite ? "False" : "True"); + + material.SetOverrideTag("RenderType", renderType); + } + + static void SetMaterialKeywords (Material material) { + eBlendMode blendMode = GetMaterialBlendMode(material); + SetBlendMode(material, blendMode); + + bool zWrite = HasZWriteEnabled(material); + bool clipAlpha = zWrite && blendMode != eBlendMode.Opaque && material.GetFloat("_Cutoff") > 0.0f; + SetKeyword(material, "_ALPHA_CLIP", clipAlpha); + + bool normalMap = material.HasProperty("_BumpMap") && material.GetTexture("_BumpMap") != null; + SetKeyword(material, "_NORMALMAP", normalMap); + + bool diffuseRamp = material.HasProperty("_DiffuseRamp") && material.GetTexture("_DiffuseRamp") != null; + SetKeyword(material, "_DIFFUSE_RAMP", diffuseRamp); + + bool blendTexture = material.HasProperty("_BlendTex") && material.GetTexture("_BlendTex") != null; + SetKeyword(material, "_TEXTURE_BLEND", blendTexture); + } + + static void MaterialChanged (MaterialEditor materialEditor) { + foreach (Material material in materialEditor.targets) + SetMaterialKeywords(material); + } + + static void SetKeyword (MaterialEditor m, string keyword, bool state) { + foreach (Material material in m.targets) { + SetKeyword(material, keyword, state); + } + } + + static void SetKeyword (Material m, string keyword, bool state) { + if (state) + m.EnableKeyword(keyword); + else + m.DisableKeyword(keyword); + } + + static bool IsLWRPShader (MaterialEditor editor, out bool mixedValue) { + return IsShaderType(kShaderLitLW, editor, out mixedValue); + } + + static bool IsURP3DShader (MaterialEditor editor, out bool mixedValue) { + return IsShaderType(kShaderLitURP, editor, out mixedValue); + } + + static bool IsURP2DShader (MaterialEditor editor, out bool mixedValue) { + return IsShaderType(kShaderLitURP2D, editor, out mixedValue); + } + + static bool IsShaderType (string shaderType, MaterialEditor editor, out bool mixedValue) { + + mixedValue = false; + bool isAnyTargetTypeShader = false; + foreach (Material material in editor.targets) { + if (material.shader.name == shaderType) { + isAnyTargetTypeShader = true; + } + else if (isAnyTargetTypeShader) { + mixedValue = true; + } + } + return isAnyTargetTypeShader; + } + + static bool IsKeywordEnabled (MaterialEditor editor, string keyword, out bool mixedValue) { + bool keywordEnabled = ((Material)editor.target).IsKeywordEnabled(keyword); + mixedValue = false; + + foreach (Material material in editor.targets) { + if (material.IsKeywordEnabled(keyword) != keywordEnabled) { + mixedValue = true; + break; + } + } + + return keywordEnabled; + } + + static eLightMode GetMaterialLightMode (Material material) { + if (material.shader.name == kShaderPixelLit || + material.shader.name == kShaderPixelLitOutline) { + return eLightMode.PixelLit; + } + else if (material.shader.name == kShaderUnlit || + material.shader.name == kShaderUnlitOutline) { + return eLightMode.Unlit; + } + else if (material.shader.name == kShaderLitLW) { + return eLightMode.LitLightweight; + } + else if (material.shader.name == kShaderLitURP) { + return eLightMode.LitUniversal; + } + else if (material.shader.name == kShaderLitURP2D) { + return eLightMode.LitUniversal2D; + } + else { // if (material.shader.name == kShaderVertexLit || kShaderVertexLitOutline) + return eLightMode.VertexLit; + } + } + + static eBlendMode GetMaterialBlendMode (Material material) { + if (material.IsKeywordEnabled("_ALPHABLEND_ON")) + return eBlendMode.StandardAlpha; + if (material.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON")) + return eBlendMode.PreMultipliedAlpha; + if (material.IsKeywordEnabled("_MULTIPLYBLEND")) + return eBlendMode.Multiply; + if (material.IsKeywordEnabled("_MULTIPLYBLEND_X2")) + return eBlendMode.Multiplyx2; + if (material.IsKeywordEnabled("_ADDITIVEBLEND")) + return eBlendMode.Additive; + if (material.IsKeywordEnabled("_ADDITIVEBLEND_SOFT")) + return eBlendMode.SoftAdditive; + + return eBlendMode.Opaque; + } + + static void SetBlendMode (Material material, eBlendMode blendMode) { + SetKeyword(material, "_ALPHABLEND_ON", blendMode == eBlendMode.StandardAlpha); + SetKeyword(material, "_ALPHAPREMULTIPLY_ON", blendMode == eBlendMode.PreMultipliedAlpha); + SetKeyword(material, "_MULTIPLYBLEND", blendMode == eBlendMode.Multiply); + SetKeyword(material, "_MULTIPLYBLEND_X2", blendMode == eBlendMode.Multiplyx2); + SetKeyword(material, "_ADDITIVEBLEND", blendMode == eBlendMode.Additive); + SetKeyword(material, "_ADDITIVEBLEND_SOFT", blendMode == eBlendMode.SoftAdditive); + + int renderQueue; + bool useCustomRenderQueue = material.GetFloat("_CustomRenderQueue") > 0.0f; + + switch (blendMode) { + case eBlendMode.Opaque: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); + SetRenderType(material, "Opaque", useCustomRenderQueue); + renderQueue = kSolidQueue; + } + break; + case eBlendMode.Additive: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.One); + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderQueue); + renderQueue = zWrite ? kAlphaTestQueue : kTransparentQueue; + } + break; + case eBlendMode.SoftAdditive: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcColor); + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderQueue); + renderQueue = zWrite ? kAlphaTestQueue : kTransparentQueue; + } + break; + case eBlendMode.Multiply: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.Zero); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.SrcColor); + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderQueue); + renderQueue = zWrite ? kAlphaTestQueue : kTransparentQueue; + } + break; + case eBlendMode.Multiplyx2: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.DstColor); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.SrcColor); + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderQueue); + renderQueue = zWrite ? kAlphaTestQueue : kTransparentQueue; + } + break; + default: + { + material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + bool zWrite = HasZWriteEnabled(material); + SetRenderType(material, zWrite ? "TransparentCutout" : "Transparent", useCustomRenderQueue); + renderQueue = zWrite ? kAlphaTestQueue : kTransparentQueue; + } + break; + } + + material.renderQueue = renderQueue + material.GetInt("_RenderQueue"); + material.SetOverrideTag("IgnoreProjector", blendMode == eBlendMode.Opaque ? "False" : "True"); + } + + static eNormalsMode GetMaterialNormalsMode (Material material) { + if (material.IsKeywordEnabled("_FIXED_NORMALS_VIEWSPACE") || material.IsKeywordEnabled("_FIXED_NORMALS_VIEWSPACE_BACKFACE")) + return eNormalsMode.FixedNormalsViewSpace; + if (material.IsKeywordEnabled("_FIXED_NORMALS_WORLDSPACE")) + return eNormalsMode.FixedNormalsWorldSpace; + if (material.IsKeywordEnabled("_FIXED_NORMALS_MODELSPACE") || material.IsKeywordEnabled("_FIXED_NORMALS_MODELSPACE_BACKFACE")) + return eNormalsMode.FixedNormalsModelSpace; + + return eNormalsMode.MeshNormals; + } + + + static void SetNormalsMode (MaterialEditor materialEditor, eNormalsMode normalsMode, bool allowBackFaceRendering) { + foreach (Material material in materialEditor.targets) { + SetNormalsMode(material, normalsMode, allowBackFaceRendering); + } + } + + static void SetNormalsMode (Material material, eNormalsMode normalsMode, bool allowBackFaceRendering) { + SetKeyword(material, "_FIXED_NORMALS_VIEWSPACE", normalsMode == eNormalsMode.FixedNormalsViewSpace && !allowBackFaceRendering); + SetKeyword(material, "_FIXED_NORMALS_VIEWSPACE_BACKFACE", normalsMode == eNormalsMode.FixedNormalsViewSpace && allowBackFaceRendering); + SetKeyword(material, "_FIXED_NORMALS_WORLDSPACE", normalsMode == eNormalsMode.FixedNormalsWorldSpace); + SetKeyword(material, "_FIXED_NORMALS_MODELSPACE", normalsMode == eNormalsMode.FixedNormalsModelSpace && !allowBackFaceRendering); + SetKeyword(material, "_FIXED_NORMALS_MODELSPACE_BACKFACE", normalsMode == eNormalsMode.FixedNormalsModelSpace && allowBackFaceRendering); + } + + static bool GetMaterialFixedNormalsBackfaceRenderingOn (Material material) { + return material.IsKeywordEnabled("_FIXED_NORMALS_VIEWSPACE_BACKFACE") || material.IsKeywordEnabled("_FIXED_NORMALS_MODELSPACE_BACKFACE"); + } + + static eDiffuseRampMode GetMaterialDiffuseRampMode (Material material) { + if (material.IsKeywordEnabled("_FULLRANGE_HARD_RAMP")) + return eDiffuseRampMode.FullRangeHard; + if (material.IsKeywordEnabled("_FULLRANGE_SOFT_RAMP")) + return eDiffuseRampMode.FullRangeSoft; + if (material.IsKeywordEnabled("_OLD_HARD_RAMP")) + return eDiffuseRampMode.OldHard; + if (material.IsKeywordEnabled("_OLD_SOFT_RAMP")) + return eDiffuseRampMode.OldSoft; + + return eDiffuseRampMode.NoRampSpecified; + } + + static void SetDiffuseRampMode (MaterialEditor materialEditor, eDiffuseRampMode rampMode) { + foreach (Material material in materialEditor.targets) { + SetDiffuseRampMode(material, rampMode); + } + } + + static void SetDiffuseRampMode (Material material, eDiffuseRampMode rampMode) { + SetKeyword(material, "_FULLRANGE_HARD_RAMP", rampMode == eDiffuseRampMode.FullRangeHard); + SetKeyword(material, "_FULLRANGE_SOFT_RAMP", rampMode == eDiffuseRampMode.FullRangeSoft); + SetKeyword(material, "_OLD_HARD_RAMP", rampMode == eDiffuseRampMode.OldHard); + SetKeyword(material, "_OLD_SOFT_RAMP", rampMode == eDiffuseRampMode.OldSoft); + } + + static bool HasZWriteEnabled (Material material) { + if (material.HasProperty("_ZWrite")) { + return material.GetFloat("_ZWrite") > 0.0f; + } + else return true; // Pixel Lit shader always has _ZWrite enabled. + } + #endregion +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs.meta new file mode 100644 index 0000000..2215e75 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Shaders/SpineSpriteShaderGUI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: aef90b4c481362e42891bb46de344c1c +timeCreated: 1479458475 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs new file mode 100644 index 0000000..33a9283 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs @@ -0,0 +1,602 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Contributed by: Mitch Thompson + +using UnityEngine; +using UnityEditor; +using System; +using System.Collections.Generic; +using System.Reflection; +using Spine; +using System.Linq; + +namespace Spine.Unity.Editor { + public struct SpineDrawerValuePair { + public string stringValue; + public SerializedProperty property; + + public SpineDrawerValuePair (string val, SerializedProperty property) { + this.stringValue = val; + this.property = property; + } + } + + public abstract class SpineTreeItemDrawerBase : PropertyDrawer where T:SpineAttributeBase { + protected SkeletonDataAsset skeletonDataAsset; + internal const string NoneStringConstant = ""; + + internal virtual string NoneString { get { return NoneStringConstant; } } + + GUIContent noneLabel; + GUIContent NoneLabel (Texture2D image = null) { + if (noneLabel == null) noneLabel = new GUIContent(NoneString); + noneLabel.image = image; + return noneLabel; + } + + protected T TargetAttribute { get { return (T)attribute; } } + protected SerializedProperty SerializedProperty { get; private set; } + + protected abstract Texture2D Icon { get; } + + public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { + SerializedProperty = property; + + if (property.propertyType != SerializedPropertyType.String) { + EditorGUI.LabelField(position, "ERROR:", "May only apply to type string"); + return; + } + + // Handle multi-editing when instances don't use the same SkeletonDataAsset. + if (!SpineInspectorUtility.TargetsUseSameData(property.serializedObject)) { + EditorGUI.DelayedTextField(position, property, label); + return; + } + + SerializedProperty dataField = property.FindBaseOrSiblingProperty(TargetAttribute.dataField); + + if (dataField != null) { + var objectReferenceValue = dataField.objectReferenceValue; + if (objectReferenceValue is SkeletonDataAsset) { + skeletonDataAsset = (SkeletonDataAsset)objectReferenceValue; + } else if (objectReferenceValue is IHasSkeletonDataAsset) { + var hasSkeletonDataAsset = (IHasSkeletonDataAsset)objectReferenceValue; + if (hasSkeletonDataAsset != null) + skeletonDataAsset = hasSkeletonDataAsset.SkeletonDataAsset; + } else if (objectReferenceValue != null) { + EditorGUI.LabelField(position, "ERROR:", "Invalid reference type"); + return; + } + + } else { + var targetObject = property.serializedObject.targetObject; + + IHasSkeletonDataAsset hasSkeletonDataAsset = targetObject as IHasSkeletonDataAsset; + if (hasSkeletonDataAsset == null) { + var component = targetObject as Component; + if (component != null) + hasSkeletonDataAsset = component.GetComponentInChildren(typeof(IHasSkeletonDataAsset)) as IHasSkeletonDataAsset; + } + + if (hasSkeletonDataAsset != null) + skeletonDataAsset = hasSkeletonDataAsset.SkeletonDataAsset; + } + + if (skeletonDataAsset == null) { + if (TargetAttribute.fallbackToTextField) { + EditorGUI.PropertyField(position, property); //EditorGUI.TextField(position, label, property.stringValue); + } else { + EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset"); + } + + skeletonDataAsset = property.serializedObject.targetObject as SkeletonDataAsset; + if (skeletonDataAsset == null) return; + } + + position = EditorGUI.PrefixLabel(position, label); + + Texture2D image = Icon; + string propertyStringValue = (property.hasMultipleDifferentValues) ? SpineInspectorUtility.EmDash : property.stringValue; + if (GUI.Button(position, string.IsNullOrEmpty(propertyStringValue) ? NoneLabel(image) : SpineInspectorUtility.TempContent(propertyStringValue, image), EditorStyles.popup)) + Selector(property); + } + + public ISkeletonComponent GetTargetSkeletonComponent (SerializedProperty property) { + var dataField = property.FindBaseOrSiblingProperty(TargetAttribute.dataField); + + if (dataField != null) { + var skeletonComponent = dataField.objectReferenceValue as ISkeletonComponent; + if (dataField.objectReferenceValue != null && skeletonComponent != null) // note the overloaded UnityEngine.Object == null check. Do not simplify. + return skeletonComponent; + } else { + var component = property.serializedObject.targetObject as Component; + if (component != null) + return component.GetComponentInChildren(typeof(ISkeletonComponent)) as ISkeletonComponent; + } + + return null; + } + + protected virtual void Selector (SerializedProperty property) { + SkeletonData data = skeletonDataAsset.GetSkeletonData(true); + if (data == null) return; + + var menu = new GenericMenu(); + PopulateMenu(menu, property, this.TargetAttribute, data); + menu.ShowAsContext(); + } + + protected abstract void PopulateMenu (GenericMenu menu, SerializedProperty property, T targetAttribute, SkeletonData data); + + protected virtual void HandleSelect (object menuItemObject) { + var clickedItem = (SpineDrawerValuePair)menuItemObject; + var serializedProperty = clickedItem.property; + if (serializedProperty.serializedObject.isEditingMultipleObjects) serializedProperty.stringValue = "oaifnoiasf��123526"; // HACK: to trigger change on multi-editing. + serializedProperty.stringValue = clickedItem.stringValue; + serializedProperty.serializedObject.ApplyModifiedProperties(); + } + + public override float GetPropertyHeight (SerializedProperty property, GUIContent label) { + return 18; + } + + } + + [CustomPropertyDrawer(typeof(SpineSlot))] + public class SpineSlotDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.slot; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSlot targetAttribute, SkeletonData data) { + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + IEnumerable orderedSlots = data.Slots.Items.OrderBy(slotData => slotData.Name); + foreach (SlotData slotData in orderedSlots) { + int slotIndex = slotData.Index; + string name = slotData.Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) { + + if (targetAttribute.containsBoundingBoxes) { + var skinEntries = new List(); + foreach (var skin in data.Skins) { + skin.GetAttachments(slotIndex, skinEntries); + } + + bool hasBoundingBox = false; + foreach (var entry in skinEntries) { + var bbAttachment = entry.Attachment as BoundingBoxAttachment; + if (bbAttachment != null) { + string menuLabel = bbAttachment.IsWeighted() ? name + " (!)" : name; + menu.AddItem(new GUIContent(menuLabel), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + hasBoundingBox = true; + break; + } + } + + if (!hasBoundingBox) + menu.AddDisabledItem(new GUIContent(name)); + + } else { + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + + } + + } + } + + } + + [CustomPropertyDrawer(typeof(SpineSkin))] + public class SpineSkinDrawer : SpineTreeItemDrawerBase { + const string DefaultSkinName = "default"; + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.skin; } } + + internal override string NoneString { get { return TargetAttribute.defaultAsEmptyString ? DefaultSkinName : NoneStringConstant; } } + + public static void GetSkinMenuItems (SkeletonData data, List outputNames, List outputMenuItems, bool includeNone = true) { + if (data == null) return; + if (outputNames == null) return; + if (outputMenuItems == null) return; + + var skins = data.Skins; + + outputNames.Clear(); + outputMenuItems.Clear(); + + var icon = SpineEditorUtilities.Icons.skin; + + if (includeNone) { + outputNames.Add(""); + outputMenuItems.Add(new GUIContent(NoneStringConstant, icon)); + } + + foreach (var s in skins) { + string skinName = s.Name; + outputNames.Add(skinName); + outputMenuItems.Add(new GUIContent(skinName, icon)); + } + } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSkin targetAttribute, SkeletonData data) { + menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); + menu.AddSeparator(""); + + for (int i = 0; i < data.Skins.Count; i++) { + string name = data.Skins.Items[i].Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) { + bool isDefault = string.Equals(name, DefaultSkinName, StringComparison.Ordinal); + string choiceValue = TargetAttribute.defaultAsEmptyString && isDefault ? string.Empty : name; + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && choiceValue == property.stringValue, HandleSelect, new SpineDrawerValuePair(choiceValue, property)); + } + + } + } + + } + + [CustomPropertyDrawer(typeof(SpineAnimation))] + public class SpineAnimationDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.animation; } } + + public static void GetAnimationMenuItems (SkeletonData data, List outputNames, List outputMenuItems, bool includeNone = true) { + if (data == null) return; + if (outputNames == null) return; + if (outputMenuItems == null) return; + + var animations = data.Animations; + + outputNames.Clear(); + outputMenuItems.Clear(); + + if (includeNone) { + outputNames.Add(""); + outputMenuItems.Add(new GUIContent(NoneStringConstant, SpineEditorUtilities.Icons.animation)); + } + + foreach (var a in animations) { + string animationName = a.Name; + outputNames.Add(animationName); + outputMenuItems.Add(new GUIContent(animationName, SpineEditorUtilities.Icons.animation)); + } + } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAnimation targetAttribute, SkeletonData data) { + var animations = skeletonDataAsset.GetAnimationStateData().SkeletonData.Animations; + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < animations.Count; i++) { + string name = animations.Items[i].Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + + } + + [CustomPropertyDrawer(typeof(SpineEvent))] + public class SpineEventNameDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.userEvent; } } + + public static void GetEventMenuItems (SkeletonData data, List eventNames, List menuItems, bool includeNone = true) { + if (data == null) return; + + var animations = data.Events; + + eventNames.Clear(); + menuItems.Clear(); + + if (includeNone) { + eventNames.Add(""); + menuItems.Add(new GUIContent(NoneStringConstant, SpineEditorUtilities.Icons.userEvent)); + } + + foreach (var a in animations) { + string animationName = a.Name; + eventNames.Add(animationName); + menuItems.Add(new GUIContent(animationName, SpineEditorUtilities.Icons.userEvent)); + } + } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineEvent targetAttribute, SkeletonData data) { + var events = skeletonDataAsset.GetSkeletonData(false).Events; + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < events.Count; i++) { + var eventObject = events.Items[i]; + string name = eventObject.Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) { + if (!TargetAttribute.audioOnly || !string.IsNullOrEmpty(eventObject.AudioPath)) { + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + + } + } + + } + + [CustomPropertyDrawer(typeof(SpineIkConstraint))] + public class SpineIkConstraintDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintIK; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineIkConstraint targetAttribute, SkeletonData data) { + var constraints = skeletonDataAsset.GetSkeletonData(false).IkConstraints; + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < constraints.Count; i++) { + string name = constraints.Items[i].Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + + } + + [CustomPropertyDrawer(typeof(SpineTransformConstraint))] + public class SpineTransformConstraintDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintTransform; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineTransformConstraint targetAttribute, SkeletonData data) { + var constraints = skeletonDataAsset.GetSkeletonData(false).TransformConstraints; + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < constraints.Count; i++) { + string name = constraints.Items[i].Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + } + + [CustomPropertyDrawer(typeof(SpinePathConstraint))] + public class SpinePathConstraintDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintPath; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpinePathConstraint targetAttribute, SkeletonData data) { + var constraints = skeletonDataAsset.GetSkeletonData(false).PathConstraints; + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < constraints.Count; i++) { + string name = constraints.Items[i].Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + } + + [CustomPropertyDrawer(typeof(SpineAttachment))] + public class SpineAttachmentDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.genericAttachment; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAttachment targetAttribute, SkeletonData data) { + ISkeletonComponent skeletonComponent = GetTargetSkeletonComponent(property); + var validSkins = new List(); + + if (skeletonComponent != null && targetAttribute.currentSkinOnly) { + Skin currentSkin = null; + + var skinProperty = property.FindBaseOrSiblingProperty(targetAttribute.skinField); + if (skinProperty != null) currentSkin = skeletonComponent.Skeleton.Data.FindSkin(skinProperty.stringValue); + + currentSkin = currentSkin ?? skeletonComponent.Skeleton.Skin; + if (currentSkin != null) + validSkins.Add(currentSkin); + else + validSkins.Add(data.Skins.Items[0]); + + } else { + foreach (Skin skin in data.Skins) + if (skin != null) validSkins.Add(skin); + } + + var attachmentNames = new List(); + var placeholderNames = new List(); + string prefix = ""; + + if (skeletonComponent != null && targetAttribute.currentSkinOnly) + menu.AddDisabledItem(new GUIContent((skeletonComponent as Component).gameObject.name + " (Skeleton)")); + else + menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); + + menu.AddSeparator(""); + if (TargetAttribute.includeNone) { + const string NullAttachmentName = ""; + menu.AddItem(new GUIContent("Null"), !property.hasMultipleDifferentValues && property.stringValue == NullAttachmentName, HandleSelect, new SpineDrawerValuePair(NullAttachmentName, property)); + menu.AddSeparator(""); + } + + Skin defaultSkin = data.Skins.Items[0]; + var slotProperty = property.FindBaseOrSiblingProperty(TargetAttribute.slotField); + + string slotMatch = ""; + if (slotProperty != null) { + if (slotProperty.propertyType == SerializedPropertyType.String) + slotMatch = slotProperty.stringValue.ToLower(); + } + + foreach (Skin skin in validSkins) { + string skinPrefix = skin.Name + "/"; + + if (validSkins.Count > 1) + prefix = skinPrefix; + + for (int i = 0; i < data.Slots.Count; i++) { + if (slotMatch.Length > 0 && !(data.Slots.Items[i].Name.Equals(slotMatch, StringComparison.OrdinalIgnoreCase))) + continue; + + attachmentNames.Clear(); + placeholderNames.Clear(); + + var skinEntries = new List(); + skin.GetAttachments(i, skinEntries); + foreach (var entry in skinEntries) { + attachmentNames.Add(entry.Name); + } + + if (skin != defaultSkin) { + foreach (var entry in skinEntries) { + placeholderNames.Add(entry.Name); + } + skinEntries.Clear(); + defaultSkin.GetAttachments(i, skinEntries); + foreach (var entry in skinEntries) { + attachmentNames.Add(entry.Name); + } + } + + for (int a = 0; a < attachmentNames.Count; a++) { + string attachmentPath = attachmentNames[a]; + string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath; + string name = attachmentNames[a]; + + if (targetAttribute.returnAttachmentPath) + name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath; + + if (targetAttribute.placeholdersOnly && !placeholderNames.Contains(attachmentPath)) { + menu.AddDisabledItem(new GUIContent(menuPath)); + } else { + menu.AddItem(new GUIContent(menuPath), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + + } + } + } + + } + + [CustomPropertyDrawer(typeof(SpineBone))] + public class SpineBoneDrawer : SpineTreeItemDrawerBase { + + protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.bone; } } + + protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineBone targetAttribute, SkeletonData data) { + menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); + menu.AddSeparator(""); + + if (TargetAttribute.includeNone) + menu.AddItem(new GUIContent(NoneString), !property.hasMultipleDifferentValues && string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property)); + + for (int i = 0; i < data.Bones.Count; i++) { + var bone = data.Bones.Items[i]; + string name = bone.Name; + if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) { + // jointName = "root/hip/bone" to show a hierarchial tree. + string jointName = name; + var iterator = bone; + while ((iterator = iterator.Parent) != null) + jointName = string.Format("{0}/{1}", iterator.Name, jointName); + + menu.AddItem(new GUIContent(jointName), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + } + } + + } + + [CustomPropertyDrawer(typeof(SpineAtlasRegion))] + public class SpineAtlasRegionDrawer : PropertyDrawer { + SerializedProperty atlasProp; + + protected SpineAtlasRegion TargetAttribute { get { return (SpineAtlasRegion)attribute; } } + + public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { + if (property.propertyType != SerializedPropertyType.String) { + EditorGUI.LabelField(position, "ERROR:", "May only apply to type string"); + return; + } + + string atlasAssetFieldName = TargetAttribute.atlasAssetField; + if (string.IsNullOrEmpty(atlasAssetFieldName)) + atlasAssetFieldName = "atlasAsset"; + + atlasProp = property.FindBaseOrSiblingProperty(atlasAssetFieldName); + + if (atlasProp == null) { + EditorGUI.LabelField(position, "ERROR:", "Must have AtlasAsset variable!"); + return; + } else if (atlasProp.objectReferenceValue == null) { + EditorGUI.LabelField(position, "ERROR:", "Atlas variable must not be null!"); + return; + } else if (!atlasProp.objectReferenceValue.GetType().IsSubclassOf(typeof(AtlasAssetBase)) && + atlasProp.objectReferenceValue.GetType() != typeof(AtlasAssetBase)) { + EditorGUI.LabelField(position, "ERROR:", "Atlas variable must be of type AtlasAsset!"); + } + + position = EditorGUI.PrefixLabel(position, label); + + if (GUI.Button(position, property.stringValue, EditorStyles.popup)) + Selector(property); + + } + + void Selector (SerializedProperty property) { + GenericMenu menu = new GenericMenu(); + AtlasAssetBase atlasAsset = (AtlasAssetBase)atlasProp.objectReferenceValue; + Atlas atlas = atlasAsset.GetAtlas(); + FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + List regions = (List)field.GetValue(atlas); + + for (int i = 0; i < regions.Count; i++) { + string name = regions[i].name; + menu.AddItem(new GUIContent(name), !property.hasMultipleDifferentValues && name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); + } + + menu.ShowAsContext(); + } + + static void HandleSelect (object val) { + var pair = (SpineDrawerValuePair)val; + pair.property.stringValue = pair.stringValue; + pair.property.serializedObject.ApplyModifiedProperties(); + } + + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs.meta new file mode 100644 index 0000000..901111a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/SpineAttributeDrawers.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f2de282d583d4a641bf1c349f0a3eef9 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility.meta new file mode 100644 index 0000000..b46de85 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 33c080d1c093a2c45b6c72c17a557067 +folderAsset: yes +timeCreated: 1563304704 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs new file mode 100644 index 0000000..8c464a8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs @@ -0,0 +1,50 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity.Editor { + public static class AssetDatabaseAvailabilityDetector { + const string MarkerResourceName = "SpineAssetDatabaseMarker"; + private static bool isMarkerLoaded; + + public static bool IsAssetDatabaseAvailable (bool forceCheck = false) { + if (!forceCheck && isMarkerLoaded) + return true; + + TextAsset markerTextAsset = Resources.Load(AssetDatabaseAvailabilityDetector.MarkerResourceName); + isMarkerLoaded = markerTextAsset != null; + if (markerTextAsset != null) { + Resources.UnloadAsset(markerTextAsset); + } + + return isMarkerLoaded; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs.meta new file mode 100644 index 0000000..00b99c1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetDatabaseAvailabilityDetector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 25086cd81e3158b439761b73d7366c47 +timeCreated: 1444587791 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs new file mode 100644 index 0000000..1ce022c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs @@ -0,0 +1,1315 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#if UNITY_2018_3_OR_NEWER +#define NEW_PREFERENCES_SETTINGS_PROVIDER +#endif + +#if UNITY_2018_2_OR_NEWER +#define EXPOSES_SPRITE_ATLAS_UTILITIES +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; + +using CompatibilityProblemInfo = Spine.Unity.SkeletonDataCompatibility.CompatibilityProblemInfo; + +namespace Spine.Unity.Editor { + + public class PathAndProblemInfo { + public string path; + public CompatibilityProblemInfo compatibilityProblems; + public string otherProblemDescription; + + public PathAndProblemInfo (string path, CompatibilityProblemInfo compatibilityInfo, string otherProblemDescription) { + this.path = path; + this.compatibilityProblems = compatibilityInfo; + this.otherProblemDescription = otherProblemDescription; + } + } + + public static class AssetUtility { + + public const string SkeletonDataSuffix = "_SkeletonData"; + public const string AtlasSuffix = "_Atlas"; + public const string SpriteAtlasSuffix = "_SpriteAtlas"; + + /// HACK: This list keeps the asset reference temporarily during importing. + /// + /// In cases of very large projects/sufficient RAM pressure, when AssetDatabase.SaveAssets is called, + /// Unity can mistakenly unload assets whose references are only on the stack. + /// This leads to MissingReferenceException and other errors. + public static readonly List protectFromStackGarbageCollection = new List(); + public static HashSet assetsImportedInWrongState = new HashSet(); + + public static void HandleOnPostprocessAllAssets (string[] imported, List texturesWithoutMetaFile) { + // In case user used "Assets -> Reimport All", during the import process, + // asset database is not initialized until some point. During that period, + // all attempts to load any assets using API (i.e. AssetDatabase.LoadAssetAtPath) + // will return null, and as result, assets won't be loaded even if they actually exists, + // which may lead to numerous importing errors. + // This situation also happens if Library folder is deleted from the project, which is a pretty + // common case, since when using version control systems, the Library folder must be excluded. + // + // So to avoid this, in case asset database is not available, we delay loading the assets + // until next time. + // + // Unity *always* reimports some internal assets after the process is done, so this method + // is always called once again in a state when asset database is available. + // + // Checking whether AssetDatabase is initialized is done by attempting to load + // a known "marker" asset that should always be available. Failing to load this asset + // means that AssetDatabase is not initialized. + AssetUtility.assetsImportedInWrongState.UnionWith(imported); + if (AssetDatabaseAvailabilityDetector.IsAssetDatabaseAvailable()) { + string[] combinedAssets = AssetUtility.assetsImportedInWrongState.ToArray(); + AssetUtility.assetsImportedInWrongState.Clear(); + AssetUtility.ImportSpineContent(combinedAssets, texturesWithoutMetaFile); + } + } + +#region Match SkeletonData with Atlases + static readonly AttachmentType[] AtlasTypes = { AttachmentType.Region, AttachmentType.Linkedmesh, AttachmentType.Mesh }; + + public static List GetRequiredAtlasRegions (string skeletonDataPath) { + List requiredPaths = new List(); + + if (skeletonDataPath.Contains(".skel")) { + AddRequiredAtlasRegionsFromBinary(skeletonDataPath, requiredPaths); + return requiredPaths; + } + + TextReader reader = null; + TextAsset spineJson = AssetDatabase.LoadAssetAtPath(skeletonDataPath); + Dictionary root = null; + try { + if (spineJson != null) { + reader = new StringReader(spineJson.text); + } + else { + // On a "Reimport All" the order of imports can be wrong, thus LoadAssetAtPath() above could return null. + // as a workaround, we provide a fallback reader. + reader = new StreamReader(skeletonDataPath); + } + root = Json.Deserialize(reader) as Dictionary; + } + finally { + if (reader != null) + reader.Dispose(); + } + + if (root == null || !root.ContainsKey("skins")) + return requiredPaths; + + var skinsList = root["skins"] as List; + if (skinsList == null) + return requiredPaths; + + foreach (Dictionary skinMap in skinsList) { + if (!skinMap.ContainsKey("attachments")) + continue; + foreach (var slot in (Dictionary)skinMap["attachments"]) { + foreach (var attachment in ((Dictionary)slot.Value)) { + var data = ((Dictionary)attachment.Value); + + // Ignore non-atlas-requiring types. + if (data.ContainsKey("type")) { + AttachmentType attachmentType; + string typeString = (string)data["type"]; + try { + attachmentType = (AttachmentType)System.Enum.Parse(typeof(AttachmentType), typeString, true); + } catch (System.ArgumentException e) { + // For more info, visit: http://esotericsoftware.com/forum/Spine-editor-and-runtime-version-management-6534 + Debug.LogWarning(string.Format("Unidentified Attachment type: \"{0}\". Skeleton may have been exported from an incompatible Spine version.", typeString), spineJson); + throw e; + } + + if (!AtlasTypes.Contains(attachmentType)) + continue; + } + + if (data.ContainsKey("path")) + requiredPaths.Add((string)data["path"]); + else if (data.ContainsKey("name")) + requiredPaths.Add((string)data["name"]); + else + requiredPaths.Add(attachment.Key); + } + } + } + + return requiredPaths; + } + + internal static void AddRequiredAtlasRegionsFromBinary (string skeletonDataPath, List requiredPaths) { + SkeletonBinary binary = new SkeletonBinary(new AtlasRequirementLoader(requiredPaths)); + Stream input = null; + TextAsset data = AssetDatabase.LoadAssetAtPath(skeletonDataPath); + try { + if (data != null) { + input = new MemoryStream(data.bytes); + } + else { + // On a "Reimport All" the order of imports can be wrong, thus LoadAssetAtPath() above could return null. + // as a workaround, we provide a fallback reader. + input = File.Open(skeletonDataPath, FileMode.Open, FileAccess.Read); + } + binary.ReadSkeletonData(input); + } + finally { + if (input != null) + input.Dispose(); + } + binary = null; + } + + internal static AtlasAssetBase GetMatchingAtlas (List requiredPaths, List atlasAssets) { + AtlasAssetBase atlasAssetMatch = null; + + foreach (AtlasAssetBase a in atlasAssets) { + Atlas atlas = a.GetAtlas(); + bool failed = false; + foreach (string regionPath in requiredPaths) { + if (atlas.FindRegion(regionPath) == null) { + failed = true; + break; + } + } + + if (!failed) { + atlasAssetMatch = a; + break; + } + } + + return atlasAssetMatch; + } + + public class AtlasRequirementLoader : AttachmentLoader { + List requirementList; + + public AtlasRequirementLoader (List requirementList) { + this.requirementList = requirementList; + } + + public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) { + requirementList.Add(path); + return new RegionAttachment(name); + } + + public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) { + requirementList.Add(path); + return new MeshAttachment(name); + } + + public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) { + return new BoundingBoxAttachment(name); + } + + public PathAttachment NewPathAttachment (Skin skin, string name) { + return new PathAttachment(name); + } + + public PointAttachment NewPointAttachment (Skin skin, string name) { + return new PointAttachment(name); + } + + public ClippingAttachment NewClippingAttachment (Skin skin, string name) { + return new ClippingAttachment(name); + } + } +#endregion + + public static void ImportSpineContent (string[] imported, List texturesWithoutMetaFile, + bool reimport = false) { + + var atlasPaths = new List(); + var imagePaths = new List(); + var skeletonPaths = new List(); + CompatibilityProblemInfo compatibilityProblemInfo = null; + + foreach (string str in imported) { + string extension = Path.GetExtension(str).ToLower(); + switch (extension) { + case ".atlas": + if (SpineEditorUtilities.Preferences.atlasTxtImportWarning) { + Debug.LogWarningFormat("`{0}` : If this file is a Spine atlas, please change its extension to `.atlas.txt`. This is to allow Unity to recognize it and avoid filename collisions. You can also set this file extension when exporting from the Spine editor.", str); + } + break; + case ".txt": + if (str.EndsWith(".atlas.txt", System.StringComparison.Ordinal)) + atlasPaths.Add(str); + break; + case ".png": + case ".jpg": + imagePaths.Add(str); + break; + case ".json": { + var jsonAsset = AssetDatabase.LoadAssetAtPath(str); + string problemDescription = null; + if (jsonAsset != null && IsSpineData(jsonAsset, out compatibilityProblemInfo, ref problemDescription)) + skeletonPaths.Add(new PathAndProblemInfo(str, compatibilityProblemInfo, problemDescription)); + if (problemDescription != null) + Debug.LogError(problemDescription, jsonAsset); + break; + } + case ".bytes": { + if (str.ToLower().EndsWith(".skel.bytes", System.StringComparison.Ordinal)) { + var binaryAsset = AssetDatabase.LoadAssetAtPath(str); + string problemDescription = null; + if (IsSpineData(binaryAsset, out compatibilityProblemInfo, ref problemDescription)) + skeletonPaths.Add(new PathAndProblemInfo(str, compatibilityProblemInfo, problemDescription)); + if (problemDescription != null) + Debug.LogError(problemDescription, binaryAsset); + } + break; + } + } + } + + // Import atlases first. + var newAtlases = new List(); + foreach (string ap in atlasPaths) { + if (ap.StartsWith("Packages")) + continue; + TextAsset atlasText = AssetDatabase.LoadAssetAtPath(ap); + AtlasAssetBase atlas = IngestSpineAtlas(atlasText, texturesWithoutMetaFile); + newAtlases.Add(atlas); + } + AddDependentSkeletonIfAtlasChanged(skeletonPaths, atlasPaths); + + // Import skeletons and match them with atlases. + bool abortSkeletonImport = false; + foreach (var skeletonPathEntry in skeletonPaths) { + string skeletonPath = skeletonPathEntry.path; + var compatibilityProblems = skeletonPathEntry.compatibilityProblems; + string otherProblemDescription = skeletonPathEntry.otherProblemDescription; + if (skeletonPath.StartsWith("Packages")) + continue; + if (!reimport && CheckForValidSkeletonData(skeletonPath)) { + ReloadSkeletonData(skeletonPath, compatibilityProblems); + continue; + } + + var loadedAsset = AssetDatabase.LoadAssetAtPath(skeletonPath); + if (compatibilityProblems != null) { + IngestIncompatibleSpineProject(loadedAsset, compatibilityProblems); + continue; + } + if (otherProblemDescription != null) { + continue; + } + + string dir = Path.GetDirectoryName(skeletonPath).Replace('\\', '/'); + +#if SPINE_TK2D + IngestSpineProject(loadedAsset, null); +#else + string skeletonName = Path.GetFileNameWithoutExtension(skeletonPath); + var atlasesForSkeleton = FindAtlasesAtPath(dir); + atlasesForSkeleton = atlasesForSkeleton.Union(newAtlases).ToList(); + var requiredPaths = GetRequiredAtlasRegions(skeletonPath); + atlasesForSkeleton.Sort((a, b) => ( + string.CompareOrdinal(b.name, skeletonName) + - string.CompareOrdinal(a.name, skeletonName))); + var atlasMatch = GetMatchingAtlas(requiredPaths, atlasesForSkeleton); + if (atlasMatch != null || requiredPaths.Count == 0) { + IngestSpineProject(loadedAsset, atlasMatch); + } else { + SkeletonImportDialog(skeletonPath, atlasesForSkeleton, requiredPaths, ref abortSkeletonImport); + } + + if (abortSkeletonImport) + break; +#endif + } + + if (atlasPaths.Count > 0 || imagePaths.Count > 0 || skeletonPaths.Count > 0) { + SkeletonDataAssetInspector[] skeletonDataInspectors = Resources.FindObjectsOfTypeAll(); + foreach (var inspector in skeletonDataInspectors) { + inspector.UpdateSkeletonData(); + } + } + + // Any post processing of images + + // Under some circumstances (e.g. on first import) SkeletonGraphic objects + // have their skeletonGraphic.skeletonDataAsset reference corrupted + // by the instance of the ScriptableObject being destroyed but still assigned. + // Here we restore broken skeletonGraphic.skeletonDataAsset references. + var skeletonGraphicObjects = Resources.FindObjectsOfTypeAll(typeof(SkeletonGraphic)) as SkeletonGraphic[]; + foreach (var skeletonGraphic in skeletonGraphicObjects) { + + if (skeletonGraphic.skeletonDataAsset == null) { + var skeletonGraphicID = skeletonGraphic.GetInstanceID(); + if (SpineEditorUtilities.DataReloadHandler.savedSkeletonDataAssetAtSKeletonGraphicID.ContainsKey(skeletonGraphicID)) { + string assetPath = SpineEditorUtilities.DataReloadHandler.savedSkeletonDataAssetAtSKeletonGraphicID[skeletonGraphicID]; + skeletonGraphic.skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(assetPath); + } + } + } + } + + static void AddDependentSkeletonIfAtlasChanged(List skeletonPaths, List atlasPaths) { + foreach (var atlasPath in atlasPaths) { + string skeletonPathJson = atlasPath.Replace(".atlas.txt", ".json"); + string skeletonPathBinary = atlasPath.Replace(".atlas.txt", ".skel.bytes"); + string usedSkeletonPath = System.IO.File.Exists(skeletonPathJson) ? skeletonPathJson : + System.IO.File.Exists(skeletonPathBinary) ? skeletonPathBinary : null; + if (usedSkeletonPath == null) + continue; + + if (skeletonPaths.FindIndex(p => { return p.path == usedSkeletonPath; } ) < 0) { + string problemDescription = null; + CompatibilityProblemInfo compatibilityProblemInfo = null; + TextAsset textAsset = AssetDatabase.LoadAssetAtPath(usedSkeletonPath); + if (textAsset != null && IsSpineData(textAsset, out compatibilityProblemInfo, ref problemDescription)) + skeletonPaths.Add(new PathAndProblemInfo(usedSkeletonPath, compatibilityProblemInfo, problemDescription)); + } + } + } + + static void ReloadSkeletonData (string skeletonJSONPath, CompatibilityProblemInfo compatibilityProblemInfo) { + string dir = Path.GetDirectoryName(skeletonJSONPath).Replace('\\', '/'); + TextAsset textAsset = AssetDatabase.LoadAssetAtPath(skeletonJSONPath); + DirectoryInfo dirInfo = new DirectoryInfo(dir); + FileInfo[] files = dirInfo.GetFiles("*.asset"); + + foreach (var f in files) { + string localPath = dir + "/" + f.Name; + var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object)); + var skeletonDataAsset = obj as SkeletonDataAsset; + if (skeletonDataAsset != null) { + if (skeletonDataAsset.skeletonJSON == textAsset) { + if (Selection.activeObject == skeletonDataAsset) + Selection.activeObject = null; + + if (compatibilityProblemInfo != null) { + SkeletonDataCompatibility.DisplayCompatibilityProblem(compatibilityProblemInfo.DescriptionString(), textAsset); + return; + } + + Debug.LogFormat("Changes to '{0}' or atlas detected. Clearing SkeletonDataAsset: {1}", skeletonJSONPath, localPath); + skeletonDataAsset.Clear(); + + string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skeletonDataAsset)); + string lastHash = EditorPrefs.GetString(guid + "_hash"); + + // For some weird reason sometimes Unity loses the internal Object pointer, + // and as a result, all comparisons with null returns true. + // But the C# wrapper is still alive, so we can "restore" the object + // by reloading it from its Instance ID. + AtlasAssetBase[] skeletonDataAtlasAssets = skeletonDataAsset.atlasAssets; + if (skeletonDataAtlasAssets != null) { + for (int i = 0; i < skeletonDataAtlasAssets.Length; i++) { + if (!ReferenceEquals(null, skeletonDataAtlasAssets[i]) && + skeletonDataAtlasAssets[i].Equals(null) && + skeletonDataAtlasAssets[i].GetInstanceID() != 0 + ) { + skeletonDataAtlasAssets[i] = EditorUtility.InstanceIDToObject(skeletonDataAtlasAssets[i].GetInstanceID()) as AtlasAssetBase; + } + } + } + + SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(true); + if (skeletonData != null) + BlendModeMaterialsUtility.UpdateBlendModeMaterials(skeletonDataAsset, ref skeletonData); + + string currentHash = skeletonData != null ? skeletonData.Hash : null; + +#if SPINE_SKELETONMECANIM + if (currentHash == null || lastHash != currentHash) + SkeletonBaker.UpdateMecanimClips(skeletonDataAsset); +#endif + + // if (currentHash == null || lastHash != currentHash) + // Do any upkeep on synchronized assets + + if (currentHash != null) + EditorPrefs.SetString(guid + "_hash", currentHash); + } + SpineEditorUtilities.DataReloadHandler.ReloadSceneSkeletonComponents(skeletonDataAsset); + SpineEditorUtilities.DataReloadHandler.ReloadAnimationReferenceAssets(skeletonDataAsset); + } + } + } + +#region Import Atlases + static List FindAtlasesAtPath (string path) { + List arr = new List(); + DirectoryInfo dir = new DirectoryInfo(path); + FileInfo[] assetInfoArr = dir.GetFiles("*.asset"); + + int subLen = Application.dataPath.Length - 6; + foreach (var f in assetInfoArr) { + string assetRelativePath = f.FullName.Substring(subLen, f.FullName.Length - subLen).Replace("\\", "/"); + Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAssetBase)); + if (obj != null) + arr.Add(obj as AtlasAssetBase); + } + + return arr; + } + + static AtlasAssetBase IngestSpineAtlas (TextAsset atlasText, List texturesWithoutMetaFile) { + if (atlasText == null) { + Debug.LogWarning("Atlas source cannot be null!"); + return null; + } + + string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", ""); + string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText)).Replace('\\', '/'); + + string atlasPath = assetPath + "/" + primaryName + AtlasSuffix + ".asset"; + + SpineAtlasAsset atlasAsset = (SpineAtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(SpineAtlasAsset)); + + List vestigialMaterials = new List(); + + if (atlasAsset == null) + atlasAsset = SpineAtlasAsset.CreateInstance(); + else { + foreach (Material m in atlasAsset.materials) + vestigialMaterials.Add(m); + } + + protectFromStackGarbageCollection.Add(atlasAsset); + atlasAsset.atlasFile = atlasText; + + //strip CR + string atlasStr = atlasText.text; + atlasStr = atlasStr.Replace("\r", ""); + + string[] atlasLines = atlasStr.Split('\n'); + List pageFiles = new List(); + for (int i = 0; i < atlasLines.Length - 1; i++) { + if (atlasLines[i].Trim().Length == 0) + pageFiles.Add(atlasLines[i + 1].Trim()); + } + + var populatingMaterials = new List(pageFiles.Count);//atlasAsset.materials = new Material[pageFiles.Count]; + + for (int i = 0; i < pageFiles.Count; i++) { + string texturePath = assetPath + "/" + pageFiles[i]; + Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)); + bool textureIsUninitialized = texturesWithoutMetaFile != null && texturesWithoutMetaFile.Contains(texturePath); + if (SpineEditorUtilities.Preferences.setTextureImporterSettings && textureIsUninitialized) { + if (string.IsNullOrEmpty(SpineEditorUtilities.Preferences.textureSettingsReference)) + SetDefaultTextureSettings(texturePath, atlasAsset); + else + SetReferenceTextureSettings(texturePath, atlasAsset, SpineEditorUtilities.Preferences.textureSettingsReference); + } + + string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]); + + //because this looks silly + if (pageName == primaryName && pageFiles.Count == 1) + pageName = "Material"; + + string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat"; + Material mat = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)); + + if (mat == null) { + mat = new Material(Shader.Find(SpineEditorUtilities.Preferences.defaultShader)); + ApplyPMAOrStraightAlphaSettings(mat, SpineEditorUtilities.Preferences.textureSettingsReference); + AssetDatabase.CreateAsset(mat, materialPath); + } else { + vestigialMaterials.Remove(mat); + } + + if (texture != null) + mat.mainTexture = texture; + + EditorUtility.SetDirty(mat); + // note: don't call AssetDatabase.SaveAssets() since this would trigger OnPostprocessAllAssets() every time unnecessarily. + populatingMaterials.Add(mat); //atlasAsset.materials[i] = mat; + } + + atlasAsset.materials = populatingMaterials.ToArray(); + + for (int i = 0; i < vestigialMaterials.Count; i++) + AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i])); + + if (AssetDatabase.GetAssetPath(atlasAsset) == "") + AssetDatabase.CreateAsset(atlasAsset, atlasPath); + else + atlasAsset.Clear(); + + EditorUtility.SetDirty(atlasAsset); + AssetDatabase.SaveAssets(); + + if (pageFiles.Count != atlasAsset.materials.Length) + Debug.LogWarning(string.Format("{0} :: Not all atlas pages were imported. If you rename your image files, please make sure you also edit the filenames specified in the atlas file.", atlasAsset.name), atlasAsset); + else + Debug.Log(string.Format("{0} :: Imported with {1} material", atlasAsset.name, atlasAsset.materials.Length), atlasAsset); + + // Iterate regions and bake marked. + Atlas atlas = atlasAsset.GetAtlas(); + if (atlas != null) { + FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic); + var regions = (List)field.GetValue(atlas); + string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset); + string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath).Replace('\\', '/'); + string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name); + + bool hasBakedRegions = false; + for (int i = 0; i < regions.Count; i++) { + AtlasRegion region = regions[i]; + string bakedPrefabPath = Path.Combine(bakedDirPath, AssetUtility.GetPathSafeName(region.name) + ".prefab").Replace("\\", "/"); + GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject)); + if (prefab != null) { + SkeletonBaker.BakeRegion(atlasAsset, region, false); + hasBakedRegions = true; + } + } + + if (hasBakedRegions) { + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + } + } + + protectFromStackGarbageCollection.Remove(atlasAsset); + // note: at Asset Pipeline V2 this LoadAssetAtPath of the just created + // asset returns null, regardless of refresh calls. + var loadedAtlas = (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAssetBase)); + return loadedAtlas != null ? loadedAtlas : atlasAsset; + } + + public static bool SpriteAtlasSettingsNeedAdjustment (UnityEngine.U2D.SpriteAtlas spriteAtlas) { + #if EXPOSES_SPRITE_ATLAS_UTILITIES + UnityEditor.U2D.SpriteAtlasPackingSettings packingSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetPackingSettings(spriteAtlas); + UnityEditor.U2D.SpriteAtlasTextureSettings textureSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetTextureSettings(spriteAtlas); + + bool areSettingsAsDesired = + packingSettings.enableRotation == true && + packingSettings.enableTightPacking == false && + textureSettings.readable == true && + textureSettings.generateMipMaps == false; + // note: platformSettings.textureCompression is always providing "Compressed", so we have to skip it. + return !areSettingsAsDesired; + #else + return false; + #endif + } + + public static bool AdjustSpriteAtlasSettings (UnityEngine.U2D.SpriteAtlas spriteAtlas) { + #if EXPOSES_SPRITE_ATLAS_UTILITIES + UnityEditor.U2D.SpriteAtlasPackingSettings packingSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetPackingSettings(spriteAtlas); + UnityEditor.U2D.SpriteAtlasTextureSettings textureSettings = UnityEditor.U2D.SpriteAtlasExtensions.GetTextureSettings(spriteAtlas); + + packingSettings.enableRotation = true; + packingSettings.enableTightPacking = false; + UnityEditor.U2D.SpriteAtlasExtensions.SetPackingSettings(spriteAtlas, packingSettings); + + textureSettings.readable = true; + textureSettings.generateMipMaps = false; + UnityEditor.U2D.SpriteAtlasExtensions.SetTextureSettings(spriteAtlas, textureSettings); + + TextureImporterPlatformSettings platformSettings = new TextureImporterPlatformSettings(); + platformSettings.textureCompression = TextureImporterCompression.Uncompressed; + platformSettings.crunchedCompression = false; + UnityEditor.U2D.SpriteAtlasExtensions.SetPlatformSettings(spriteAtlas, platformSettings); + + string atlasPath = AssetDatabase.GetAssetPath(spriteAtlas); + Debug.Log(string.Format("Adjusted unsuitable SpriteAtlas settings '{0}'", atlasPath), spriteAtlas); + return false; + #else + return true; + #endif + } + + public static bool GeneratePngFromSpriteAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlas, out string texturePath) { + texturePath = System.IO.Path.ChangeExtension(AssetDatabase.GetAssetPath(spriteAtlas), ".png"); + if (spriteAtlas == null) + return false; + + Texture2D tempTexture = SpineSpriteAtlasAsset.AccessPackedTextureEditor(spriteAtlas); + if (tempTexture == null) + return false; + + byte[] bytes = null; + try { + bytes = tempTexture.EncodeToPNG(); + } + catch (System.Exception) { + // handled below + } + if (bytes == null || bytes.Length == 0) { + Debug.LogError("Could not read Compressed SpriteAtlas. Please enable 'Read/Write Enabled' and ensure 'Compression' is set to 'None' in Inspector.", spriteAtlas); + return false; + } + System.IO.File.WriteAllBytes(texturePath, bytes); + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + return System.IO.File.Exists(texturePath); + } + + public static AtlasAssetBase IngestSpriteAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlas, List texturesWithoutMetaFile) { + if (spriteAtlas == null) { + Debug.LogWarning("SpriteAtlas source cannot be null!"); + return null; + } + + if (SpriteAtlasSettingsNeedAdjustment(spriteAtlas)) { + // settings need to be adjusted via the 'Spine SpriteAtlas Import' window if you want to use it as a Spine atlas. + return null; + } + + Texture2D texture = null; + { // only one page file + string texturePath; + GeneratePngFromSpriteAtlas(spriteAtlas, out texturePath); + texture = AssetDatabase.LoadAssetAtPath(texturePath); + if (texture == null && System.IO.File.Exists(texturePath)) { + EditorUtility.SetDirty(spriteAtlas); + return null; // next iteration will load the texture as well. + } + } + + string primaryName = spriteAtlas.name; + string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spriteAtlas)).Replace('\\', '/'); + + string atlasPath = assetPath + "/" + primaryName + SpriteAtlasSuffix + ".asset"; + + SpineSpriteAtlasAsset atlasAsset = AssetDatabase.LoadAssetAtPath(atlasPath); + + List vestigialMaterials = new List(); + + if (atlasAsset == null) + atlasAsset = SpineSpriteAtlasAsset.CreateInstance(); + else { + foreach (Material m in atlasAsset.materials) + vestigialMaterials.Add(m); + } + + protectFromStackGarbageCollection.Add(atlasAsset); + atlasAsset.spriteAtlasFile = spriteAtlas; + + int pagesCount = 1; + var populatingMaterials = new List(pagesCount); + + { + string pageName = "SpriteAtlas"; + + string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat"; + Material mat = AssetDatabase.LoadAssetAtPath(materialPath); + + if (mat == null) { + mat = new Material(Shader.Find(SpineEditorUtilities.Preferences.defaultShader)); + ApplyPMAOrStraightAlphaSettings(mat, SpineEditorUtilities.Preferences.textureSettingsReference); + AssetDatabase.CreateAsset(mat, materialPath); + } + else { + vestigialMaterials.Remove(mat); + } + + if (texture != null) + mat.mainTexture = texture; + + EditorUtility.SetDirty(mat); + // note: don't call AssetDatabase.SaveAssets() since this would trigger OnPostprocessAllAssets() every time unnecessarily. + populatingMaterials.Add(mat); //atlasAsset.materials[i] = mat; + } + + atlasAsset.materials = populatingMaterials.ToArray(); + + for (int i = 0; i < vestigialMaterials.Count; i++) + AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i])); + + if (AssetDatabase.GetAssetPath(atlasAsset) == "") + AssetDatabase.CreateAsset(atlasAsset, atlasPath); + else + atlasAsset.Clear(); + + atlasAsset.GetAtlas(); + atlasAsset.updateRegionsInPlayMode = true; + + EditorUtility.SetDirty(atlasAsset); + AssetDatabase.SaveAssets(); + + Debug.Log(string.Format("{0} :: Imported with {1} material", atlasAsset.name, atlasAsset.materials.Length), atlasAsset); + + protectFromStackGarbageCollection.Remove(atlasAsset); + return (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAssetBase)); + } + + static bool SetDefaultTextureSettings (string texturePath, SpineAtlasAsset atlasAsset) { + TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath); + if (texImporter == null) { + Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset); + return false; + } + + texImporter.textureCompression = TextureImporterCompression.Uncompressed; + texImporter.alphaSource = TextureImporterAlphaSource.FromInput; + texImporter.mipmapEnabled = false; + texImporter.alphaIsTransparency = false; // Prevent the texture importer from applying bleed to the transparent parts for PMA. + texImporter.spriteImportMode = SpriteImportMode.None; + texImporter.maxTextureSize = 2048; + + EditorUtility.SetDirty(texImporter); + AssetDatabase.ImportAsset(texturePath); + AssetDatabase.SaveAssets(); + return true; + } + +#if NEW_PREFERENCES_SETTINGS_PROVIDER + static bool SetReferenceTextureSettings (string texturePath, SpineAtlasAsset atlasAsset, string referenceAssetPath) { + var texturePreset = AssetDatabase.LoadAssetAtPath(referenceAssetPath); + bool isTexturePreset = texturePreset != null && texturePreset.GetTargetTypeName() == "TextureImporter"; + if (!isTexturePreset) + return SetDefaultTextureSettings(texturePath, atlasAsset); + + TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath); + if (texImporter == null) { + Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset); + return false; + } + + texturePreset.ApplyTo(texImporter); + AssetDatabase.ImportAsset(texturePath); + AssetDatabase.SaveAssets(); + return true; + } +#else + static bool SetReferenceTextureSettings (string texturePath, SpineAtlasAsset atlasAsset, string referenceAssetPath) { + TextureImporter reference = TextureImporter.GetAtPath(referenceAssetPath) as TextureImporter; + if (reference == null) + return SetDefaultTextureSettings(texturePath, atlasAsset); + + TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath); + if (texImporter == null) { + Debug.LogWarning(string.Format("{0}: Texture asset \"{1}\" not found. Skipping. Please check your atlas file for renamed files.", atlasAsset.name, texturePath), atlasAsset); + return false; + } + + texImporter.sRGBTexture = reference.sRGBTexture; + texImporter.textureCompression = reference.textureCompression; + texImporter.alphaSource = reference.alphaSource; + texImporter.mipmapEnabled = reference.mipmapEnabled; + texImporter.alphaIsTransparency = reference.alphaIsTransparency; + texImporter.spriteImportMode = reference.spriteImportMode; + texImporter.maxTextureSize = reference.maxTextureSize; + texImporter.isReadable = reference.isReadable; + texImporter.filterMode = reference.filterMode; + texImporter.mipmapFilter = reference.mipmapFilter; + texImporter.textureType = reference.textureType; + + EditorUtility.SetDirty(texImporter); + AssetDatabase.ImportAsset(texturePath); + AssetDatabase.SaveAssets(); + return true; + } +#endif + + static void ApplyPMAOrStraightAlphaSettings (Material material, string referenceTextureSettings) { + bool isUsingPMAWorkflow = string.IsNullOrEmpty(referenceTextureSettings) || + (!referenceTextureSettings.ToLower().Contains("straight") && referenceTextureSettings.ToLower().Contains("pma")); + + MaterialChecks.EnablePMAAtMaterial(material, isUsingPMAWorkflow); + } +#endregion + +#region Import SkeletonData (json or binary) + internal static string GetSkeletonDataAssetFilePath(TextAsset spineJson) { + string primaryName = Path.GetFileNameWithoutExtension(spineJson.name); + string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spineJson)).Replace('\\', '/'); + return assetPath + "/" + primaryName + SkeletonDataSuffix + ".asset"; + } + + internal static SkeletonDataAsset IngestIncompatibleSpineProject(TextAsset spineJson, + CompatibilityProblemInfo compatibilityProblemInfo) { + + if (spineJson == null) + return null; + + string filePath = GetSkeletonDataAssetFilePath(spineJson); + SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset)); + if (skeletonDataAsset == null) { + skeletonDataAsset = SkeletonDataAsset.CreateInstance(); + skeletonDataAsset.skeletonJSON = spineJson; + AssetDatabase.CreateAsset(skeletonDataAsset, filePath); + } + EditorUtility.SetDirty(skeletonDataAsset); + + SkeletonDataCompatibility.DisplayCompatibilityProblem(compatibilityProblemInfo.DescriptionString(), spineJson); + return skeletonDataAsset; + } + + internal static SkeletonDataAsset IngestSpineProject (TextAsset spineJson, params AtlasAssetBase[] atlasAssets) { + string filePath = GetSkeletonDataAssetFilePath(spineJson); + +#if SPINE_TK2D + if (spineJson != null) { + SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset)); + if (skeletonDataAsset == null) { + skeletonDataAsset = SkeletonDataAsset.CreateInstance(); + skeletonDataAsset.skeletonJSON = spineJson; + skeletonDataAsset.fromAnimation = new string[0]; + skeletonDataAsset.toAnimation = new string[0]; + skeletonDataAsset.duration = new float[0]; + skeletonDataAsset.defaultMix = SpineEditorUtilities.Preferences.defaultMix; + skeletonDataAsset.scale = SpineEditorUtilities.Preferences.defaultScale; + + AssetDatabase.CreateAsset(skeletonDataAsset, filePath); + AssetDatabase.SaveAssets(); + } else { + skeletonDataAsset.Clear(); + skeletonDataAsset.GetSkeletonData(true); + } + + return skeletonDataAsset; + } else { + EditorUtility.DisplayDialog("Error!", "Tried to ingest null Spine data.", "OK"); + return null; + } + +#else + if (spineJson != null && atlasAssets != null) { + SkeletonDataAsset skeletonDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset)); + if (skeletonDataAsset == null) { + skeletonDataAsset = ScriptableObject.CreateInstance(); + { + skeletonDataAsset.atlasAssets = atlasAssets; + skeletonDataAsset.skeletonJSON = spineJson; + skeletonDataAsset.defaultMix = SpineEditorUtilities.Preferences.defaultMix; + skeletonDataAsset.scale = SpineEditorUtilities.Preferences.defaultScale; + skeletonDataAsset.blendModeMaterials.applyAdditiveMaterial = !SpineEditorUtilities.Preferences.UsesPMAWorkflow; + } + AssetDatabase.CreateAsset(skeletonDataAsset, filePath); + } else { + skeletonDataAsset.atlasAssets = atlasAssets; + skeletonDataAsset.Clear(); + } + var skeletonData = skeletonDataAsset.GetSkeletonData(true); + BlendModeMaterialsUtility.UpdateBlendModeMaterials(skeletonDataAsset, ref skeletonData); + AssetDatabase.SaveAssets(); + + return skeletonDataAsset; + } else { + EditorUtility.DisplayDialog("Error!", "Must specify both Spine JSON and AtlasAsset array", "OK"); + return null; + } +#endif + } +#endregion + +#region Spine Skeleton Data File Validation + public static bool CheckForValidSkeletonData (string skeletonJSONPath) { + string dir = Path.GetDirectoryName(skeletonJSONPath).Replace('\\', '/'); + TextAsset textAsset = AssetDatabase.LoadAssetAtPath(skeletonJSONPath); + DirectoryInfo dirInfo = new DirectoryInfo(dir); + FileInfo[] files = dirInfo.GetFiles("*.asset"); + + foreach (var path in files) { + string localPath = dir + "/" + path.Name; + var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object)); + var skeletonDataAsset = obj as SkeletonDataAsset; + if (skeletonDataAsset != null && skeletonDataAsset.skeletonJSON == textAsset) + return true; + } + return false; + } + + public static bool IsSpineData (TextAsset asset, out CompatibilityProblemInfo compatibilityProblemInfo, ref string problemDescription) { + bool isSpineSkeletonData; + SkeletonDataCompatibility.VersionInfo fileVersion = SkeletonDataCompatibility.GetVersionInfo(asset, out isSpineSkeletonData, ref problemDescription); + compatibilityProblemInfo = SkeletonDataCompatibility.GetCompatibilityProblemInfo(fileVersion); + return isSpineSkeletonData; + } +#endregion + +#region Dialogs + public static void SkeletonImportDialog (string skeletonPath, List localAtlases, List requiredPaths, ref bool abortSkeletonImport) { + bool resolved = false; + while (!resolved) { + + string filename = Path.GetFileNameWithoutExtension(skeletonPath); + int result = EditorUtility.DisplayDialogComplex( + string.Format("AtlasAsset for \"{0}\"", filename), + string.Format("Could not automatically set the AtlasAsset for \"{0}\".\n\n (You may resolve this manually later.)", filename), + "Resolve atlases...", "Import without atlases", "Stop importing" + ); + + switch (result) { + case -1: + //Debug.Log("Select Atlas"); + AtlasAssetBase selectedAtlas = BrowseAtlasDialog(Path.GetDirectoryName(skeletonPath).Replace('\\', '/')); + if (selectedAtlas != null) { + localAtlases.Clear(); + localAtlases.Add(selectedAtlas); + var atlasMatch = AssetUtility.GetMatchingAtlas(requiredPaths, localAtlases); + if (atlasMatch != null) { + resolved = true; + AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath), atlasMatch); + } + } + break; + case 0: // Resolve AtlasAssets... + var atlasList = MultiAtlasDialog(requiredPaths, Path.GetDirectoryName(skeletonPath).Replace('\\', '/'), + Path.GetFileNameWithoutExtension(skeletonPath)); + if (atlasList != null) + AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath), atlasList.ToArray()); + + resolved = true; + break; + case 1: // Import without atlas + Debug.LogWarning("Imported with missing atlases. Skeleton will not render: " + Path.GetFileName(skeletonPath)); + AssetUtility.IngestSpineProject(AssetDatabase.LoadAssetAtPath(skeletonPath), new AtlasAssetBase[] { }); + resolved = true; + break; + case 2: // Stop importing all + abortSkeletonImport = true; + resolved = true; + break; + } + } + } + + public static List MultiAtlasDialog (List requiredPaths, string initialDirectory, string filename = "") { + List atlasAssets = new List(); + bool resolved = false; + string lastAtlasPath = initialDirectory; + while (!resolved) { + + // Build dialog box message. + var missingRegions = new List(requiredPaths); + var dialogText = new StringBuilder(); + { + dialogText.AppendLine(string.Format("SkeletonDataAsset for \"{0}\"", filename)); + dialogText.AppendLine("has missing regions."); + dialogText.AppendLine(); + dialogText.AppendLine("Current Atlases:"); + + if (atlasAssets.Count == 0) + dialogText.AppendLine("\t--none--"); + + for (int i = 0; i < atlasAssets.Count; i++) + dialogText.AppendLine("\t" + atlasAssets[i].name); + + dialogText.AppendLine(); + dialogText.AppendLine("Missing Regions:"); + + foreach (var atlasAsset in atlasAssets) { + var atlas = atlasAsset.GetAtlas(); + for (int i = 0; i < missingRegions.Count; i++) { + if (atlas.FindRegion(missingRegions[i]) != null) { + missingRegions.RemoveAt(i); + i--; + } + } + } + + int n = missingRegions.Count; + if (n == 0) + break; + + const int MaxListLength = 15; + for (int i = 0; (i < n && i < MaxListLength); i++) + dialogText.AppendLine(string.Format("\t {0}", missingRegions[i])); + + if (n > MaxListLength) + dialogText.AppendLine(string.Format("\t... {0} more...", n - MaxListLength)); + } + + // Show dialog box. + int result = EditorUtility.DisplayDialogComplex( + "SkeletonDataAsset has missing Atlas.", + dialogText.ToString(), + "Browse Atlas...", "Import anyway", "Cancel import" + ); + + switch (result) { + case 0: // Browse... + AtlasAssetBase selectedAtlasAsset = BrowseAtlasDialog(lastAtlasPath); + if (selectedAtlasAsset != null) { + if (!atlasAssets.Contains(selectedAtlasAsset)) { + var atlas = selectedAtlasAsset.GetAtlas(); + bool hasValidRegion = false; + foreach (string str in missingRegions) { + if (atlas.FindRegion(str) != null) { + hasValidRegion = true; + break; + } + } + atlasAssets.Add(selectedAtlasAsset); + } + } + break; + case 1: // Import anyway + resolved = true; + break; + case 2: // Cancel + atlasAssets = null; + resolved = true; + break; + } + } + + return atlasAssets; + } + + public static AtlasAssetBase BrowseAtlasDialog (string dirPath) { + string path = EditorUtility.OpenFilePanel("Select AtlasAsset...", dirPath, "asset"); + if (path == "") + return null; // Canceled or closed by user. + + int subLen = Application.dataPath.Length - 6; + string assetRelativePath = path.Substring(subLen, path.Length - subLen).Replace("\\", "/"); + + var obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAssetBase)); + if (obj == null || !(obj is AtlasAssetBase)) { + Debug.Log("Chosen asset was not of type AtlasAssetBase"); + return null; + } + + return (AtlasAssetBase)obj; + } +#endregion + + public static string GetPathSafeName (string name) { + foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { // Doesn't handle more obscure file name limitations. + name = name.Replace(c, '_'); + } + return name; + } + } + + public static class EditorInstantiation { + public delegate Component InstantiateDelegate (SkeletonDataAsset skeletonDataAsset); + + public class SkeletonComponentSpawnType { + public string menuLabel; + public InstantiateDelegate instantiateDelegate; + public bool isUI; + } + + internal static readonly List additionalSpawnTypes = new List(); + + public static void TryInitializeSkeletonRendererSettings (SkeletonRenderer skeletonRenderer, Skin skin = null) { + const string PMAShaderQuery = "Spine/Skeleton"; + const string TintBlackShaderQuery = "Tint Black"; + + if (skeletonRenderer == null) return; + var skeletonDataAsset = skeletonRenderer.skeletonDataAsset; + if (skeletonDataAsset == null) return; + + bool pmaVertexColors = false; + bool tintBlack = false; + foreach (AtlasAssetBase atlasAsset in skeletonDataAsset.atlasAssets) { + if (!pmaVertexColors) { + foreach (Material m in atlasAsset.Materials) { + if (m.shader.name.Contains(PMAShaderQuery)) { + pmaVertexColors = true; + break; + } + } + } + + if (!tintBlack) { + foreach (Material m in atlasAsset.Materials) { + if (m.shader.name.Contains(TintBlackShaderQuery)) { + tintBlack = true; + break; + } + } + } + } + + skeletonRenderer.pmaVertexColors = pmaVertexColors; + skeletonRenderer.tintBlack = tintBlack; + skeletonRenderer.zSpacing = SpineEditorUtilities.Preferences.defaultZSpacing; + + var data = skeletonDataAsset.GetSkeletonData(false); + bool noSkins = data.DefaultSkin == null && (data.Skins == null || data.Skins.Count == 0); // Support attachmentless/skinless SkeletonData. + skin = skin ?? data.DefaultSkin ?? (noSkins ? null : data.Skins.Items[0]); + if (skin != null && skin != data.DefaultSkin) { + skeletonRenderer.initialSkinName = skin.Name; + } + } + + public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, string skinName, + bool destroyInvalid = true, bool useObjectFactory = true) { + + var skeletonData = skeletonDataAsset.GetSkeletonData(true); + var skin = skeletonData != null ? skeletonData.FindSkin(skinName) : null; + return InstantiateSkeletonAnimation(skeletonDataAsset, skin, destroyInvalid, useObjectFactory); + } + + public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, Skin skin = null, + bool destroyInvalid = true, bool useObjectFactory = true) { + + SkeletonData data = skeletonDataAsset.GetSkeletonData(true); + + if (data == null) { + for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) { + string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]); + skeletonDataAsset.atlasAssets[i] = (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAssetBase)); + } + data = skeletonDataAsset.GetSkeletonData(false); + } + + if (data == null) { + Debug.LogWarning("InstantiateSkeletonAnimation tried to instantiate a skeleton from an invalid SkeletonDataAsset.", skeletonDataAsset); + return null; + } + + string spineGameObjectName = string.Format("Spine GameObject ({0})", skeletonDataAsset.name.Replace(AssetUtility.SkeletonDataSuffix, "")); + GameObject go = EditorInstantiation.NewGameObject(spineGameObjectName, useObjectFactory, + typeof(MeshFilter), typeof(MeshRenderer), typeof(SkeletonAnimation)); + SkeletonAnimation newSkeletonAnimation = go.GetComponent(); + newSkeletonAnimation.skeletonDataAsset = skeletonDataAsset; + TryInitializeSkeletonRendererSettings(newSkeletonAnimation, skin); + + // Initialize + try { + newSkeletonAnimation.Initialize(false); + } catch (System.Exception e) { + if (destroyInvalid) { + Debug.LogWarning("Editor-instantiated SkeletonAnimation threw an Exception. Destroying GameObject to prevent orphaned GameObject.\n" + e.Message, skeletonDataAsset); + GameObject.DestroyImmediate(go); + } + throw e; + } + + newSkeletonAnimation.loop = SpineEditorUtilities.Preferences.defaultInstantiateLoop; + newSkeletonAnimation.skeleton.Update(0); + newSkeletonAnimation.state.Update(0); + newSkeletonAnimation.state.Apply(newSkeletonAnimation.skeleton); + newSkeletonAnimation.skeleton.UpdateWorldTransform(); + + return newSkeletonAnimation; + } + + /// Handles creating a new GameObject in the Unity Editor. This uses the new ObjectFactory API where applicable. + public static GameObject NewGameObject (string name, bool useObjectFactory) { +#if NEW_PREFAB_SYSTEM + if (useObjectFactory) + return ObjectFactory.CreateGameObject(name); +#endif + return new GameObject(name); + } + + /// Handles creating a new GameObject in the Unity Editor. This uses the new ObjectFactory API where applicable. + public static GameObject NewGameObject (string name, bool useObjectFactory, params System.Type[] components) { +#if NEW_PREFAB_SYSTEM + if (useObjectFactory) + return ObjectFactory.CreateGameObject(name, components); +#endif + return new GameObject(name, components); + } + + public static void InstantiateEmptySpineGameObject (string name, bool useObjectFactory) where T : MonoBehaviour { + var parentGameObject = Selection.activeObject as GameObject; + var parentTransform = parentGameObject == null ? null : parentGameObject.transform; + + var gameObject = EditorInstantiation.NewGameObject(name, useObjectFactory, typeof(T)); + gameObject.transform.SetParent(parentTransform, false); + EditorUtility.FocusProjectWindow(); + Selection.activeObject = gameObject; + EditorGUIUtility.PingObject(Selection.activeObject); + } + +#region SkeletonMecanim +#if SPINE_SKELETONMECANIM + public static SkeletonMecanim InstantiateSkeletonMecanim (SkeletonDataAsset skeletonDataAsset, string skinName) { + return InstantiateSkeletonMecanim(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName)); + } + + public static SkeletonMecanim InstantiateSkeletonMecanim (SkeletonDataAsset skeletonDataAsset, Skin skin = null, + bool destroyInvalid = true, bool useObjectFactory = true) { + SkeletonData data = skeletonDataAsset.GetSkeletonData(true); + + if (data == null) { + for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) { + string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]); + skeletonDataAsset.atlasAssets[i] = (AtlasAssetBase)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAssetBase)); + } + data = skeletonDataAsset.GetSkeletonData(false); + } + + if (data == null) { + Debug.LogWarning("InstantiateSkeletonMecanim tried to instantiate a skeleton from an invalid SkeletonDataAsset.", skeletonDataAsset); + return null; + } + + string spineGameObjectName = string.Format("Spine Mecanim GameObject ({0})", skeletonDataAsset.name.Replace(AssetUtility.SkeletonDataSuffix, "")); + GameObject go = EditorInstantiation.NewGameObject(spineGameObjectName, useObjectFactory, + typeof(MeshFilter), typeof(MeshRenderer), typeof(Animator), typeof(SkeletonMecanim)); + + if (skeletonDataAsset.controller == null) { + SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset); + Debug.Log(string.Format("Mecanim controller was automatically generated and assigned for {0}", skeletonDataAsset.name), skeletonDataAsset); + } + + go.GetComponent().runtimeAnimatorController = skeletonDataAsset.controller; + + SkeletonMecanim newSkeletonMecanim = go.GetComponent(); + newSkeletonMecanim.skeletonDataAsset = skeletonDataAsset; + TryInitializeSkeletonRendererSettings(newSkeletonMecanim, skin); + + // Initialize + try { + newSkeletonMecanim.Initialize(false); + } catch (System.Exception e) { + if (destroyInvalid) { + Debug.LogWarning("Editor-instantiated SkeletonAnimation threw an Exception. Destroying GameObject to prevent orphaned GameObject.", skeletonDataAsset); + GameObject.DestroyImmediate(go); + } + throw e; + } + + newSkeletonMecanim.skeleton.Update(0); + newSkeletonMecanim.skeleton.UpdateWorldTransform(); + newSkeletonMecanim.LateUpdate(); + + return newSkeletonMecanim; + } +#endif +#endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs.meta new file mode 100644 index 0000000..2f6480e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/AssetUtility.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 49377c72c37e2c149b106c260a241f3c +timeCreated: 1563311043 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs new file mode 100644 index 0000000..91baf3c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs @@ -0,0 +1,282 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2020_1_OR_NEWER +#define UPGRADE_ALL_BLEND_MODE_MATERIALS +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System; + +namespace Spine.Unity.Editor { + + public class BlendModeMaterialsUtility { + + public const string MATERIAL_SUFFIX_MULTIPLY = "-Multiply"; + public const string MATERIAL_SUFFIX_SCREEN = "-Screen"; + public const string MATERIAL_SUFFIX_ADDITIVE = "-Additive"; + +#if UPGRADE_ALL_BLEND_MODE_MATERIALS + public const bool ShallUpgradeBlendModeMaterials = true; +#else + public const bool ShallUpgradeBlendModeMaterials = false; +#endif + + protected class TemplateMaterials { + public Material multiplyTemplate; + public Material screenTemplate; + public Material additiveTemplate; + }; + + public static void UpgradeBlendModeMaterials (SkeletonDataAsset skeletonDataAsset) { + var skeletonData = skeletonDataAsset.GetSkeletonData(true); + if (skeletonData == null) + return; + UpdateBlendModeMaterials(skeletonDataAsset, ref skeletonData, true); + } + + public static void UpdateBlendModeMaterials (SkeletonDataAsset skeletonDataAsset) { + var skeletonData = skeletonDataAsset.GetSkeletonData(true); + if (skeletonData == null) + return; + UpdateBlendModeMaterials(skeletonDataAsset, ref skeletonData, false); + } + + public static void UpdateBlendModeMaterials (SkeletonDataAsset skeletonDataAsset, ref SkeletonData skeletonData, + bool upgradeFromModifierAssets = ShallUpgradeBlendModeMaterials) { + + TemplateMaterials templateMaterials = new TemplateMaterials(); + bool anyMaterialsChanged = ClearUndesiredMaterialEntries(skeletonDataAsset); + + var blendModesModifierAsset = FindBlendModeMaterialsModifierAsset(skeletonDataAsset); + if (blendModesModifierAsset) { + if (upgradeFromModifierAssets) { + TransferSettingsFromModifierAsset(blendModesModifierAsset, + skeletonDataAsset, templateMaterials); + UpdateBlendmodeMaterialsRequiredState(skeletonDataAsset, skeletonData); + } + else + return; + } + else { + if (!UpdateBlendmodeMaterialsRequiredState(skeletonDataAsset, skeletonData)) + return; + AssignPreferencesTemplateMaterials(templateMaterials); + } + bool success = CreateAndAssignMaterials(skeletonDataAsset, templateMaterials, ref anyMaterialsChanged); + if (success) { + if (blendModesModifierAsset != null) { + RemoveObsoleteModifierAsset(blendModesModifierAsset, skeletonDataAsset); + } + } + + skeletonDataAsset.Clear(); + skeletonData = skeletonDataAsset.GetSkeletonData(true); + if (anyMaterialsChanged) + ReloadSceneSkeletons(skeletonDataAsset); + AssetDatabase.SaveAssets(); + } + + protected static bool ClearUndesiredMaterialEntries (SkeletonDataAsset skeletonDataAsset) { + Predicate ifMaterialMissing = r => r.material == null; + + bool anyMaterialsChanged = false; + if (!skeletonDataAsset.blendModeMaterials.applyAdditiveMaterial) { + anyMaterialsChanged |= skeletonDataAsset.blendModeMaterials.additiveMaterials.Count > 0; + skeletonDataAsset.blendModeMaterials.additiveMaterials.Clear(); + } + else + anyMaterialsChanged |= skeletonDataAsset.blendModeMaterials.additiveMaterials.RemoveAll(ifMaterialMissing) != 0; + anyMaterialsChanged |= skeletonDataAsset.blendModeMaterials.multiplyMaterials.RemoveAll(ifMaterialMissing) != 0; + anyMaterialsChanged |= skeletonDataAsset.blendModeMaterials.screenMaterials.RemoveAll(ifMaterialMissing) != 0; + return anyMaterialsChanged; + } + + protected static BlendModeMaterialsAsset FindBlendModeMaterialsModifierAsset (SkeletonDataAsset skeletonDataAsset) { + foreach (var modifierAsset in skeletonDataAsset.skeletonDataModifiers) { + if (modifierAsset is BlendModeMaterialsAsset) + return (BlendModeMaterialsAsset)modifierAsset; + } + return null; + } + + protected static bool UpdateBlendmodeMaterialsRequiredState (SkeletonDataAsset skeletonDataAsset, SkeletonData skeletonData) { + return skeletonDataAsset.blendModeMaterials.UpdateBlendmodeMaterialsRequiredState(skeletonData); + } + + protected static void TransferSettingsFromModifierAsset (BlendModeMaterialsAsset modifierAsset, + SkeletonDataAsset skeletonDataAsset, TemplateMaterials templateMaterials) { + + skeletonDataAsset.blendModeMaterials.TransferSettingsFrom(modifierAsset); + + templateMaterials.multiplyTemplate = modifierAsset.multiplyMaterialTemplate; + templateMaterials.screenTemplate = modifierAsset.screenMaterialTemplate; + templateMaterials.additiveTemplate = modifierAsset.additiveMaterialTemplate; + } + + protected static void RemoveObsoleteModifierAsset (BlendModeMaterialsAsset modifierAsset, + SkeletonDataAsset skeletonDataAsset) { + + skeletonDataAsset.skeletonDataModifiers.Remove(modifierAsset); + Debug.Log(string.Format("BlendModeMaterialsAsset upgraded to built-in BlendModeMaterials at SkeletonDataAsset '{0}'.", + skeletonDataAsset.name), skeletonDataAsset); + EditorUtility.SetDirty(skeletonDataAsset); + } + + protected static void AssignPreferencesTemplateMaterials (TemplateMaterials templateMaterials) { + + templateMaterials.multiplyTemplate = SpineEditorUtilities.Preferences.BlendModeMaterialMultiply; + templateMaterials.screenTemplate = SpineEditorUtilities.Preferences.BlendModeMaterialScreen; + templateMaterials.additiveTemplate = SpineEditorUtilities.Preferences.BlendModeMaterialAdditive; + } + + protected static bool CreateAndAssignMaterials (SkeletonDataAsset skeletonDataAsset, + TemplateMaterials templateMaterials, ref bool anyReplacementMaterialsChanged) { + + bool anyCreationFailed = false; + var blendModeMaterials = skeletonDataAsset.blendModeMaterials; + bool applyAdditiveMaterial = blendModeMaterials.applyAdditiveMaterial; + + var skinEntries = new List(); + + skeletonDataAsset.Clear(); + skeletonDataAsset.isUpgradingBlendModeMaterials = true; + SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(true); + + var slotsItems = skeletonData.Slots.Items; + for (int slotIndex = 0, slotCount = skeletonData.Slots.Count; slotIndex < slotCount; slotIndex++) { + var slot = slotsItems[slotIndex]; + if (slot.BlendMode == BlendMode.Normal) continue; + if (!applyAdditiveMaterial && slot.BlendMode == BlendMode.Additive) continue; + + List replacementMaterials = null; + Material materialTemplate = null; + string materialSuffix = null; + switch (slot.BlendMode) { + case BlendMode.Multiply: + replacementMaterials = blendModeMaterials.multiplyMaterials; + materialTemplate = templateMaterials.multiplyTemplate; + materialSuffix = MATERIAL_SUFFIX_MULTIPLY; + break; + case BlendMode.Screen: + replacementMaterials = blendModeMaterials.screenMaterials; + materialTemplate = templateMaterials.screenTemplate; + materialSuffix = MATERIAL_SUFFIX_SCREEN; + break; + case BlendMode.Additive: + replacementMaterials = blendModeMaterials.additiveMaterials; + materialTemplate = templateMaterials.additiveTemplate; + materialSuffix = MATERIAL_SUFFIX_ADDITIVE; + break; + } + + skinEntries.Clear(); + foreach (var skin in skeletonData.Skins) + skin.GetAttachments(slotIndex, skinEntries); + + foreach (var entry in skinEntries) { + var renderableAttachment = entry.Attachment as IHasRendererObject; + if (renderableAttachment != null) { + var originalRegion = (AtlasRegion)renderableAttachment.RendererObject; + bool replacementExists = replacementMaterials.Exists( + replacement => replacement.pageName == originalRegion.page.name); + if (!replacementExists) { + bool createdNewMaterial; + var replacement = CreateOrLoadReplacementMaterial(originalRegion, materialTemplate, materialSuffix, out createdNewMaterial); + if (replacement != null) { + replacementMaterials.Add(replacement); + anyReplacementMaterialsChanged = true; + if (createdNewMaterial) { + Debug.Log(string.Format("Created blend mode Material '{0}' for SkeletonDataAsset '{1}'.", + replacement.material.name, skeletonDataAsset), replacement.material); + } + } + else { + Debug.LogError(string.Format("Failed creating blend mode Material for SkeletonDataAsset '{0}',"+ + " atlas page '{1}', template '{2}'.", + skeletonDataAsset.name, originalRegion.page.name, materialTemplate.name), + skeletonDataAsset); + anyCreationFailed = true; + } + } + } + } + } + + skeletonDataAsset.isUpgradingBlendModeMaterials = false; + EditorUtility.SetDirty(skeletonDataAsset); + return !anyCreationFailed; + } + + protected static string GetBlendModeMaterialPath(AtlasPage originalPage, string materialSuffix) { + var originalMaterial = originalPage.rendererObject as Material; + var originalPath = AssetDatabase.GetAssetPath(originalMaterial); + return originalPath.Replace(".mat", materialSuffix + ".mat"); + } + + protected static BlendModeMaterials.ReplacementMaterial CreateOrLoadReplacementMaterial ( + AtlasRegion originalRegion, Material materialTemplate, string materialSuffix, out bool createdNewMaterial) { + + createdNewMaterial = false; + var newReplacement = new BlendModeMaterials.ReplacementMaterial(); + var originalPage = originalRegion.page; + var originalMaterial = originalPage.rendererObject as Material; + var blendMaterialPath = GetBlendModeMaterialPath(originalPage, materialSuffix); + + newReplacement.pageName = originalPage.name; + if (File.Exists(blendMaterialPath)) { + newReplacement.material = AssetDatabase.LoadAssetAtPath(blendMaterialPath); + } + else { + var blendModeMaterial = new Material(materialTemplate) { + name = originalMaterial.name + " " + materialTemplate.name, + mainTexture = originalMaterial.mainTexture + }; + newReplacement.material = blendModeMaterial; + + AssetDatabase.CreateAsset(blendModeMaterial, blendMaterialPath); + EditorUtility.SetDirty(blendModeMaterial); + createdNewMaterial = true; + } + + if (newReplacement.material) + return newReplacement; + else + return null; + } + + protected static void ReloadSceneSkeletons (SkeletonDataAsset skeletonDataAsset) { + if (SpineEditorUtilities.Preferences.autoReloadSceneSkeletons) + SpineEditorUtilities.DataReloadHandler.ReloadSceneSkeletonComponents(skeletonDataAsset); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs.meta new file mode 100644 index 0000000..5d96bd8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BlendModeMaterialsUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8094f8aedb33b7744b109c2c1294d37a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs new file mode 100644 index 0000000..b3a2156 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs @@ -0,0 +1,182 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#if UNITY_2018 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEWHIERARCHYWINDOWCALLBACKS +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + public partial class SpineEditorUtilities { + public static class SpineTK2DEditorUtility { + const string SPINE_TK2D_DEFINE = "SPINE_TK2D"; + + internal static bool IsTK2DInstalled () { + return (Shader.Find("tk2d/SolidVertexColor") != null || + Shader.Find("tk2d/AdditiveVertexColor") != null); + } + + internal static bool IsTK2DAllowed { + get { + return false; // replace with "return true;" to allow TK2D support + } + } + + internal static void EnableTK2D () { + if (!IsTK2DAllowed) + return; + SpineBuildEnvUtility.DisableSpineAsmdefFiles(); + SpineBuildEnvUtility.EnableBuildDefine(SPINE_TK2D_DEFINE); + } + + internal static void DisableTK2D () { + SpineBuildEnvUtility.EnableSpineAsmdefFiles(); + SpineBuildEnvUtility.DisableBuildDefine(SPINE_TK2D_DEFINE); + } + } + } + + public static class SpineBuildEnvUtility + { + static bool IsInvalidGroup (BuildTargetGroup group) { + int gi = (int)group; + return + gi == 15 || gi == 16 + || + group == BuildTargetGroup.Unknown; + } + + public static bool EnableBuildDefine (string define) { + + bool wasDefineAdded = false; + Debug.LogWarning("Please ignore errors \"PlayerSettings Validation: Requested build target group doesn't exist\" below"); + foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) { + if (IsInvalidGroup(group)) + continue; + + string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group); + if (!defines.Contains(define)) { + wasDefineAdded = true; + if (defines.EndsWith(";", System.StringComparison.Ordinal)) + defines += define; + else + defines += ";" + define; + + PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines); + } + } + Debug.LogWarning("Please ignore errors \"PlayerSettings Validation: Requested build target group doesn't exist\" above"); + + if (wasDefineAdded) { + Debug.LogWarning("Setting Scripting Define Symbol " + define); + } + else { + Debug.LogWarning("Already Set Scripting Define Symbol " + define); + } + return wasDefineAdded; + } + + public static bool DisableBuildDefine (string define) { + + bool wasDefineRemoved = false; + foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) { + if (IsInvalidGroup(group)) + continue; + + string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group); + if (defines.Contains(define)) { + wasDefineRemoved = true; + if (defines.Contains(define + ";")) + defines = defines.Replace(define + ";", ""); + else + defines = defines.Replace(define, ""); + + PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines); + } + } + + if (wasDefineRemoved) { + Debug.LogWarning("Removing Scripting Define Symbol " + define); + } + else { + Debug.LogWarning("Already Removed Scripting Define Symbol " + define); + } + return wasDefineRemoved; + } + + public static void DisableSpineAsmdefFiles () { + SetAsmdefFileActive("spine-unity-editor", false); + SetAsmdefFileActive("spine-unity", false); + } + + public static void EnableSpineAsmdefFiles () { + SetAsmdefFileActive("spine-unity-editor", true); + SetAsmdefFileActive("spine-unity", true); + } + + internal static void SetAsmdefFileActive (string filename, bool setActive) { + + string typeSearchString = setActive ? " t:TextAsset" : " t:AssemblyDefinitionAsset"; + string extensionBeforeChange = setActive ? ".txt" : ".asmdef"; + string[] guids = AssetDatabase.FindAssets(filename + typeSearchString); + foreach (string guid in guids) { + string currentPath = AssetDatabase.GUIDToAssetPath(guid); + if (System.IO.Path.GetExtension(currentPath) != extensionBeforeChange) // asmdef is also found as t:TextAsset, so check + continue; + + string targetPath = System.IO.Path.ChangeExtension(currentPath, setActive ? "asmdef" : "txt"); + if (System.IO.File.Exists(currentPath) && !System.IO.File.Exists(targetPath)) { + System.IO.File.Copy(currentPath, targetPath); + System.IO.File.Copy(currentPath + ".meta", targetPath + ".meta"); + } + AssetDatabase.DeleteAsset(currentPath); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs.meta new file mode 100644 index 0000000..8710013 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/BuildSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 80767dcb23931c645ad70c88670ddeb6 +timeCreated: 1563313275 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs new file mode 100644 index 0000000..e14c0db --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs @@ -0,0 +1,145 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + + public partial class SpineEditorUtilities { + public static class DataReloadHandler { + + internal static Dictionary savedSkeletonDataAssetAtSKeletonGraphicID = new Dictionary(); + + #if NEWPLAYMODECALLBACKS + internal static void OnPlaymodeStateChanged (PlayModeStateChange stateChange) { + #else + internal static void OnPlaymodeStateChanged () { + #endif + ReloadAllActiveSkeletonsEditMode(); + } + + public static void ReloadAllActiveSkeletonsEditMode () { + + if (EditorApplication.isPaused) return; + if (EditorApplication.isPlaying) return; + if (EditorApplication.isCompiling) return; + if (EditorApplication.isPlayingOrWillChangePlaymode) return; + + var skeletonDataAssetsToReload = new HashSet(); + + var activeSkeletonRenderers = GameObject.FindObjectsOfType(); + foreach (var sr in activeSkeletonRenderers) { + var skeletonDataAsset = sr.skeletonDataAsset; + if (skeletonDataAsset != null) skeletonDataAssetsToReload.Add(skeletonDataAsset); + } + + // Under some circumstances (e.g. on first import) SkeletonGraphic objects + // have their skeletonGraphic.skeletonDataAsset reference corrupted + // by the instance of the ScriptableObject being destroyed but still assigned. + // Here we save the skeletonGraphic.skeletonDataAsset asset path in order + // to restore it later. + var activeSkeletonGraphics = GameObject.FindObjectsOfType(); + foreach (var sg in activeSkeletonGraphics) { + var skeletonDataAsset = sg.skeletonDataAsset; + if (skeletonDataAsset != null) { + var assetPath = AssetDatabase.GetAssetPath(skeletonDataAsset); + var sgID = sg.GetInstanceID(); + savedSkeletonDataAssetAtSKeletonGraphicID[sgID] = assetPath; + skeletonDataAssetsToReload.Add(skeletonDataAsset); + } + } + + foreach (var sda in skeletonDataAssetsToReload) { + sda.Clear(); + sda.GetSkeletonData(true); + } + + foreach (var sr in activeSkeletonRenderers) { + var meshRenderer = sr.GetComponent(); + var sharedMaterials = meshRenderer.sharedMaterials; + foreach (var m in sharedMaterials) { + if (m == null) { + sr.Initialize(true); + break; + } + } + } + + foreach (var sg in activeSkeletonGraphics) { + if (sg.mainTexture == null) + sg.Initialize(true); + } + } + + public static void ReloadSceneSkeletonComponents (SkeletonDataAsset skeletonDataAsset) { + if (EditorApplication.isPaused) return; + if (EditorApplication.isPlaying) return; + if (EditorApplication.isCompiling) return; + if (EditorApplication.isPlayingOrWillChangePlaymode) return; + + var activeSkeletonRenderers = GameObject.FindObjectsOfType(); + foreach (var sr in activeSkeletonRenderers) { + if (sr.isActiveAndEnabled && sr.skeletonDataAsset == skeletonDataAsset) sr.Initialize(true); + } + + var activeSkeletonGraphics = GameObject.FindObjectsOfType(); + foreach (var sg in activeSkeletonGraphics) { + if (sg.isActiveAndEnabled && sg.skeletonDataAsset == skeletonDataAsset) sg.Initialize(true); + } + } + + public static void ReloadAnimationReferenceAssets (SkeletonDataAsset skeletonDataAsset) { + string[] guids = UnityEditor.AssetDatabase.FindAssets("t:AnimationReferenceAsset"); + foreach (string guid in guids) { + string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(path)) { + var referenceAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(path); + if (referenceAsset.SkeletonDataAsset == skeletonDataAsset) + referenceAsset.Initialize(); + } + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs.meta new file mode 100644 index 0000000..21bfdf2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/DataReloadHandler.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8a1a76014a68634a8ede50af6db1cae +timeCreated: 1563310382 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs new file mode 100644 index 0000000..71e7ce1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs @@ -0,0 +1,147 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + public partial class SpineEditorUtilities { + public static class Icons { + public static Texture2D skeleton; + public static Texture2D nullBone; + public static Texture2D bone; + public static Texture2D poseBones; + public static Texture2D boneNib; + public static Texture2D slot; + public static Texture2D slotRoot; + public static Texture2D skinPlaceholder; + public static Texture2D image; + public static Texture2D genericAttachment; + public static Texture2D boundingBox; + public static Texture2D point; + public static Texture2D mesh; + public static Texture2D weights; + public static Texture2D path; + public static Texture2D clipping; + public static Texture2D skin; + public static Texture2D skinsRoot; + public static Texture2D animation; + public static Texture2D animationRoot; + public static Texture2D spine; + public static Texture2D userEvent; + public static Texture2D constraintNib; + public static Texture2D constraintRoot; + public static Texture2D constraintTransform; + public static Texture2D constraintPath; + public static Texture2D constraintIK; + public static Texture2D warning; + public static Texture2D skeletonUtility; + public static Texture2D hingeChain; + public static Texture2D subMeshRenderer; + public static Texture2D skeletonDataAssetIcon; + public static Texture2D info; + public static Texture2D unity; + + static Texture2D LoadIcon (string filename) { + return (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/" + filename); + } + + public static void Initialize () { + skeleton = LoadIcon("icon-skeleton.png"); + nullBone = LoadIcon("icon-null.png"); + bone = LoadIcon("icon-bone.png"); + poseBones = LoadIcon("icon-poseBones.png"); + boneNib = LoadIcon("icon-boneNib.png"); + slot = LoadIcon("icon-slot.png"); + slotRoot = LoadIcon("icon-slotRoot.png"); + skinPlaceholder = LoadIcon("icon-skinPlaceholder.png"); + + genericAttachment = LoadIcon("icon-attachment.png"); + image = LoadIcon("icon-image.png"); + boundingBox = LoadIcon("icon-boundingBox.png"); + point = LoadIcon("icon-point.png"); + mesh = LoadIcon("icon-mesh.png"); + weights = LoadIcon("icon-weights.png"); + path = LoadIcon("icon-path.png"); + clipping = LoadIcon("icon-clipping.png"); + + skin = LoadIcon("icon-skin.png"); + skinsRoot = LoadIcon("icon-skinsRoot.png"); + animation = LoadIcon("icon-animation.png"); + animationRoot = LoadIcon("icon-animationRoot.png"); + spine = LoadIcon("icon-spine.png"); + userEvent = LoadIcon("icon-event.png"); + constraintNib = LoadIcon("icon-constraintNib.png"); + + constraintRoot = LoadIcon("icon-constraints.png"); + constraintTransform = LoadIcon("icon-constraintTransform.png"); + constraintPath = LoadIcon("icon-constraintPath.png"); + constraintIK = LoadIcon("icon-constraintIK.png"); + + warning = LoadIcon("icon-warning.png"); + skeletonUtility = LoadIcon("icon-skeletonUtility.png"); + hingeChain = LoadIcon("icon-hingeChain.png"); + subMeshRenderer = LoadIcon("icon-subMeshRenderer.png"); + + skeletonDataAssetIcon = LoadIcon("SkeletonDataAsset Icon.png"); + + info = EditorGUIUtility.FindTexture("console.infoicon.sml"); + unity = EditorGUIUtility.FindTexture("SceneAsset Icon"); + } + + public static Texture2D GetAttachmentIcon (Attachment attachment) { + // Analysis disable once CanBeReplacedWithTryCastAndCheckForNull + if (attachment is RegionAttachment) + return Icons.image; + else if (attachment is MeshAttachment) + return ((MeshAttachment)attachment).IsWeighted() ? Icons.weights : Icons.mesh; + else if (attachment is BoundingBoxAttachment) + return Icons.boundingBox; + else if (attachment is PointAttachment) + return Icons.point; + else if (attachment is PathAttachment) + return Icons.path; + else if (attachment is ClippingAttachment) + return Icons.clipping; + else + return Icons.warning; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs.meta new file mode 100644 index 0000000..c8cf2c2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Icons.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8603301469b2a284db8eaa26dc60ada8 +timeCreated: 1563312057 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs new file mode 100644 index 0000000..d76a770 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs @@ -0,0 +1,193 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + using EventType = UnityEngine.EventType; + + public partial class SpineEditorUtilities { + public static class DragAndDropInstantiation { + public struct SpawnMenuData { + public Vector3 spawnPoint; + public Transform parent; + public SkeletonDataAsset skeletonDataAsset; + public EditorInstantiation.InstantiateDelegate instantiateDelegate; + public bool isUI; + } + + public static void SceneViewDragAndDrop (SceneView sceneview) { + var current = UnityEngine.Event.current; + var references = DragAndDrop.objectReferences; + if (current.type == EventType.Layout) + return; + + // Allow drag and drop of one SkeletonDataAsset. + if (references.Length == 1) { + var skeletonDataAsset = references[0] as SkeletonDataAsset; + if (skeletonDataAsset != null) { + var mousePos = current.mousePosition; + + bool invalidSkeletonData = skeletonDataAsset.GetSkeletonData(true) == null; + if (invalidSkeletonData) { + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + Handles.BeginGUI(); + GUI.Label(new Rect(mousePos + new Vector2(20f, 20f), new Vector2(400f, 40f)), new GUIContent(string.Format("{0} is invalid.\nCannot create new Spine GameObject.", skeletonDataAsset.name), SpineEditorUtilities.Icons.warning)); + Handles.EndGUI(); + return; + } else { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + Handles.BeginGUI(); + GUI.Label(new Rect(mousePos + new Vector2(20f, 20f), new Vector2(400f, 20f)), new GUIContent(string.Format("Create Spine GameObject ({0})", skeletonDataAsset.skeletonJSON.name), SpineEditorUtilities.Icons.skeletonDataAssetIcon)); + Handles.EndGUI(); + + if (current.type == EventType.DragPerform) { + RectTransform rectTransform = (Selection.activeGameObject == null) ? null : Selection.activeGameObject.GetComponent(); + Plane plane = (rectTransform == null) ? new Plane(Vector3.back, Vector3.zero) : new Plane(-rectTransform.forward, rectTransform.position); + Vector3 spawnPoint = MousePointToWorldPoint2D(mousePos, sceneview.camera, plane); + ShowInstantiateContextMenu(skeletonDataAsset, spawnPoint, null); + DragAndDrop.AcceptDrag(); + current.Use(); + } + } + } + } + } + + public static void ShowInstantiateContextMenu (SkeletonDataAsset skeletonDataAsset, Vector3 spawnPoint, Transform parent) { + var menu = new GenericMenu(); + + // SkeletonAnimation + menu.AddItem(new GUIContent("SkeletonAnimation"), false, HandleSkeletonComponentDrop, new SpawnMenuData { + skeletonDataAsset = skeletonDataAsset, + spawnPoint = spawnPoint, + parent = parent, + instantiateDelegate = (data) => EditorInstantiation.InstantiateSkeletonAnimation(data), + isUI = false + }); + + // SkeletonGraphic + var skeletonGraphicInspectorType = System.Type.GetType("Spine.Unity.Editor.SkeletonGraphicInspector"); + if (skeletonGraphicInspectorType != null) { + var graphicInstantiateDelegate = skeletonGraphicInspectorType.GetMethod("SpawnSkeletonGraphicFromDrop", BindingFlags.Static | BindingFlags.Public); + if (graphicInstantiateDelegate != null) + menu.AddItem(new GUIContent("SkeletonGraphic (UI)"), false, HandleSkeletonComponentDrop, new SpawnMenuData { + skeletonDataAsset = skeletonDataAsset, + spawnPoint = spawnPoint, + parent = parent, + instantiateDelegate = System.Delegate.CreateDelegate(typeof(EditorInstantiation.InstantiateDelegate), graphicInstantiateDelegate) as EditorInstantiation.InstantiateDelegate, + isUI = true + }); + } + +#if SPINE_SKELETONMECANIM + menu.AddSeparator(""); + // SkeletonMecanim + menu.AddItem(new GUIContent("SkeletonMecanim"), false, HandleSkeletonComponentDrop, new SpawnMenuData { + skeletonDataAsset = skeletonDataAsset, + spawnPoint = spawnPoint, + parent = parent, + instantiateDelegate = (data) => EditorInstantiation.InstantiateSkeletonMecanim(data), + isUI = false + }); +#endif + + menu.ShowAsContext(); + } + + public static void HandleSkeletonComponentDrop (object spawnMenuData) { + var data = (SpawnMenuData)spawnMenuData; + + if (data.skeletonDataAsset.GetSkeletonData(true) == null) { + EditorUtility.DisplayDialog("Invalid SkeletonDataAsset", "Unable to create Spine GameObject.\n\nPlease check your SkeletonDataAsset.", "Ok"); + return; + } + + bool isUI = data.isUI; + + Component newSkeletonComponent = data.instantiateDelegate.Invoke(data.skeletonDataAsset); + GameObject newGameObject = newSkeletonComponent.gameObject; + Transform newTransform = newGameObject.transform; + + var usedParent = data.parent != null ? data.parent.gameObject : isUI ? Selection.activeGameObject : null; + if (usedParent) + newTransform.SetParent(usedParent.transform, false); + + newTransform.position = isUI ? data.spawnPoint : RoundVector(data.spawnPoint, 2); + + if (isUI) { + if (usedParent != null && usedParent.GetComponent() != null) { + ((SkeletonGraphic)newSkeletonComponent).MatchRectTransformWithBounds(); + } + else + Debug.Log("Created a UI Skeleton GameObject not under a RectTransform. It may not be visible until you parent it to a canvas."); + } + + if (!isUI && usedParent != null && usedParent.transform.localScale != Vector3.one) + Debug.Log("New Spine GameObject was parented to a scaled Transform. It may not be the intended size."); + + Selection.activeGameObject = newGameObject; + //EditorGUIUtility.PingObject(newGameObject); // Doesn't work when setting activeGameObject. + Undo.RegisterCreatedObjectUndo(newGameObject, "Create Spine GameObject"); + } + + /// + /// Rounds off vector components to a number of decimal digits. + /// + public static Vector3 RoundVector (Vector3 vector, int digits) { + vector.x = (float)System.Math.Round(vector.x, digits); + vector.y = (float)System.Math.Round(vector.y, digits); + vector.z = (float)System.Math.Round(vector.z, digits); + return vector; + } + + /// + /// Converts a mouse point to a world point on a plane. + /// + static Vector3 MousePointToWorldPoint2D (Vector2 mousePosition, Camera camera, Plane plane) { + var screenPos = new Vector3(mousePosition.x, camera.pixelHeight - mousePosition.y, 0f); + var ray = camera.ScreenPointToRay(screenPos); + float distance; + bool hit = plane.Raycast(ray, out distance); + return ray.GetPoint(distance); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs.meta new file mode 100644 index 0000000..442ea7a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Instantiation.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 94ecc7f73dfc0484e848a0e6a1a11f2b +timeCreated: 1563311945 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs new file mode 100644 index 0000000..def8761 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs @@ -0,0 +1,434 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#if UNITY_2018_3_OR_NEWER +#define NEW_PREFERENCES_SETTINGS_PROVIDER +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + public partial class SpineEditorUtilities { + + #if NEW_PREFERENCES_SETTINGS_PROVIDER + static class SpineSettingsProviderRegistration + { + [SettingsProvider] + public static SettingsProvider CreateSpineSettingsProvider() + { + var provider = new SettingsProvider("Spine", SettingsScope.User) + { + label = "Spine", + guiHandler = (searchContext) => + { + var settings = SpinePreferences.GetOrCreateSettings(); + var serializedSettings = new SerializedObject(settings); + SpinePreferences.HandlePreferencesGUI(serializedSettings); + if (serializedSettings.ApplyModifiedProperties()) + OldPreferences.SaveToEditorPrefs(settings); + }, + + // Populate the search keywords to enable smart search filtering and label highlighting: + keywords = new HashSet(new[] { "Spine", "Preferences", "Skeleton", "Default", "Mix", "Duration" }) + }; + return provider; + } + } + #else + // Preferences entry point + [PreferenceItem("Spine")] + static void PreferencesGUI () { + Preferences.HandlePreferencesGUI(); + } + #endif + + #if NEW_PREFERENCES_SETTINGS_PROVIDER + public static SpinePreferences Preferences { + get { + return SpinePreferences.GetOrCreateSettings(); + } + } + #endif + + #if NEW_PREFERENCES_SETTINGS_PROVIDER + public static class OldPreferences { + #else + public static class Preferences { + #endif + const string DEFAULT_SCALE_KEY = "SPINE_DEFAULT_SCALE"; + public static float defaultScale = SpinePreferences.DEFAULT_DEFAULT_SCALE; + + const string DEFAULT_MIX_KEY = "SPINE_DEFAULT_MIX"; + public static float defaultMix = SpinePreferences.DEFAULT_DEFAULT_MIX; + + const string DEFAULT_SHADER_KEY = "SPINE_DEFAULT_SHADER"; + public static string defaultShader = SpinePreferences.DEFAULT_DEFAULT_SHADER; + + const string DEFAULT_ZSPACING_KEY = "SPINE_DEFAULT_ZSPACING"; + public static float defaultZSpacing = SpinePreferences.DEFAULT_DEFAULT_ZSPACING; + + const string DEFAULT_INSTANTIATE_LOOP_KEY = "SPINE_DEFAULT_INSTANTIATE_LOOP"; + public static bool defaultInstantiateLoop = SpinePreferences.DEFAULT_DEFAULT_INSTANTIATE_LOOP; + + const string SHOW_HIERARCHY_ICONS_KEY = "SPINE_SHOW_HIERARCHY_ICONS"; + public static bool showHierarchyIcons = SpinePreferences.DEFAULT_SHOW_HIERARCHY_ICONS; + + const string SET_TEXTUREIMPORTER_SETTINGS_KEY = "SPINE_SET_TEXTUREIMPORTER_SETTINGS"; + public static bool setTextureImporterSettings = SpinePreferences.DEFAULT_SET_TEXTUREIMPORTER_SETTINGS; + + const string TEXTURE_SETTINGS_REFERENCE_KEY = "SPINE_TEXTURE_SETTINGS_REFERENCE"; + public static string textureSettingsReference = SpinePreferences.DEFAULT_TEXTURE_SETTINGS_REFERENCE; + + public static bool UsesPMAWorkflow { + get { + return SpinePreferences.IsPMAWorkflow(textureSettingsReference); + } + } + + const string BLEND_MODE_MATERIAL_MULTIPLY_KEY = "SPINE_BLENDMODE_MATERIAL_MULTIPLY"; + const string BLEND_MODE_MATERIAL_SCREEN_KEY = "SPINE_BLENDMODE_MATERIAL_SCREEN"; + const string BLEND_MODE_MATERIAL_ADDITIVE_KEY = "SPINE_BLENDMODE_MATERIAL_ADDITIVE"; + public static string blendModeMaterialMultiply = ""; + public static string blendModeMaterialScreen = ""; + public static string blendModeMaterialAdditive = ""; + public const string DEFAULT_BLEND_MODE_MULTIPLY_MATERIAL = SpinePreferences.DEFAULT_BLEND_MODE_MULTIPLY_MATERIAL; + public const string DEFAULT_BLEND_MODE_SCREEN_MATERIAL = SpinePreferences.DEFAULT_BLEND_MODE_SCREEN_MATERIAL; + public const string DEFAULT_BLEND_MODE_ADDITIVE_MATERIAL = SpinePreferences.DEFAULT_BLEND_MODE_ADDITIVE_MATERIAL; + + public static Material BlendModeMaterialMultiply { + get { return AssetDatabase.LoadAssetAtPath(blendModeMaterialMultiply); } + } + public static Material BlendModeMaterialScreen { + get { return AssetDatabase.LoadAssetAtPath(blendModeMaterialScreen); } + } + public static Material BlendModeMaterialAdditive { + get { return AssetDatabase.LoadAssetAtPath(blendModeMaterialAdditive); } + } + + const string ATLASTXT_WARNING_KEY = "SPINE_ATLASTXT_WARNING"; + public static bool atlasTxtImportWarning = SpinePreferences.DEFAULT_ATLASTXT_WARNING; + + const string TEXTUREIMPORTER_WARNING_KEY = "SPINE_TEXTUREIMPORTER_WARNING"; + public static bool textureImporterWarning = SpinePreferences.DEFAULT_TEXTUREIMPORTER_WARNING; + + const string COMPONENTMATERIAL_WARNING_KEY = "SPINE_COMPONENTMATERIAL_WARNING"; + public static bool componentMaterialWarning = SpinePreferences.DEFAULT_COMPONENTMATERIAL_WARNING; + + public const float DEFAULT_MIPMAPBIAS = SpinePreferences.DEFAULT_MIPMAPBIAS; + + public const string SCENE_ICONS_SCALE_KEY = "SPINE_SCENE_ICONS_SCALE"; + public static float handleScale = SpinePreferences.DEFAULT_SCENE_ICONS_SCALE; + + const string AUTO_RELOAD_SCENESKELETONS_KEY = "SPINE_AUTO_RELOAD_SCENESKELETONS"; + public static bool autoReloadSceneSkeletons = SpinePreferences.DEFAULT_AUTO_RELOAD_SCENESKELETONS; + + const string MECANIM_EVENT_INCLUDE_FOLDERNAME_KEY = "SPINE_MECANIM_EVENT_INCLUDE_FOLDERNAME"; + public static bool mecanimEventIncludeFolderName = SpinePreferences.DEFAULT_MECANIM_EVENT_INCLUDE_FOLDERNAME; + + const string TIMELINE_USE_BLEND_DURATION_KEY = "SPINE_TIMELINE_USE_BLEND_DURATION_KEY"; + public static bool timelineUseBlendDuration = SpinePreferences.DEFAULT_TIMELINE_USE_BLEND_DURATION; + + + static bool preferencesLoaded = false; + + public static void Load () { + if (preferencesLoaded) + return; + + defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, SpinePreferences.DEFAULT_DEFAULT_MIX); + defaultScale = EditorPrefs.GetFloat(DEFAULT_SCALE_KEY, SpinePreferences.DEFAULT_DEFAULT_SCALE); + defaultZSpacing = EditorPrefs.GetFloat(DEFAULT_ZSPACING_KEY, SpinePreferences.DEFAULT_DEFAULT_ZSPACING); + defaultShader = EditorPrefs.GetString(DEFAULT_SHADER_KEY, SpinePreferences.DEFAULT_DEFAULT_SHADER); + showHierarchyIcons = EditorPrefs.GetBool(SHOW_HIERARCHY_ICONS_KEY, SpinePreferences.DEFAULT_SHOW_HIERARCHY_ICONS); + setTextureImporterSettings = EditorPrefs.GetBool(SET_TEXTUREIMPORTER_SETTINGS_KEY, SpinePreferences.DEFAULT_SET_TEXTUREIMPORTER_SETTINGS); + textureSettingsReference = EditorPrefs.GetString(TEXTURE_SETTINGS_REFERENCE_KEY, SpinePreferences.DEFAULT_TEXTURE_SETTINGS_REFERENCE); + blendModeMaterialMultiply = EditorPrefs.GetString(BLEND_MODE_MATERIAL_MULTIPLY_KEY, ""); + blendModeMaterialScreen = EditorPrefs.GetString(BLEND_MODE_MATERIAL_SCREEN_KEY, ""); + blendModeMaterialAdditive = EditorPrefs.GetString(BLEND_MODE_MATERIAL_ADDITIVE_KEY, ""); + autoReloadSceneSkeletons = EditorPrefs.GetBool(AUTO_RELOAD_SCENESKELETONS_KEY, SpinePreferences.DEFAULT_AUTO_RELOAD_SCENESKELETONS); + mecanimEventIncludeFolderName = EditorPrefs.GetBool(MECANIM_EVENT_INCLUDE_FOLDERNAME_KEY, SpinePreferences.DEFAULT_MECANIM_EVENT_INCLUDE_FOLDERNAME); + atlasTxtImportWarning = EditorPrefs.GetBool(ATLASTXT_WARNING_KEY, SpinePreferences.DEFAULT_ATLASTXT_WARNING); + textureImporterWarning = EditorPrefs.GetBool(TEXTUREIMPORTER_WARNING_KEY, SpinePreferences.DEFAULT_TEXTUREIMPORTER_WARNING); + componentMaterialWarning = EditorPrefs.GetBool(COMPONENTMATERIAL_WARNING_KEY, SpinePreferences.DEFAULT_COMPONENTMATERIAL_WARNING); + timelineUseBlendDuration = EditorPrefs.GetBool(TIMELINE_USE_BLEND_DURATION_KEY, SpinePreferences.DEFAULT_TIMELINE_USE_BLEND_DURATION); + handleScale = EditorPrefs.GetFloat(SCENE_ICONS_SCALE_KEY, SpinePreferences.DEFAULT_SCENE_ICONS_SCALE); + preferencesLoaded = true; + } + +#if NEW_PREFERENCES_SETTINGS_PROVIDER + public static void CopyOldToNewPreferences(ref SpinePreferences newPreferences) { + newPreferences.defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, SpinePreferences.DEFAULT_DEFAULT_MIX); + newPreferences.defaultScale = EditorPrefs.GetFloat(DEFAULT_SCALE_KEY, SpinePreferences.DEFAULT_DEFAULT_SCALE); + newPreferences.defaultZSpacing = EditorPrefs.GetFloat(DEFAULT_ZSPACING_KEY, SpinePreferences.DEFAULT_DEFAULT_ZSPACING); + newPreferences.defaultShader = EditorPrefs.GetString(DEFAULT_SHADER_KEY, SpinePreferences.DEFAULT_DEFAULT_SHADER); + newPreferences.showHierarchyIcons = EditorPrefs.GetBool(SHOW_HIERARCHY_ICONS_KEY, SpinePreferences.DEFAULT_SHOW_HIERARCHY_ICONS); + newPreferences.setTextureImporterSettings = EditorPrefs.GetBool(SET_TEXTUREIMPORTER_SETTINGS_KEY, SpinePreferences.DEFAULT_SET_TEXTUREIMPORTER_SETTINGS); + newPreferences.textureSettingsReference = EditorPrefs.GetString(TEXTURE_SETTINGS_REFERENCE_KEY, SpinePreferences.DEFAULT_TEXTURE_SETTINGS_REFERENCE); + newPreferences.autoReloadSceneSkeletons = EditorPrefs.GetBool(AUTO_RELOAD_SCENESKELETONS_KEY, SpinePreferences.DEFAULT_AUTO_RELOAD_SCENESKELETONS); + newPreferences.mecanimEventIncludeFolderName = EditorPrefs.GetBool(MECANIM_EVENT_INCLUDE_FOLDERNAME_KEY, SpinePreferences.DEFAULT_MECANIM_EVENT_INCLUDE_FOLDERNAME); + newPreferences.atlasTxtImportWarning = EditorPrefs.GetBool(ATLASTXT_WARNING_KEY, SpinePreferences.DEFAULT_ATLASTXT_WARNING); + newPreferences.textureImporterWarning = EditorPrefs.GetBool(TEXTUREIMPORTER_WARNING_KEY, SpinePreferences.DEFAULT_TEXTUREIMPORTER_WARNING); + newPreferences.componentMaterialWarning = EditorPrefs.GetBool(COMPONENTMATERIAL_WARNING_KEY, SpinePreferences.DEFAULT_COMPONENTMATERIAL_WARNING); + newPreferences.timelineUseBlendDuration = EditorPrefs.GetBool(TIMELINE_USE_BLEND_DURATION_KEY, SpinePreferences.DEFAULT_TIMELINE_USE_BLEND_DURATION); + newPreferences.handleScale = EditorPrefs.GetFloat(SCENE_ICONS_SCALE_KEY, SpinePreferences.DEFAULT_SCENE_ICONS_SCALE); + } + + public static void SaveToEditorPrefs(SpinePreferences preferences) { + EditorPrefs.SetFloat(DEFAULT_MIX_KEY, preferences.defaultMix); + EditorPrefs.SetFloat(DEFAULT_SCALE_KEY, preferences.defaultScale); + EditorPrefs.SetFloat(DEFAULT_ZSPACING_KEY, preferences.defaultZSpacing); + EditorPrefs.SetString(DEFAULT_SHADER_KEY, preferences.defaultShader); + EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, preferences.showHierarchyIcons); + EditorPrefs.SetBool(SET_TEXTUREIMPORTER_SETTINGS_KEY, preferences.setTextureImporterSettings); + EditorPrefs.SetString(TEXTURE_SETTINGS_REFERENCE_KEY, preferences.textureSettingsReference); + EditorPrefs.SetBool(AUTO_RELOAD_SCENESKELETONS_KEY, preferences.autoReloadSceneSkeletons); + EditorPrefs.SetBool(MECANIM_EVENT_INCLUDE_FOLDERNAME_KEY, preferences.mecanimEventIncludeFolderName); + EditorPrefs.SetBool(ATLASTXT_WARNING_KEY, preferences.atlasTxtImportWarning); + EditorPrefs.SetBool(TEXTUREIMPORTER_WARNING_KEY, preferences.textureImporterWarning); + EditorPrefs.SetBool(COMPONENTMATERIAL_WARNING_KEY, preferences.componentMaterialWarning); + EditorPrefs.SetBool(TIMELINE_USE_BLEND_DURATION_KEY, preferences.timelineUseBlendDuration); + EditorPrefs.SetFloat(SCENE_ICONS_SCALE_KEY, preferences.handleScale); + } +#endif + +#if !NEW_PREFERENCES_SETTINGS_PROVIDER + public static void HandlePreferencesGUI () { + if (!preferencesLoaded) + Load(); + + EditorGUI.BeginChangeCheck(); + showHierarchyIcons = EditorGUILayout.Toggle(new GUIContent("Show Hierarchy Icons", "Show relevant icons on GameObjects with Spine Components on them. Disable this if you have large, complex scenes."), showHierarchyIcons); + if (EditorGUI.EndChangeCheck()) { + EditorPrefs.SetBool(SHOW_HIERARCHY_ICONS_KEY, showHierarchyIcons); +#if NEWPLAYMODECALLBACKS + HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); +#else + HierarchyHandler.IconsOnPlaymodeStateChanged(); +#endif + } + + BoolPrefsField(ref autoReloadSceneSkeletons, AUTO_RELOAD_SCENESKELETONS_KEY, new GUIContent("Auto-reload scene components", "Reloads Skeleton components in the scene whenever their SkeletonDataAsset is modified. This makes it so changes in the SkeletonDataAsset inspector are immediately reflected. This may be slow when your scenes have large numbers of SkeletonRenderers or SkeletonGraphic.")); + + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("Auto-Import Settings", EditorStyles.boldLabel); + { + SpineEditorUtilities.FloatPrefsField(ref defaultMix, DEFAULT_MIX_KEY, new GUIContent("Default Mix", "The Default Mix Duration for newly imported SkeletonDataAssets."), min: 0); + SpineEditorUtilities.FloatPrefsField(ref defaultScale, DEFAULT_SCALE_KEY, new GUIContent("Default SkeletonData Scale", "The Default skeleton import scale for newly imported SkeletonDataAssets."), min: 0.0000001f); + + EditorGUI.BeginChangeCheck(); + var shader = (EditorGUILayout.ObjectField("Default Shader", Shader.Find(defaultShader), typeof(Shader), false) as Shader); + defaultShader = shader != null ? shader.name : SpinePreferences.DEFAULT_DEFAULT_SHADER; + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetString(DEFAULT_SHADER_KEY, defaultShader); + + SpineEditorUtilities.BoolPrefsField(ref setTextureImporterSettings, SET_TEXTUREIMPORTER_SETTINGS_KEY, new GUIContent("Apply Atlas Texture Settings", "Apply the recommended settings for Texture Importers.")); + SpineEditorUtilities.Texture2DPrefsField(ref textureSettingsReference, TEXTURE_SETTINGS_REFERENCE_KEY, new GUIContent("Atlas Texture Reference Settings", "Apply the selected reference texture import settings at newly imported atlas textures. When exporting atlas textures from Spine with \"Premultiply alpha\" enabled (the default), you can leave it at \"PMAPresetTemplate\". If you have disabled \"Premultiply alpha\", set it to \"StraightAlphaPresetTemplate\". You can also create your own reference texture asset and assign it here.")); + if (string.IsNullOrEmpty(textureSettingsReference)) { + var pmaTextureSettingsReferenceGUIDS = AssetDatabase.FindAssets("PMAPresetTemplate"); + if (pmaTextureSettingsReferenceGUIDS.Length > 0) { + textureSettingsReference = AssetDatabase.GUIDToAssetPath(pmaTextureSettingsReferenceGUIDS[0]); + EditorPrefs.SetString(TEXTURE_SETTINGS_REFERENCE_KEY, textureSettingsReference); + } + } + + SpineEditorUtilities.MaterialPrefsField(ref blendModeMaterialAdditive, BLEND_MODE_MATERIAL_ADDITIVE_KEY, new GUIContent("Additive Material", "Additive blend mode Material template.")); + if (string.IsNullOrEmpty(blendModeMaterialAdditive)) { + var blendModeMaterialAdditiveGUIDS = AssetDatabase.FindAssets(DEFAULT_BLEND_MODE_ADDITIVE_MATERIAL); + if (blendModeMaterialAdditiveGUIDS.Length > 0) { + blendModeMaterialAdditive = AssetDatabase.GUIDToAssetPath(blendModeMaterialAdditiveGUIDS[0]); + } + } + SpineEditorUtilities.MaterialPrefsField(ref blendModeMaterialMultiply, BLEND_MODE_MATERIAL_MULTIPLY_KEY, new GUIContent("Multiply Material", "Multiply blend mode Material template.")); + if (string.IsNullOrEmpty(blendModeMaterialMultiply)) { + var blendModeMaterialMultiplyGUIDS = AssetDatabase.FindAssets(DEFAULT_BLEND_MODE_MULTIPLY_MATERIAL); + if (blendModeMaterialMultiplyGUIDS.Length > 0) { + blendModeMaterialMultiply = AssetDatabase.GUIDToAssetPath(blendModeMaterialMultiplyGUIDS[0]); + } + } + SpineEditorUtilities.MaterialPrefsField(ref blendModeMaterialScreen, BLEND_MODE_MATERIAL_SCREEN_KEY, new GUIContent("Screen Material", "Screen blend mode Material template.")); + if (string.IsNullOrEmpty(blendModeMaterialScreen)) { + var blendModeMaterialScreenGUIDS = AssetDatabase.FindAssets(DEFAULT_BLEND_MODE_SCREEN_MATERIAL); + if (blendModeMaterialScreenGUIDS.Length > 0) { + blendModeMaterialScreen = AssetDatabase.GUIDToAssetPath(blendModeMaterialScreenGUIDS[0]); + } + } + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Warnings", EditorStyles.boldLabel); + { + SpineEditorUtilities.BoolPrefsField(ref atlasTxtImportWarning, ATLASTXT_WARNING_KEY, new GUIContent("Atlas Extension Warning", "Log a warning and recommendation whenever a `.atlas` file is found.")); + SpineEditorUtilities.BoolPrefsField(ref textureImporterWarning, TEXTUREIMPORTER_WARNING_KEY, new GUIContent("Texture Settings Warning", "Log a warning and recommendation whenever Texture Import Settings are detected that could lead to undesired effects, e.g. white border artifacts.")); + SpineEditorUtilities.BoolPrefsField(ref componentMaterialWarning, COMPONENTMATERIAL_WARNING_KEY, new GUIContent("Component & Material Warning", "Log a warning and recommendation whenever Component and Material settings are not compatible.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Editor Instantiation", EditorStyles.boldLabel); + { + EditorGUI.BeginChangeCheck(); + defaultZSpacing = EditorGUILayout.Slider("Default Slot Z-Spacing", defaultZSpacing, -0.1f, 0f); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetFloat(DEFAULT_ZSPACING_KEY, defaultZSpacing); + + SpineEditorUtilities.BoolPrefsField(ref defaultInstantiateLoop, DEFAULT_INSTANTIATE_LOOP_KEY, new GUIContent("Default Loop", "Spawn Spine GameObjects with loop enabled.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Mecanim Bake Settings", EditorStyles.boldLabel); + { + SpineEditorUtilities.BoolPrefsField(ref mecanimEventIncludeFolderName, MECANIM_EVENT_INCLUDE_FOLDERNAME_KEY, new GUIContent("Include Folder Name in Event", "When enabled, Mecanim events will call methods named 'FolderNameEventName', when disabled it will call 'EventName'.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Handles and Gizmos", EditorStyles.boldLabel); + { + EditorGUI.BeginChangeCheck(); + handleScale = EditorGUILayout.Slider("Editor Bone Scale", handleScale, 0.01f, 2f); + handleScale = Mathf.Max(0.01f, handleScale); + if (EditorGUI.EndChangeCheck()) { + EditorPrefs.SetFloat(SCENE_ICONS_SCALE_KEY, handleScale); + SceneView.RepaintAll(); + } + } + +#if SPINE_TK2D_DEFINE + bool isTK2DDefineSet = true; +#else + bool isTK2DDefineSet = false; +#endif + bool isTK2DAllowed = SpineTK2DEditorUtility.IsTK2DAllowed; + if (SpineTK2DEditorUtility.IsTK2DInstalled() || isTK2DDefineSet) { + GUILayout.Space(20); + EditorGUILayout.LabelField("3rd Party Settings", EditorStyles.boldLabel); + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.PrefixLabel("Define TK2D"); + if (isTK2DAllowed && GUILayout.Button("Enable", GUILayout.Width(64))) + SpineTK2DEditorUtility.EnableTK2D(); + if (GUILayout.Button("Disable", GUILayout.Width(64))) + SpineTK2DEditorUtility.DisableTK2D(); + } +#if !SPINE_TK2D_DEFINE + if (!isTK2DAllowed) { + EditorGUILayout.LabelField("To allow TK2D support, please modify line 67 in", EditorStyles.boldLabel); + EditorGUILayout.LabelField("Spine/Editor/spine-unity/Editor/Util./BuildSettings.cs", EditorStyles.boldLabel); + } +#endif + } + + GUILayout.Space(20); + EditorGUILayout.LabelField("Timeline Extension", EditorStyles.boldLabel); + { + SpineEditorUtilities.BoolPrefsField(ref timelineUseBlendDuration, TIMELINE_USE_BLEND_DURATION_KEY, new GUIContent("Use Blend Duration", "When enabled, MixDuration will be synced with timeline clip transition duration 'Ease In Duration'.")); + } + } +#endif // !NEW_PREFERENCES_SETTINGS_PROVIDER + } + + static void BoolPrefsField (ref bool currentValue, string editorPrefsKey, GUIContent label) { + EditorGUI.BeginChangeCheck(); + currentValue = EditorGUILayout.Toggle(label, currentValue); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetBool(editorPrefsKey, currentValue); + } + + static void FloatPrefsField (ref float currentValue, string editorPrefsKey, GUIContent label, float min = float.NegativeInfinity, float max = float.PositiveInfinity) { + EditorGUI.BeginChangeCheck(); + currentValue = EditorGUILayout.DelayedFloatField(label, currentValue); + if (EditorGUI.EndChangeCheck()) { + currentValue = Mathf.Clamp(currentValue, min, max); + EditorPrefs.SetFloat(editorPrefsKey, currentValue); + } + } + + static void Texture2DPrefsField (ref string currentValue, string editorPrefsKey, GUIContent label) { + EditorGUI.BeginChangeCheck(); + EditorGUIUtility.wideMode = true; + var texture = (EditorGUILayout.ObjectField(label, AssetDatabase.LoadAssetAtPath(currentValue), typeof(Object), false) as Texture2D); + currentValue = texture != null ? AssetDatabase.GetAssetPath(texture) : ""; + if (EditorGUI.EndChangeCheck()) { + EditorPrefs.SetString(editorPrefsKey, currentValue); + } + } + + static void MaterialPrefsField (ref string currentValue, string editorPrefsKey, GUIContent label) { + EditorGUI.BeginChangeCheck(); + EditorGUIUtility.wideMode = true; + var material = (EditorGUILayout.ObjectField(label, AssetDatabase.LoadAssetAtPath(currentValue), typeof(Object), false) as Material); + currentValue = material != null ? AssetDatabase.GetAssetPath(material) : ""; + if (EditorGUI.EndChangeCheck()) { + EditorPrefs.SetString(editorPrefsKey, currentValue); + } + } + + public static void FloatPropertyField (SerializedProperty property, GUIContent label, float min = float.NegativeInfinity, float max = float.PositiveInfinity) { + EditorGUI.BeginChangeCheck(); + property.floatValue = EditorGUILayout.DelayedFloatField(label, property.floatValue); + if (EditorGUI.EndChangeCheck()) { + property.floatValue = Mathf.Clamp(property.floatValue, min, max); + } + } + + public static void ShaderPropertyField (SerializedProperty property, GUIContent label, string fallbackShaderName) { + var shader = (EditorGUILayout.ObjectField(label, Shader.Find(property.stringValue), typeof(Shader), false) as Shader); + property.stringValue = shader != null ? shader.name : fallbackShaderName; + } + + public static void MaterialPropertyField (SerializedProperty property, GUIContent label) { + var material = (EditorGUILayout.ObjectField(label, AssetDatabase.LoadAssetAtPath(property.stringValue), typeof(Material), false) as Material); + property.stringValue = material ? AssetDatabase.GetAssetPath(material) : ""; + } + + #if NEW_PREFERENCES_SETTINGS_PROVIDER + public static void PresetAssetPropertyField (SerializedProperty property, GUIContent label) { + var texturePreset = (EditorGUILayout.ObjectField(label, AssetDatabase.LoadAssetAtPath(property.stringValue), typeof(UnityEditor.Presets.Preset), false) as UnityEditor.Presets.Preset); + bool isTexturePreset = texturePreset != null && texturePreset.GetTargetTypeName() == "TextureImporter"; + property.stringValue = isTexturePreset ? AssetDatabase.GetAssetPath(texturePreset) : ""; + } + #endif + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs.meta new file mode 100644 index 0000000..3c2d5ac --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/Preferences.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6d80c945a2e3436459a97b7a9a16ef46 +timeCreated: 1563311495 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs new file mode 100644 index 0000000..5c8016b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs @@ -0,0 +1,459 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 +#pragma warning disable 0618 // for 3.7 branch only. Avoids "PreferenceItem' is obsolete: '[PreferenceItem] is deprecated. Use [SettingsProvider] instead." + +// Original contribution by: Mitch Thompson + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEWHIERARCHYWINDOWCALLBACKS +#endif + +#if UNITY_2018_3_OR_NEWER +#define NEW_PREFERENCES_SETTINGS_PROVIDER +#endif + +#if UNITY_2017_1_OR_NEWER +#define BUILT_IN_SPRITE_MASK_COMPONENT +#endif + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + using EventType = UnityEngine.EventType; + + // Analysis disable once ConvertToStaticType + [InitializeOnLoad] + public partial class SpineEditorUtilities : AssetPostprocessor { + + public static string editorPath = ""; + public static string editorGUIPath = ""; + public static bool initialized; + private static List texturesWithoutMetaFile = new List(); + + // Auto-import entry point for textures + void OnPreprocessTexture () { + #if UNITY_2018_1_OR_NEWER + bool customTextureSettingsExist = !assetImporter.importSettingsMissing; + #else + bool customTextureSettingsExist = System.IO.File.Exists(assetImporter.assetPath + ".meta"); + #endif + if (!customTextureSettingsExist) { + texturesWithoutMetaFile.Add(assetImporter.assetPath); + } + } + + // Auto-import post process entry point for all assets + static void OnPostprocessAllAssets (string[] imported, string[] deleted, string[] moved, string[] movedFromAssetPaths) { + if (imported.Length == 0) + return; + + // we copy the list here to prevent nested calls to OnPostprocessAllAssets() triggering a Clear() of the list + // in the middle of execution. + var texturesWithoutMetaFileCopy = new List(texturesWithoutMetaFile); + AssetUtility.HandleOnPostprocessAllAssets(imported, texturesWithoutMetaFileCopy); + texturesWithoutMetaFile.Clear(); + } + +#region Initialization + static SpineEditorUtilities () { + EditorApplication.delayCall += Initialize; // delayed so that AssetDatabase is ready. + } + + static void Initialize () { + // Note: Preferences need to be loaded when changing play mode + // to initialize handle scale correctly. + #if !NEW_PREFERENCES_SETTINGS_PROVIDER + Preferences.Load(); + #else + SpinePreferences.Load(); + #endif + + if (EditorApplication.isPlayingOrWillChangePlaymode) return; + + string[] assets = AssetDatabase.FindAssets("t:script SpineEditorUtilities"); + string assetPath = AssetDatabase.GUIDToAssetPath(assets[0]); + editorPath = Path.GetDirectoryName(assetPath).Replace('\\', '/'); + + assets = AssetDatabase.FindAssets("t:texture icon-subMeshRenderer"); + if (assets.Length > 0) { + assetPath = AssetDatabase.GUIDToAssetPath(assets[0]); + editorGUIPath = Path.GetDirectoryName(assetPath).Replace('\\', '/'); + } + else { + editorGUIPath = editorPath.Replace("/Utility", "/GUI"); + } + Icons.Initialize(); + + // Drag and Drop + #if UNITY_2019_1_OR_NEWER + SceneView.duringSceneGui -= DragAndDropInstantiation.SceneViewDragAndDrop; + SceneView.duringSceneGui += DragAndDropInstantiation.SceneViewDragAndDrop; + #else + SceneView.onSceneGUIDelegate -= DragAndDropInstantiation.SceneViewDragAndDrop; + SceneView.onSceneGUIDelegate += DragAndDropInstantiation.SceneViewDragAndDrop; + #endif + + EditorApplication.hierarchyWindowItemOnGUI -= HierarchyHandler.HandleDragAndDrop; + EditorApplication.hierarchyWindowItemOnGUI += HierarchyHandler.HandleDragAndDrop; + + // Hierarchy Icons + #if NEWPLAYMODECALLBACKS + EditorApplication.playModeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged; + EditorApplication.playModeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged; + HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); + #else + EditorApplication.playmodeStateChanged -= HierarchyHandler.IconsOnPlaymodeStateChanged; + EditorApplication.playmodeStateChanged += HierarchyHandler.IconsOnPlaymodeStateChanged; + HierarchyHandler.IconsOnPlaymodeStateChanged(); + #endif + + // Data Refresh Edit Mode. + // This prevents deserialized SkeletonData from persisting from play mode to edit mode. + #if NEWPLAYMODECALLBACKS + EditorApplication.playModeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged; + EditorApplication.playModeStateChanged += DataReloadHandler.OnPlaymodeStateChanged; + DataReloadHandler.OnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); + #else + EditorApplication.playmodeStateChanged -= DataReloadHandler.OnPlaymodeStateChanged; + EditorApplication.playmodeStateChanged += DataReloadHandler.OnPlaymodeStateChanged; + DataReloadHandler.OnPlaymodeStateChanged(); + #endif + + if (SpineEditorUtilities.Preferences.textureImporterWarning) { + IssueWarningsForUnrecommendedTextureSettings(); + } + + initialized = true; + } + + public static void ConfirmInitialization () { + if (!initialized || Icons.skeleton == null) + Initialize(); + } + + public static void IssueWarningsForUnrecommendedTextureSettings() { + + string[] atlasDescriptionGUIDs = AssetDatabase.FindAssets("t:textasset .atlas"); // Note: finds ".atlas.txt" but also ".atlas 1.txt" files. + for (int i = 0; i < atlasDescriptionGUIDs.Length; ++i) { + string atlasDescriptionPath = AssetDatabase.GUIDToAssetPath(atlasDescriptionGUIDs[i]); + if (!atlasDescriptionPath.EndsWith(".atlas.txt")) + continue; + + string texturePath = atlasDescriptionPath.Replace(".atlas.txt", ".png"); + + bool textureExists = IssueWarningsForUnrecommendedTextureSettings(texturePath); + if (!textureExists) { + texturePath = texturePath.Replace(".png", ".jpg"); + textureExists = IssueWarningsForUnrecommendedTextureSettings(texturePath); + } + if (!textureExists) { + continue; + } + } + } + + public static void ReloadSkeletonDataAssetAndComponent (SkeletonRenderer component) { + if (component == null) return; + ReloadSkeletonDataAsset(component.skeletonDataAsset); + ReinitializeComponent(component); + } + + public static void ReloadSkeletonDataAssetAndComponent (SkeletonGraphic component) { + if (component == null) return; + ReloadSkeletonDataAsset(component.skeletonDataAsset); + // Reinitialize. + ReinitializeComponent(component); + } + + public static void ReloadSkeletonDataAsset (SkeletonDataAsset skeletonDataAsset) { + if (skeletonDataAsset != null) { + foreach (AtlasAssetBase aa in skeletonDataAsset.atlasAssets) { + if (aa != null) aa.Clear(); + } + skeletonDataAsset.Clear(); + } + skeletonDataAsset.GetSkeletonData(true); + } + + public static void ReinitializeComponent (SkeletonRenderer component) { + if (component == null) return; + if (!SkeletonDataAssetIsValid(component.SkeletonDataAsset)) return; + + var stateComponent = component as IAnimationStateComponent; + AnimationState oldAnimationState = null; + if (stateComponent != null) { + oldAnimationState = stateComponent.AnimationState; + } + + component.Initialize(true); // implicitly clears any subscribers + + if (oldAnimationState != null) { + stateComponent.AnimationState.AssignEventSubscribersFrom(oldAnimationState); + } + + #if BUILT_IN_SPRITE_MASK_COMPONENT + SpineMaskUtilities.EditorAssignSpriteMaskMaterials(component); + #endif + component.LateUpdate(); + } + + public static void ReinitializeComponent (SkeletonGraphic component) { + if (component == null) return; + if (!SkeletonDataAssetIsValid(component.SkeletonDataAsset)) return; + component.Initialize(true); + component.LateUpdate(); + } + + public static bool SkeletonDataAssetIsValid (SkeletonDataAsset asset) { + return asset != null && asset.GetSkeletonData(quiet: true) != null; + } + + public static bool IssueWarningsForUnrecommendedTextureSettings(string texturePath) + { + TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath); + if (texImporter == null) { + return false; + } + + int extensionPos = texturePath.LastIndexOf('.'); + string materialPath = texturePath.Substring(0, extensionPos) + "_Material.mat"; + Material material = AssetDatabase.LoadAssetAtPath(materialPath); + + if (material == null) + return true; + + string errorMessage = null; + if (MaterialChecks.IsTextureSetupProblematic(material, PlayerSettings.colorSpace, + texImporter. sRGBTexture, texImporter. mipmapEnabled, texImporter. alphaIsTransparency, + texturePath, materialPath, ref errorMessage)) { + Debug.LogWarning(errorMessage, material); + } + return true; + } + #endregion + + public static class HierarchyHandler { + static Dictionary skeletonRendererTable = new Dictionary(); + static Dictionary skeletonUtilityBoneTable = new Dictionary(); + static Dictionary boundingBoxFollowerTable = new Dictionary(); + static Dictionary boundingBoxFollowerGraphicTable = new Dictionary(); + +#if NEWPLAYMODECALLBACKS + internal static void IconsOnPlaymodeStateChanged (PlayModeStateChange stateChange) { +#else + internal static void IconsOnPlaymodeStateChanged () { +#endif + skeletonRendererTable.Clear(); + skeletonUtilityBoneTable.Clear(); + boundingBoxFollowerTable.Clear(); + boundingBoxFollowerGraphicTable.Clear(); + +#if NEWHIERARCHYWINDOWCALLBACKS + EditorApplication.hierarchyChanged -= IconsOnChanged; +#else + EditorApplication.hierarchyWindowChanged -= IconsOnChanged; +#endif + EditorApplication.hierarchyWindowItemOnGUI -= IconsOnGUI; + + if (!Application.isPlaying && Preferences.showHierarchyIcons) { +#if NEWHIERARCHYWINDOWCALLBACKS + EditorApplication.hierarchyChanged += IconsOnChanged; +#else + EditorApplication.hierarchyWindowChanged += IconsOnChanged; +#endif + EditorApplication.hierarchyWindowItemOnGUI += IconsOnGUI; + IconsOnChanged(); + } + } + + internal static void IconsOnChanged () { + skeletonRendererTable.Clear(); + skeletonUtilityBoneTable.Clear(); + boundingBoxFollowerTable.Clear(); + boundingBoxFollowerGraphicTable.Clear(); + + SkeletonRenderer[] arr = Object.FindObjectsOfType(); + foreach (SkeletonRenderer r in arr) + skeletonRendererTable[r.gameObject.GetInstanceID()] = r.gameObject; + + SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType(); + foreach (SkeletonUtilityBone b in boneArr) + skeletonUtilityBoneTable[b.gameObject.GetInstanceID()] = b; + + BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType(); + foreach (BoundingBoxFollower bbf in bbfArr) + boundingBoxFollowerTable[bbf.gameObject.GetInstanceID()] = bbf; + + BoundingBoxFollowerGraphic[] bbfgArr = Object.FindObjectsOfType(); + foreach (BoundingBoxFollowerGraphic bbf in bbfgArr) + boundingBoxFollowerGraphicTable[bbf.gameObject.GetInstanceID()] = bbf; + } + + internal static void IconsOnGUI (int instanceId, Rect selectionRect) { + Rect r = new Rect(selectionRect); + if (skeletonRendererTable.ContainsKey(instanceId)) { + r.x = r.width - 15; + r.width = 15; + GUI.Label(r, Icons.spine); + } else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) { + r.x -= 26; + if (skeletonUtilityBoneTable[instanceId] != null) { + if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0) + r.x += 13; + r.y += 2; + r.width = 13; + r.height = 13; + if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) + GUI.DrawTexture(r, Icons.bone); + else + GUI.DrawTexture(r, Icons.poseBones); + } + } else if (boundingBoxFollowerTable.ContainsKey(instanceId)) { + r.x -= 26; + if (boundingBoxFollowerTable[instanceId] != null) { + if (boundingBoxFollowerTable[instanceId].transform.childCount == 0) + r.x += 13; + r.y += 2; + r.width = 13; + r.height = 13; + GUI.DrawTexture(r, Icons.boundingBox); + } + } else if (boundingBoxFollowerGraphicTable.ContainsKey(instanceId)) { + r.x -= 26; + if (boundingBoxFollowerGraphicTable[instanceId] != null) { + if (boundingBoxFollowerGraphicTable[instanceId].transform.childCount == 0) + r.x += 13; + r.y += 2; + r.width = 13; + r.height = 13; + GUI.DrawTexture(r, Icons.boundingBox); + } + } + } + + internal static void HandleDragAndDrop (int instanceId, Rect selectionRect) { + // HACK: Uses EditorApplication.hierarchyWindowItemOnGUI. + // Only works when there is at least one item in the scene. + var current = UnityEngine.Event.current; + var eventType = current.type; + bool isDraggingEvent = eventType == EventType.DragUpdated; + bool isDropEvent = eventType == EventType.DragPerform; + UnityEditor.DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + + if (isDraggingEvent || isDropEvent) { + var mouseOverWindow = EditorWindow.mouseOverWindow; + if (mouseOverWindow != null) { + + // One, existing, valid SkeletonDataAsset + var references = UnityEditor.DragAndDrop.objectReferences; + if (references.Length == 1) { + var skeletonDataAsset = references[0] as SkeletonDataAsset; + if (skeletonDataAsset != null && skeletonDataAsset.GetSkeletonData(true) != null) { + + // Allow drag-and-dropping anywhere in the Hierarchy Window. + // HACK: string-compare because we can't get its type via reflection. + const string HierarchyWindow = "UnityEditor.SceneHierarchyWindow"; + const string GenericDataTargetID = "target"; + if (HierarchyWindow.Equals(mouseOverWindow.GetType().ToString(), System.StringComparison.Ordinal)) { + if (isDraggingEvent) { + var mouseOverTarget = UnityEditor.EditorUtility.InstanceIDToObject(instanceId); + if (mouseOverTarget) + DragAndDrop.SetGenericData(GenericDataTargetID, mouseOverTarget); + // Note: do not call current.Use(), otherwise we get the wrong drop-target parent. + } else if (isDropEvent) { + var parentGameObject = DragAndDrop.GetGenericData(GenericDataTargetID) as UnityEngine.GameObject; + Transform parent = parentGameObject != null ? parentGameObject.transform : null; + // when dragging into empty space in hierarchy below last node, last node would be parent. + if (IsLastNodeInHierarchy(parent)) + parent = null; + DragAndDropInstantiation.ShowInstantiateContextMenu(skeletonDataAsset, Vector3.zero, parent); + UnityEditor.DragAndDrop.AcceptDrag(); + current.Use(); + return; + } + } + } + } + } + } + } + + internal static bool IsLastNodeInHierarchy (Transform node) { + if (node == null) + return false; + + while (node.parent != null) { + if (node.GetSiblingIndex() != node.parent.childCount - 1) + return false; + node = node.parent; + } + + var rootNodes = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); + bool isLastNode = (rootNodes.Length > 0 && rootNodes[rootNodes.Length - 1].transform == node); + return isLastNode; + } + } + } + + public class TextureModificationWarningProcessor : UnityEditor.AssetModificationProcessor + { + static string[] OnWillSaveAssets(string[] paths) + { + if (SpineEditorUtilities.Preferences.textureImporterWarning) { + foreach (string path in paths) { + if ((path != null) && + (path.EndsWith(".png.meta", System.StringComparison.Ordinal) || + path.EndsWith(".jpg.meta", System.StringComparison.Ordinal))) { + + string texturePath = System.IO.Path.ChangeExtension(path, null); // .meta removed + string atlasPath = System.IO.Path.ChangeExtension(texturePath, "atlas.txt"); + if (System.IO.File.Exists(atlasPath)) + SpineEditorUtilities.IssueWarningsForUnrecommendedTextureSettings(texturePath); + } + } + } + return paths; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs.meta new file mode 100644 index 0000000..544e477 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineEditorUtilities.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f834d5cd806ec4645915ac315edbdc60 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs new file mode 100644 index 0000000..84f3827 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs @@ -0,0 +1,501 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; +using System.Globalization; + +namespace Spine.Unity.Editor { + using EventType = UnityEngine.EventType; + + public static class SpineHandles { + public static Color BoneColor { get { return new Color(0.8f, 0.8f, 0.8f, 0.4f); } } + public static Color PathColor { get { return new Color(254/255f, 127/255f, 0); } } + public static Color TransformContraintColor { get { return new Color(170/255f, 226/255f, 35/255f); } } + public static Color IkColor { get { return new Color(228/255f,90/255f,43/255f); } } + public static Color PointColor { get { return new Color(1f, 1f, 0f, 1f); } } + + static Vector3[] _boneMeshVerts = { + new Vector3(0, 0, 0), + new Vector3(0.1f, 0.1f, 0), + new Vector3(1, 0, 0), + new Vector3(0.1f, -0.1f, 0) + }; + static Mesh _boneMesh; + public static Mesh BoneMesh { + get { + if (_boneMesh == null) { + _boneMesh = new Mesh { + vertices = _boneMeshVerts, + uv = new Vector2[4], + triangles = new [] { 0, 1, 2, 2, 3, 0 } + }; + _boneMesh.RecalculateBounds(); + _boneMesh.RecalculateNormals(); + } + return _boneMesh; + } + } + + static Mesh _arrowheadMesh; + public static Mesh ArrowheadMesh { + get { + if (_arrowheadMesh == null) { + _arrowheadMesh = new Mesh { + vertices = new [] { + new Vector3(0, 0), + new Vector3(-0.1f, 0.05f), + new Vector3(-0.1f, -0.05f) + }, + uv = new Vector2[3], + triangles = new [] { 0, 1, 2 } + }; + _arrowheadMesh.RecalculateBounds(); + _arrowheadMesh.RecalculateNormals(); + } + return _arrowheadMesh; + } + } + + static Material _boneMaterial; + static Material BoneMaterial { + get { + if (_boneMaterial == null) { + _boneMaterial = new Material(Shader.Find("Hidden/Spine/Bones")); + _boneMaterial.SetColor("_Color", SpineHandles.BoneColor); + } + + return _boneMaterial; + } + } + public static Material GetBoneMaterial () { + BoneMaterial.SetColor("_Color", SpineHandles.BoneColor); + return BoneMaterial; + } + + public static Material GetBoneMaterial (Color color) { + BoneMaterial.SetColor("_Color", color); + return BoneMaterial; + } + + static Material _ikMaterial; + public static Material IKMaterial { + get { + if (_ikMaterial == null) { + _ikMaterial = new Material(Shader.Find("Hidden/Spine/Bones")); + _ikMaterial.SetColor("_Color", SpineHandles.IkColor); + } + return _ikMaterial; + } + } + + static GUIStyle _boneNameStyle; + public static GUIStyle BoneNameStyle { + get { + if (_boneNameStyle == null) { + _boneNameStyle = new GUIStyle(EditorStyles.whiteMiniLabel) { + alignment = TextAnchor.MiddleCenter, + stretchWidth = true, + padding = new RectOffset(0, 0, 0, 0), + contentOffset = new Vector2(-5f, 0f) + }; + } + return _boneNameStyle; + } + } + + static GUIStyle _pathNameStyle; + public static GUIStyle PathNameStyle { + get { + if (_pathNameStyle == null) { + _pathNameStyle = new GUIStyle(SpineHandles.BoneNameStyle); + _pathNameStyle.normal.textColor = SpineHandles.PathColor; + } + return _pathNameStyle; + } + } + + static GUIStyle _pointNameStyle; + public static GUIStyle PointNameStyle { + get { + if (_pointNameStyle == null) { + _pointNameStyle = new GUIStyle(SpineHandles.BoneNameStyle); + _pointNameStyle.normal.textColor = SpineHandles.PointColor; + } + return _pointNameStyle; + } + } + + public static void DrawBoneNames (Transform transform, Skeleton skeleton, float positionScale = 1f) { + GUIStyle style = BoneNameStyle; + foreach (Bone b in skeleton.Bones) { + if (!b.Active) continue; + var pos = new Vector3(b.WorldX * positionScale, b.WorldY * positionScale, 0) + (new Vector3(b.A, b.C) * (b.Data.Length * 0.5f)); + pos = transform.TransformPoint(pos); + Handles.Label(pos, b.Data.Name, style); + } + } + + public static void DrawBones (Transform transform, Skeleton skeleton, float positionScale = 1f) { + float boneScale = 1.8f; // Draw the root bone largest; + DrawCrosshairs2D(skeleton.Bones.Items[0].GetWorldPosition(transform), 0.08f, positionScale); + + foreach (Bone b in skeleton.Bones) { + if (!b.Active) continue; + DrawBone(transform, b, boneScale, positionScale); + boneScale = 1f; + } + } + + static Vector3[] _boneWireBuffer = new Vector3[5]; + static Vector3[] GetBoneWireBuffer (Matrix4x4 m) { + for (int i = 0, n = _boneMeshVerts.Length; i < n; i++) + _boneWireBuffer[i] = m.MultiplyPoint(_boneMeshVerts[i]); + + _boneWireBuffer[4] = _boneWireBuffer[0]; // closed polygon. + return _boneWireBuffer; + } + public static void DrawBoneWireframe (Transform transform, Bone b, Color color, float skeletonRenderScale = 1f) { + Handles.color = color; + var pos = new Vector3(b.WorldX * skeletonRenderScale, b.WorldY * skeletonRenderScale, 0); + float length = b.Data.Length; + + if (length > 0) { + Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotationX); + Vector3 scale = Vector3.one * length * b.WorldScaleX * skeletonRenderScale; + const float my = 1.5f; + scale.y *= (SpineEditorUtilities.Preferences.handleScale + 1) * 0.5f; + scale.y = Mathf.Clamp(scale.x, -my * skeletonRenderScale, my * skeletonRenderScale); + Handles.DrawPolyLine(GetBoneWireBuffer(transform.localToWorldMatrix * Matrix4x4.TRS(pos, rot, scale))); + var wp = transform.TransformPoint(pos); + DrawBoneCircle(wp, color, transform.forward, skeletonRenderScale); + } else { + var wp = transform.TransformPoint(pos); + DrawBoneCircle(wp, color, transform.forward, skeletonRenderScale); + } + } + + public static void DrawBone (Transform transform, Bone b, float boneScale, float skeletonRenderScale = 1f) { + var pos = new Vector3(b.WorldX * skeletonRenderScale, b.WorldY * skeletonRenderScale, 0); + float length = b.Data.Length; + if (length > 0) { + Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotationX); + Vector3 scale = Vector3.one * length * b.WorldScaleX * skeletonRenderScale; + const float my = 1.5f; + scale.y *= (SpineEditorUtilities.Preferences.handleScale + 1f) * 0.5f; + scale.y = Mathf.Clamp(scale.x, -my * skeletonRenderScale, my * skeletonRenderScale); + SpineHandles.GetBoneMaterial().SetPass(0); + Graphics.DrawMeshNow(SpineHandles.BoneMesh, transform.localToWorldMatrix * Matrix4x4.TRS(pos, rot, scale)); + } else { + var wp = transform.TransformPoint(pos); + DrawBoneCircle(wp, SpineHandles.BoneColor, transform.forward, boneScale * skeletonRenderScale); + } + } + + public static void DrawBone (Transform transform, Bone b, float boneScale, Color color, float skeletonRenderScale = 1f) { + var pos = new Vector3(b.WorldX * skeletonRenderScale, b.WorldY * skeletonRenderScale, 0); + float length = b.Data.Length; + if (length > 0) { + Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotationX); + Vector3 scale = Vector3.one * length * b.WorldScaleX; + const float my = 1.5f; + scale.y *= (SpineEditorUtilities.Preferences.handleScale + 1f) * 0.5f; + scale.y = Mathf.Clamp(scale.x, -my, my); + SpineHandles.GetBoneMaterial(color).SetPass(0); + Graphics.DrawMeshNow(SpineHandles.BoneMesh, transform.localToWorldMatrix * Matrix4x4.TRS(pos, rot, scale)); + } else { + var wp = transform.TransformPoint(pos); + DrawBoneCircle(wp, color, transform.forward, boneScale * skeletonRenderScale); + } + } + + public static void DrawPaths (Transform transform, Skeleton skeleton) { + foreach (Slot s in skeleton.DrawOrder) { + var p = s.Attachment as PathAttachment; + if (p != null) SpineHandles.DrawPath(s, p, transform, true); + } + } + + static float[] pathVertexBuffer; + public static void DrawPath (Slot s, PathAttachment p, Transform t, bool includeName) { + int worldVerticesLength = p.WorldVerticesLength; + + if (pathVertexBuffer == null || pathVertexBuffer.Length < worldVerticesLength) + pathVertexBuffer = new float[worldVerticesLength]; + + float[] pv = pathVertexBuffer; + p.ComputeWorldVertices(s, pv); + + var ocolor = Handles.color; + Handles.color = SpineHandles.PathColor; + + Matrix4x4 m = t.localToWorldMatrix; + const int step = 6; + int n = worldVerticesLength - step; + Vector3 p0, p1, p2, p3; + for (int i = 2; i < n; i += step) { + p0 = m.MultiplyPoint(new Vector3(pv[i], pv[i+1])); + p1 = m.MultiplyPoint(new Vector3(pv[i+2], pv[i+3])); + p2 = m.MultiplyPoint(new Vector3(pv[i+4], pv[i+5])); + p3 = m.MultiplyPoint(new Vector3(pv[i+6], pv[i+7])); + DrawCubicBezier(p0, p1, p2, p3); + } + + n += step; + if (p.Closed) { + p0 = m.MultiplyPoint(new Vector3(pv[n - 4], pv[n - 3])); + p1 = m.MultiplyPoint(new Vector3(pv[n - 2], pv[n - 1])); + p2 = m.MultiplyPoint(new Vector3(pv[0], pv[1])); + p3 = m.MultiplyPoint(new Vector3(pv[2], pv[3])); + DrawCubicBezier(p0, p1, p2, p3); + } + + const float endCapSize = 0.05f; + Vector3 firstPoint = m.MultiplyPoint(new Vector3(pv[2], pv[3])); + SpineHandles.DrawDot(firstPoint, endCapSize); + + //if (!p.Closed) SpineHandles.DrawDot(m.MultiplyPoint(new Vector3(pv[n - 4], pv[n - 3])), endCapSize); + if (includeName) Handles.Label(firstPoint + new Vector3(0,0.1f), p.Name, PathNameStyle); + + Handles.color = ocolor; + } + + public static void DrawDot (Vector3 position, float size) { + Handles.DotHandleCap(0, position, Quaternion.identity, size * HandleUtility.GetHandleSize(position), EventType.Ignore); //Handles.DotCap(0, position, Quaternion.identity, size * HandleUtility.GetHandleSize(position)); + } + + public static void DrawBoundingBoxes (Transform transform, Skeleton skeleton) { + foreach (var slot in skeleton.Slots) { + var bba = slot.Attachment as BoundingBoxAttachment; + if (bba != null) SpineHandles.DrawBoundingBox(slot, bba, transform); + } + } + + public static void DrawBoundingBox (Slot slot, BoundingBoxAttachment box, Transform t) { + if (box.Vertices.Length <= 2) return; // Handle cases where user creates a BoundingBoxAttachment but doesn't actually define it. + + var worldVerts = new float[box.WorldVerticesLength]; + box.ComputeWorldVertices(slot, worldVerts); + + Handles.color = Color.green; + Vector3 lastVert = Vector3.zero; + Vector3 vert = Vector3.zero; + Vector3 firstVert = t.TransformPoint(new Vector3(worldVerts[0], worldVerts[1], 0)); + for (int i = 0; i < worldVerts.Length; i += 2) { + vert.x = worldVerts[i]; + vert.y = worldVerts[i + 1]; + vert.z = 0; + + vert = t.TransformPoint(vert); + + if (i > 0) + Handles.DrawLine(lastVert, vert); + + lastVert = vert; + } + + Handles.DrawLine(lastVert, firstVert); + } + + public static void DrawPointAttachment (Bone bone, PointAttachment pointAttachment, Transform skeletonTransform) { + if (bone == null) return; + if (pointAttachment == null) return; + + Vector2 localPos; + pointAttachment.ComputeWorldPosition(bone, out localPos.x, out localPos.y); + float localRotation = pointAttachment.ComputeWorldRotation(bone); + Matrix4x4 m = Matrix4x4.TRS(localPos, Quaternion.Euler(0, 0, localRotation), Vector3.one) * Matrix4x4.TRS(Vector3.right * 0.25f, Quaternion.identity, Vector3.one); + + DrawBoneCircle(skeletonTransform.TransformPoint(localPos), SpineHandles.PointColor, Vector3.back, 1.3f); + DrawArrowhead(skeletonTransform.localToWorldMatrix * m); + } + + public static void DrawConstraints (Transform transform, Skeleton skeleton, float skeletonRenderScale = 1f) { + Vector3 targetPos; + Vector3 pos; + bool active; + Color handleColor; + const float Thickness = 4f; + Vector3 normal = transform.forward; + + // Transform Constraints + handleColor = SpineHandles.TransformContraintColor; + foreach (var tc in skeleton.TransformConstraints) { + var targetBone = tc.Target; + targetPos = targetBone.GetWorldPosition(transform, skeletonRenderScale); + + if (tc.TranslateMix > 0) { + if (tc.TranslateMix != 1f) { + Handles.color = handleColor; + foreach (var b in tc.Bones) { + pos = b.GetWorldPosition(transform, skeletonRenderScale); + Handles.DrawDottedLine(targetPos, pos, Thickness); + } + } + SpineHandles.DrawBoneCircle(targetPos, handleColor, normal, 1.3f * skeletonRenderScale); + Handles.color = handleColor; + SpineHandles.DrawCrosshairs(targetPos, 0.2f, targetBone.A, targetBone.B, targetBone.C, targetBone.D, transform, skeletonRenderScale); + } + } + + // IK Constraints + handleColor = SpineHandles.IkColor; + foreach (var ikc in skeleton.IkConstraints) { + Bone targetBone = ikc.Target; + targetPos = targetBone.GetWorldPosition(transform, skeletonRenderScale); + var bones = ikc.Bones; + active = ikc.Mix > 0; + if (active) { + pos = bones.Items[0].GetWorldPosition(transform, skeletonRenderScale); + switch (bones.Count) { + case 1: { + Handles.color = handleColor; + Handles.DrawLine(targetPos, pos); + SpineHandles.DrawBoneCircle(targetPos, handleColor, normal); + var m = bones.Items[0].GetMatrix4x4(); + m.m03 = targetBone.WorldX * skeletonRenderScale; + m.m13 = targetBone.WorldY * skeletonRenderScale; + SpineHandles.DrawArrowhead(transform.localToWorldMatrix * m); + break; + } + case 2: { + Bone childBone = bones.Items[1]; + Vector3 child = childBone.GetWorldPosition(transform, skeletonRenderScale); + Handles.color = handleColor; + Handles.DrawLine(child, pos); + Handles.DrawLine(targetPos, child); + SpineHandles.DrawBoneCircle(pos, handleColor, normal, 0.5f); + SpineHandles.DrawBoneCircle(child, handleColor, normal, 0.5f); + SpineHandles.DrawBoneCircle(targetPos, handleColor, normal); + var m = childBone.GetMatrix4x4(); + m.m03 = targetBone.WorldX * skeletonRenderScale; + m.m13 = targetBone.WorldY * skeletonRenderScale; + SpineHandles.DrawArrowhead(transform.localToWorldMatrix * m); + break; + } + } + } + //Handles.Label(targetPos, ikc.Data.Name, SpineHandles.BoneNameStyle); + } + + // Path Constraints + handleColor = SpineHandles.PathColor; + foreach (var pc in skeleton.PathConstraints) { + active = pc.TranslateMix > 0; + if (active) + foreach (var b in pc.Bones) + SpineHandles.DrawBoneCircle(b.GetWorldPosition(transform, skeletonRenderScale), handleColor, normal, 1f * skeletonRenderScale); + } + } + + static void DrawCrosshairs2D (Vector3 position, float scale, float skeletonRenderScale = 1f) { + scale *= SpineEditorUtilities.Preferences.handleScale * skeletonRenderScale; + Handles.DrawLine(position + new Vector3(-scale, 0), position + new Vector3(scale, 0)); + Handles.DrawLine(position + new Vector3(0, -scale), position + new Vector3(0, scale)); + } + + static void DrawCrosshairs (Vector3 position, float scale, float a, float b, float c, float d, Transform transform, float skeletonRenderScale = 1f) { + scale *= SpineEditorUtilities.Preferences.handleScale * skeletonRenderScale; + + var xOffset = (Vector3)(new Vector2(a, c).normalized * scale); + var yOffset = (Vector3)(new Vector2(b, d).normalized * scale); + xOffset = transform.TransformDirection(xOffset); + yOffset = transform.TransformDirection(yOffset); + + Handles.DrawLine(position + xOffset, position - xOffset); + Handles.DrawLine(position + yOffset, position - yOffset); + } + + static void DrawArrowhead2D (Vector3 pos, float localRotation, float scale = 1f) { + scale *= SpineEditorUtilities.Preferences.handleScale; + + SpineHandles.IKMaterial.SetPass(0); + Graphics.DrawMeshNow(SpineHandles.ArrowheadMesh, Matrix4x4.TRS(pos, Quaternion.Euler(0, 0, localRotation), new Vector3(scale, scale, scale))); + } + + static void DrawArrowhead (Vector3 pos, Quaternion worldQuaternion) { + Graphics.DrawMeshNow(SpineHandles.ArrowheadMesh, pos, worldQuaternion, 0); + } + + static void DrawArrowhead (Matrix4x4 m) { + float s = SpineEditorUtilities.Preferences.handleScale; + m.m00 *= s; + m.m01 *= s; + m.m02 *= s; + m.m10 *= s; + m.m11 *= s; + m.m12 *= s; + m.m20 *= s; + m.m21 *= s; + m.m22 *= s; + + SpineHandles.IKMaterial.SetPass(0); + Graphics.DrawMeshNow(SpineHandles.ArrowheadMesh, m); + } + + static void DrawBoneCircle (Vector3 pos, Color outlineColor, Vector3 normal, float scale = 1f) { + scale *= SpineEditorUtilities.Preferences.handleScale; + + Color o = Handles.color; + Handles.color = outlineColor; + float firstScale = 0.08f * scale; + Handles.DrawSolidDisc(pos, normal, firstScale); + const float Thickness = 0.03f; + float secondScale = firstScale - (Thickness * SpineEditorUtilities.Preferences.handleScale * scale); + + if (secondScale > 0f) { + Handles.color = new Color(0.3f, 0.3f, 0.3f, 0.5f); + Handles.DrawSolidDisc(pos, normal, secondScale); + } + + Handles.color = o; + } + + internal static void DrawCubicBezier (Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) { + Handles.DrawBezier(p0, p3, p1, p2, Handles.color, Texture2D.whiteTexture, 2f); + // const float dotSize = 0.01f; + // Quaternion q = Quaternion.identity; + // Handles.DotCap(0, p0, q, dotSize); + // Handles.DotCap(0, p1, q, dotSize); + // Handles.DotCap(0, p2, q, dotSize); + // Handles.DotCap(0, p3, q, dotSize); + // Handles.DrawLine(p0, p1); + // Handles.DrawLine(p3, p2); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs.meta new file mode 100644 index 0000000..6a1532b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineHandles.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f4c97e41d3d90e24bbb40d634e6cc336 +timeCreated: 1563313275 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs new file mode 100644 index 0000000..7842686 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs @@ -0,0 +1,376 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.Reflection; + +namespace Spine.Unity.Editor { + public static class SpineInspectorUtility { + + public static string Pluralize (int n, string singular, string plural) { + return n + " " + (n == 1 ? singular : plural); + } + + public static string PluralThenS (int n) { + return n == 1 ? "" : "s"; + } + + public static string EmDash { + get { return "\u2014"; } + } + + static GUIContent tempContent; + internal static GUIContent TempContent (string text, Texture2D image = null, string tooltip = null) { + if (tempContent == null) tempContent = new GUIContent(); + tempContent.text = text; + tempContent.image = image; + tempContent.tooltip = tooltip; + return tempContent; + } + + public static void PropertyFieldWideLabel (SerializedProperty property, GUIContent label = null, float minimumLabelWidth = 150) { + EditorGUIUtility.labelWidth = minimumLabelWidth; + EditorGUILayout.PropertyField(property, label ?? TempContent(property.displayName, null, property.tooltip)); + EditorGUIUtility.labelWidth = 0; // Resets to default + } + + public static void PropertyFieldFitLabel (SerializedProperty property, GUIContent label = null, float extraSpace = 5f) { + label = label ?? TempContent(property.displayName, null, property.tooltip); + float width = GUI.skin.label.CalcSize(TempContent(label.text)).x + extraSpace; + if (label.image != null) + width += EditorGUIUtility.singleLineHeight; + PropertyFieldWideLabel(property, label, width); + } + + /// Multi-edit-compatible version of EditorGUILayout.ToggleLeft(SerializedProperty) + public static void ToggleLeftLayout (SerializedProperty property, GUIContent label = null, float width = 120f) { + if (label == null) label = SpineInspectorUtility.TempContent(property.displayName, tooltip: property.tooltip); + + if (property.hasMultipleDifferentValues) { + bool previousShowMixedValue = EditorGUI.showMixedValue; + EditorGUI.showMixedValue = true; + + bool clicked = EditorGUILayout.ToggleLeft(label, property.boolValue, GUILayout.Width(width)); + if (clicked) property.boolValue = true; // Set all values to true when clicked. + + EditorGUI.showMixedValue = previousShowMixedValue; + } else { + property.boolValue = EditorGUILayout.ToggleLeft(label, property.boolValue, GUILayout.Width(width)); + } + } + + /// Multi-edit-compatible version of EditorGUILayout.ToggleLeft(SerializedProperty) + public static void ToggleLeft (Rect rect, SerializedProperty property, GUIContent label = null) { + if (label == null) label = SpineInspectorUtility.TempContent(property.displayName, tooltip: property.tooltip); + + if (property.hasMultipleDifferentValues) { + bool previousShowMixedValue = EditorGUI.showMixedValue; + EditorGUI.showMixedValue = true; + + bool clicked = EditorGUI.ToggleLeft(rect, label, property.boolValue); + if (clicked) property.boolValue = true; // Set all values to true when clicked. + + EditorGUI.showMixedValue = previousShowMixedValue; + } else { + property.boolValue = EditorGUI.ToggleLeft(rect, label, property.boolValue); + } + } + + public static bool UndoRedoPerformed (UnityEngine.Event current) { + return current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed"; + } + + public static Texture2D UnityIcon() { + return EditorGUIUtility.ObjectContent(null, typeof(T)).image as Texture2D; + } + + public static Texture2D UnityIcon(System.Type type) { + return EditorGUIUtility.ObjectContent(null, type).image as Texture2D; + } + + public static FieldInfo GetNonPublicField (System.Type type, string fieldName) { + return type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); + } + + #region SerializedProperty Helpers + public static SerializedProperty FindBaseOrSiblingProperty (this SerializedProperty property, string propertyName) { + if (string.IsNullOrEmpty(propertyName)) return null; + + SerializedProperty relativeProperty = property.serializedObject.FindProperty(propertyName); // baseProperty + + // If base property is not found, look for the sibling property. + if (relativeProperty == null) { + string propertyPath = property.propertyPath; + int localPathLength = property.name.Length; + + string newPropertyPath = propertyPath.Remove(propertyPath.Length - localPathLength, localPathLength) + propertyName; + relativeProperty = property.serializedObject.FindProperty(newPropertyPath); + + // If a direct sibling property was not found, try to find the sibling of the array. + if (relativeProperty == null && property.isArray) { + int propertyPathLength = propertyPath.Length; + + int dotCount = 0; + const int SiblingOfListDotCount = 3; + for (int i = 1; i < propertyPathLength; i++) { + if (propertyPath[propertyPathLength - i] == '.') { + dotCount++; + if (dotCount >= SiblingOfListDotCount) { + localPathLength = i - 1; + break; + } + } + } + + newPropertyPath = propertyPath.Remove(propertyPath.Length - localPathLength, localPathLength) + propertyName; + relativeProperty = property.serializedObject.FindProperty(newPropertyPath); + } + } + + return relativeProperty; + } + #endregion + + #region Layout Scopes + static GUIStyle grayMiniLabel; + public static GUIStyle GrayMiniLabel { + get { + if (grayMiniLabel == null) { + grayMiniLabel = new GUIStyle(EditorStyles.centeredGreyMiniLabel) { + alignment = TextAnchor.UpperLeft + }; + } + return grayMiniLabel; + } + } + + public class LabelWidthScope : System.IDisposable { + public LabelWidthScope (float minimumLabelWidth = 190f) { + EditorGUIUtility.labelWidth = minimumLabelWidth; + } + + public void Dispose () { + EditorGUIUtility.labelWidth = 0f; + } + } + + public class IndentScope : System.IDisposable { + public IndentScope () { EditorGUI.indentLevel++; } + public void Dispose () { EditorGUI.indentLevel--; } + } + + public class BoxScope : System.IDisposable { + readonly bool indent; + + static GUIStyle boxScopeStyle; + public static GUIStyle BoxScopeStyle { + get { + if (boxScopeStyle == null) { + boxScopeStyle = new GUIStyle(EditorStyles.helpBox); + RectOffset p = boxScopeStyle.padding; // RectOffset is a class + p.right += 6; + p.top += 1; + p.left += 3; + } + + return boxScopeStyle; + } + } + + public BoxScope (bool indent = true) { + this.indent = indent; + EditorGUILayout.BeginVertical(BoxScopeStyle); + if (indent) EditorGUI.indentLevel++; + } + + public void Dispose () { + if (indent) EditorGUI.indentLevel--; + EditorGUILayout.EndVertical(); + } + } + #endregion + + #region Button + const float CenterButtonMaxWidth = 270f; + const float CenterButtonHeight = 30f; + static GUIStyle spineButtonStyle; + static GUIStyle SpineButtonStyle { + get { + if (spineButtonStyle == null) { + spineButtonStyle = new GUIStyle(GUI.skin.button); + spineButtonStyle.padding = new RectOffset(10, 10, 10, 10); + } + return spineButtonStyle; + } + } + + public static bool LargeCenteredButton (string label, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { + if (sideSpace) { + bool clicked; + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + clicked = GUILayout.Button(label, SpineButtonStyle, GUILayout.MaxWidth(maxWidth), GUILayout.Height(CenterButtonHeight)); + EditorGUILayout.Space(); + } + EditorGUILayout.Space(); + return clicked; + } else { + return GUILayout.Button(label, GUILayout.MaxWidth(CenterButtonMaxWidth), GUILayout.Height(CenterButtonHeight)); + } + } + + public static bool LargeCenteredButton (GUIContent content, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { + if (sideSpace) { + bool clicked; + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + clicked = GUILayout.Button(content, SpineButtonStyle, GUILayout.MaxWidth(maxWidth), GUILayout.Height(CenterButtonHeight)); + EditorGUILayout.Space(); + } + EditorGUILayout.Space(); + return clicked; + } else { + return GUILayout.Button(content, GUILayout.MaxWidth(CenterButtonMaxWidth), GUILayout.Height(CenterButtonHeight)); + } + } + + public static bool CenteredButton (GUIContent content, float height = 20f, bool sideSpace = true, float maxWidth = CenterButtonMaxWidth) { + if (sideSpace) { + bool clicked; + using (new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.Space(); + clicked = GUILayout.Button(content, GUILayout.MaxWidth(maxWidth), GUILayout.Height(height)); + EditorGUILayout.Space(); + } + EditorGUILayout.Space(); + return clicked; + } else { + return GUILayout.Button(content, GUILayout.MaxWidth(maxWidth), GUILayout.Height(height)); + } + } + #endregion + + #region Multi-Editing Helpers + public static bool TargetsUseSameData (SerializedObject so) { + if (so.isEditingMultipleObjects) { + int n = so.targetObjects.Length; + var first = so.targetObjects[0] as IHasSkeletonDataAsset; + for (int i = 1; i < n; i++) { + var sr = so.targetObjects[i] as IHasSkeletonDataAsset; + if (sr != null && sr.SkeletonDataAsset != first.SkeletonDataAsset) + return false; + } + } + return true; + } + + public static SerializedObject GetRenderersSerializedObject (SerializedObject serializedObject) { + if (serializedObject.isEditingMultipleObjects) { + var renderers = new List(); + foreach (var o in serializedObject.targetObjects) { + var component = o as Component; + if (component != null) { + var renderer = component.GetComponent(); + if (renderer != null) + renderers.Add(renderer); + } + } + return new SerializedObject(renderers.ToArray()); + } else { + var component = serializedObject.targetObject as Component; + if (component != null) { + var renderer = component.GetComponent(); + if (renderer != null) + return new SerializedObject(renderer); + } + } + + return null; + } + #endregion + + #region Sorting Layer Field Helpers + static readonly GUIContent SortingLayerLabel = new GUIContent("Sorting Layer", "MeshRenderer.sortingLayerID"); + static readonly GUIContent OrderInLayerLabel = new GUIContent("Order in Layer", "MeshRenderer.sortingOrder"); + + static MethodInfo m_SortingLayerFieldMethod; + static MethodInfo SortingLayerFieldMethod { + get { + if (m_SortingLayerFieldMethod == null) + m_SortingLayerFieldMethod = typeof(EditorGUILayout).GetMethod("SortingLayerField", BindingFlags.Static | BindingFlags.NonPublic, null, new [] { typeof(GUIContent), typeof(SerializedProperty), typeof(GUIStyle) }, null); + + return m_SortingLayerFieldMethod; + } + } + + public struct SerializedSortingProperties { + public SerializedObject renderer; + public SerializedProperty sortingLayerID; + public SerializedProperty sortingOrder; + + public SerializedSortingProperties (Renderer r) : this(new SerializedObject(r)) {} + public SerializedSortingProperties (Object[] renderers) : this(new SerializedObject(renderers)) {} + + public SerializedSortingProperties (SerializedObject rendererSerializedObject) { + renderer = rendererSerializedObject; + sortingLayerID = renderer.FindProperty("m_SortingLayerID"); + sortingOrder = renderer.FindProperty("m_SortingOrder"); + } + + public void ApplyModifiedProperties () { + renderer.ApplyModifiedProperties(); + + // SetDirty + if (renderer.isEditingMultipleObjects) + foreach (var o in renderer.targetObjects) + EditorUtility.SetDirty(o); + else + EditorUtility.SetDirty(renderer.targetObject); + } + } + + public static void SortingPropertyFields (SerializedSortingProperties prop, bool applyModifiedProperties) { + if (applyModifiedProperties) + EditorGUI.BeginChangeCheck(); + + if (SpineInspectorUtility.SortingLayerFieldMethod != null && prop.sortingLayerID != null) + SpineInspectorUtility.SortingLayerFieldMethod.Invoke(null, new object[] { SortingLayerLabel, prop.sortingLayerID, EditorStyles.popup } ); + else + EditorGUILayout.PropertyField(prop.sortingLayerID); + + EditorGUILayout.PropertyField(prop.sortingOrder, OrderInLayerLabel); + + if (applyModifiedProperties && EditorGUI.EndChangeCheck()) + prop.ApplyModifiedProperties(); + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs.meta new file mode 100644 index 0000000..3219ca0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineInspectorUtility.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 663715b5714e2db499192c8d91ef1f86 +timeCreated: 1457404957 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs new file mode 100644 index 0000000..f3e3dc2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs @@ -0,0 +1,246 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#pragma warning disable 0219 + +#define SPINE_SKELETONMECANIM + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#if UNITY_2018 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEWHIERARCHYWINDOWCALLBACKS +#endif + +#if UNITY_2017_1_OR_NEWER +#define BUILT_IN_SPRITE_MASK_COMPONENT +#endif + +#if BUILT_IN_SPRITE_MASK_COMPONENT + +using UnityEngine; +using UnityEditor; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Linq; +using System.Reflection; + +namespace Spine.Unity.Editor { + + public class SpineMaskUtilities { + + private const string MATERIAL_FILENAME_SUFFIX_INSIDE_MASK = "_InsideMask"; + private const string MATERIAL_FILENAME_SUFFIX_OUTSIDE_MASK = "_OutsideMask"; + + public static void EditorAssignSpriteMaskMaterials(SkeletonRenderer skeleton) { + var maskMaterials = skeleton.maskMaterials; + var maskInteraction = skeleton.maskInteraction; + var meshRenderer = skeleton.GetComponent(); + + if (maskMaterials.materialsMaskDisabled.Length > 0 && maskMaterials.materialsMaskDisabled[0] != null && + maskInteraction == SpriteMaskInteraction.None) { + meshRenderer.materials = maskMaterials.materialsMaskDisabled; + } + else if (maskInteraction == SpriteMaskInteraction.VisibleInsideMask) { + if (maskMaterials.materialsInsideMask.Length == 0 || maskMaterials.materialsInsideMask[0] == null) + EditorInitSpriteMaskMaterialsInsideMask(skeleton); + meshRenderer.materials = maskMaterials.materialsInsideMask; + } + else if (maskInteraction == SpriteMaskInteraction.VisibleOutsideMask) { + if (maskMaterials.materialsOutsideMask.Length == 0 || maskMaterials.materialsOutsideMask[0] == null) + EditorInitSpriteMaskMaterialsOutsideMask(skeleton); + meshRenderer.materials = maskMaterials.materialsOutsideMask; + } + } + + public static bool AreMaskMaterialsMissing(SkeletonRenderer skeleton) { + var maskMaterials = skeleton.maskMaterials; + var maskInteraction = skeleton.maskInteraction; + + if (maskInteraction == SpriteMaskInteraction.VisibleInsideMask) { + return (maskMaterials.materialsInsideMask.Length == 0 || maskMaterials.materialsInsideMask[0] == null); + } + else if (maskInteraction == SpriteMaskInteraction.VisibleOutsideMask) { + return (maskMaterials.materialsOutsideMask.Length == 0 || maskMaterials.materialsOutsideMask[0] == null); + } + return false; + } + + public static void EditorInitMaskMaterials(SkeletonRenderer skeleton, SkeletonRenderer.SpriteMaskInteractionMaterials maskMaterials, SpriteMaskInteraction maskType) { + if (maskType == SpriteMaskInteraction.None) { + EditorConfirmDisabledMaskMaterialsInit(skeleton); + } + else if (maskType == SpriteMaskInteraction.VisibleInsideMask) { + EditorInitSpriteMaskMaterialsInsideMask(skeleton); + } + else if (maskType == SpriteMaskInteraction.VisibleOutsideMask) { + EditorInitSpriteMaskMaterialsOutsideMask(skeleton); + } + } + + public static void EditorDeleteMaskMaterials(SkeletonRenderer.SpriteMaskInteractionMaterials maskMaterials, SpriteMaskInteraction maskType) { + Material[] targetMaterials; + if (maskType == SpriteMaskInteraction.VisibleInsideMask) { + targetMaterials = maskMaterials.materialsInsideMask; + } + else if (maskType == SpriteMaskInteraction.VisibleOutsideMask) { + targetMaterials = maskMaterials.materialsOutsideMask; + } + else { + Debug.LogWarning("EditorDeleteMaskMaterials: Normal materials are kept as a reference and shall never be deleted."); + return; + } + + for (int i = 0; i < targetMaterials.Length; ++i) { + var material = targetMaterials[i]; + if (material != null) { + string materialPath = UnityEditor.AssetDatabase.GetAssetPath(material); + UnityEditor.AssetDatabase.DeleteAsset(materialPath); + Debug.Log(string.Concat("Deleted material '", materialPath, "'")); + } + } + + if (maskType == SpriteMaskInteraction.VisibleInsideMask) { + maskMaterials.materialsInsideMask = new Material[0]; + } + else if (maskType == SpriteMaskInteraction.VisibleOutsideMask) { + maskMaterials.materialsOutsideMask = new Material[0]; + } + } + + private static void EditorInitSpriteMaskMaterialsInsideMask(SkeletonRenderer skeleton) { + var maskMaterials = skeleton.maskMaterials; + EditorInitSpriteMaskMaterialsForMaskType(skeleton, SkeletonRenderer.STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE, + ref maskMaterials.materialsInsideMask); + } + + private static void EditorInitSpriteMaskMaterialsOutsideMask(SkeletonRenderer skeleton) { + var maskMaterials = skeleton.maskMaterials; + EditorInitSpriteMaskMaterialsForMaskType(skeleton, SkeletonRenderer.STENCIL_COMP_MASKINTERACTION_VISIBLE_OUTSIDE, + ref maskMaterials.materialsOutsideMask); + } + + private static void EditorInitSpriteMaskMaterialsForMaskType(SkeletonRenderer skeleton, UnityEngine.Rendering.CompareFunction maskFunction, + ref Material[] materialsToFill) { + if (!EditorConfirmDisabledMaskMaterialsInit(skeleton)) + return; + + var maskMaterials = skeleton.maskMaterials; + var originalMaterials = maskMaterials.materialsMaskDisabled; + materialsToFill = new Material[originalMaterials.Length]; + for (int i = 0; i < originalMaterials.Length; i++) { + Material newMaterial = null; + + if (!Application.isPlaying) { + newMaterial = EditorCreateOrLoadMaskMaterialAsset(maskMaterials, maskFunction, originalMaterials[i]); + } + if (newMaterial == null) { + newMaterial = new Material(originalMaterials[i]); + newMaterial.SetFloat(SkeletonRenderer.STENCIL_COMP_PARAM_ID, (int)maskFunction); + } + materialsToFill[i] = newMaterial; + } + } + + private static bool EditorConfirmDisabledMaskMaterialsInit(SkeletonRenderer skeleton) { + var maskMaterials = skeleton.maskMaterials; + if (maskMaterials.materialsMaskDisabled.Length > 0 && maskMaterials.materialsMaskDisabled[0] != null) { + return true; + } + + var meshRenderer = skeleton.GetComponent(); + Material[] currentMaterials = meshRenderer.sharedMaterials; + + if (currentMaterials.Length == 0 || currentMaterials[0] == null) { + Debug.LogWarning("No materials found assigned at " + skeleton.name); + return false; + } + + // We have to be sure that there has not been a recompilation or similar events that led to + // inside- or outside-mask materials being assigned to meshRenderer.sharedMaterials. + string firstMaterialPath = UnityEditor.AssetDatabase.GetAssetPath(currentMaterials[0]); + if (firstMaterialPath.Contains(MATERIAL_FILENAME_SUFFIX_INSIDE_MASK) || + firstMaterialPath.Contains(MATERIAL_FILENAME_SUFFIX_OUTSIDE_MASK)) { + + maskMaterials.materialsMaskDisabled = new Material[currentMaterials.Length]; + for (int i = 0; i < currentMaterials.Length; ++i) { + string path = UnityEditor.AssetDatabase.GetAssetPath(currentMaterials[i]); + string correctPath = null; + if (path.Contains(MATERIAL_FILENAME_SUFFIX_INSIDE_MASK)) { + correctPath = path.Replace(MATERIAL_FILENAME_SUFFIX_INSIDE_MASK, ""); + } + else if (path.Contains(MATERIAL_FILENAME_SUFFIX_OUTSIDE_MASK)) { + correctPath = path.Replace(MATERIAL_FILENAME_SUFFIX_OUTSIDE_MASK, ""); + } + + if (correctPath != null) { + Material material = UnityEditor.AssetDatabase.LoadAssetAtPath(correctPath); + if (material == null) + Debug.LogWarning("No original ignore-mask material found for path " + correctPath); + maskMaterials.materialsMaskDisabled[i] = material; + } + } + } + else { + maskMaterials.materialsMaskDisabled = currentMaterials; + } + return true; + } + + public static Material EditorCreateOrLoadMaskMaterialAsset(SkeletonRenderer.SpriteMaskInteractionMaterials maskMaterials, + UnityEngine.Rendering.CompareFunction maskFunction, Material originalMaterial) { + string originalMaterialPath = UnityEditor.AssetDatabase.GetAssetPath(originalMaterial); + int posOfExtensionDot = originalMaterialPath.LastIndexOf('.'); + string materialPath = (maskFunction == SkeletonRenderer.STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE) ? + originalMaterialPath.Insert(posOfExtensionDot, MATERIAL_FILENAME_SUFFIX_INSIDE_MASK) : + originalMaterialPath.Insert(posOfExtensionDot, MATERIAL_FILENAME_SUFFIX_OUTSIDE_MASK); + + Material material = UnityEditor.AssetDatabase.LoadAssetAtPath(materialPath); + if (material != null) { + return material; + } + + material = new Material(originalMaterial); + material.SetFloat(SkeletonRenderer.STENCIL_COMP_PARAM_ID, (int)maskFunction); + + UnityEditor.AssetDatabase.CreateAsset(material, materialPath); + Debug.Log(string.Concat("Created material '", materialPath, "' for mask interaction based on '", originalMaterialPath, "'.")); + UnityEditor.EditorUtility.SetDirty(material); + UnityEditor.AssetDatabase.SaveAssets(); + return material; + } + } +} +#endif // BUILT_IN_SPRITE_MASK_COMPONENT diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs.meta new file mode 100644 index 0000000..7d3b80b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Utility/SpineMaskUtilities.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7c1b3a9ddacb550458bb86affdf77bf5 +timeCreated: 1550564907 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows.meta new file mode 100644 index 0000000..ee5bf8b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b6badf2758b1ea44e8c5ec62ef338e22 +folderAsset: yes +timeCreated: 1563305058 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs new file mode 100644 index 0000000..a4bf070 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs @@ -0,0 +1,1490 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#define SPINE_SKELETONMECANIM + +using UnityEngine; +using UnityEditor; +using UnityEditorInternal; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.IO; +using Spine; + +namespace Spine.Unity.Editor { + + /// + /// [SUPPORTS] + /// Linear, Constant, and Bezier Curves* + /// Inverse Kinematics* + /// Inherit Rotation + /// Translate Timeline + /// Rotate Timeline + /// Scale Timeline** + /// Event Timeline*** + /// Attachment Timeline + /// + /// RegionAttachment + /// MeshAttachment (optionally Skinned) + /// + /// [LIMITATIONS] + /// *Bezier Curves are baked into the animation at 60fps and are not realtime. Use bakeIncrement constant to adjust key density if desired. + /// *Inverse Kinematics is baked into the animation at 60fps and are not realtime. Use bakeIncrement constant to adjust key density if desired. + /// ***Events may only fire 1 type of data per event in Unity safely so priority to String data if present in Spine key, otherwise a Float is sent whether the Spine key was Int or Float with priority given to Int. + /// + /// [DOES NOT SUPPORT] + /// FFD (Unity does not provide access to BlendShapes with code) + /// Color Keys (Maybe one day when Unity supports full FBX standard and provides access with code) + /// Draw Order Keyframes + /// + public static class SkeletonBaker { + + #region SkeletonMecanim's Mecanim Clips + #if SPINE_SKELETONMECANIM + public static void UpdateMecanimClips (SkeletonDataAsset skeletonDataAsset) { + if (skeletonDataAsset.controller == null) + return; + + SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset); + } + + public static void GenerateMecanimAnimationClips (SkeletonDataAsset skeletonDataAsset) { + var data = skeletonDataAsset.GetSkeletonData(true); + if (data == null) { + Debug.LogError("SkeletonData loading failed!", skeletonDataAsset); + return; + } + + string dataPath = AssetDatabase.GetAssetPath(skeletonDataAsset); + string controllerPath = dataPath.Replace(AssetUtility.SkeletonDataSuffix, "_Controller").Replace(".asset", ".controller"); + UnityEditor.Animations.AnimatorController controller; + if (skeletonDataAsset.controller != null) { + controller = (UnityEditor.Animations.AnimatorController)skeletonDataAsset.controller; + controllerPath = AssetDatabase.GetAssetPath(controller); + } else { + if (File.Exists(controllerPath)) { + if (EditorUtility.DisplayDialog("Controller Overwrite Warning", "Unknown Controller already exists at: " + controllerPath, "Update", "Overwrite")) { + controller = (UnityEditor.Animations.AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController)); + } else { + controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath); + } + } else { + controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath); + } + + } + + skeletonDataAsset.controller = controller; + EditorUtility.SetDirty(skeletonDataAsset); + + UnityEngine.Object[] objs = AssetDatabase.LoadAllAssetsAtPath(controllerPath); + + var unityAnimationClipTable = new Dictionary(); + var spineAnimationTable = new Dictionary(); + + foreach (var o in objs) { + //Debug.LogFormat("({0}){1} : {3} + {2} + {4}", o.GetType(), o.name, o.hideFlags, o.GetInstanceID(), o.GetHashCode()); + // There is a bug in Unity 5.3.3 (and likely before) that creates + // a duplicate AnimationClip when you duplicate a Mecanim Animator State. + // These duplicates seem to be identifiable by their HideFlags, so we'll exclude them. + if (o is AnimationClip) { + var clip = o as AnimationClip; + if (!clip.HasFlag(HideFlags.HideInHierarchy)) { + if (unityAnimationClipTable.ContainsKey(clip.name)) { + Debug.LogWarningFormat("Duplicate AnimationClips were found named {0}", clip.name); + } + unityAnimationClipTable.Add(clip.name, clip); + } + } + } + + foreach (var animations in data.Animations) { + string animationName = animations.Name; // Review for unsafe names. Requires runtime implementation too. + spineAnimationTable.Add(animationName, animations); + + if (unityAnimationClipTable.ContainsKey(animationName) == false) { + AnimationClip newClip = new AnimationClip { + name = animationName + }; + //AssetDatabase.CreateAsset(newClip, Path.GetDirectoryName(dataPath) + "/" + animationName + ".asset"); + AssetDatabase.AddObjectToAsset(newClip, controller); + unityAnimationClipTable.Add(animationName, newClip); + } + + AnimationClip clip = unityAnimationClipTable[animationName]; + clip.SetCurve("", typeof(GameObject), "dummy", AnimationCurve.Linear(0, 0, animations.Duration, 0)); + var settings = AnimationUtility.GetAnimationClipSettings(clip); + settings.stopTime = animations.Duration; + SetAnimationSettings(clip, settings); + + AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]); + foreach (Timeline t in animations.Timelines) { + if (t is EventTimeline) + ParseEventTimeline((EventTimeline)t, clip, SendMessageOptions.DontRequireReceiver); + } + + EditorUtility.SetDirty(clip); + unityAnimationClipTable.Remove(animationName); + } + + foreach (var clip in unityAnimationClipTable.Values) { + AnimationClip.DestroyImmediate(clip, true); + } + + AssetDatabase.Refresh(); + AssetDatabase.SaveAssets(); + } + + static bool HasFlag (this UnityEngine.Object o, HideFlags flagToCheck) { + return (o.hideFlags & flagToCheck) == flagToCheck; + } + #endif + #endregion + + #region Prefab and AnimationClip Baking + /// + /// Interval between key sampling for Bezier curves, IK controlled bones, and Inherit Rotation effected bones. + /// + const float BakeIncrement = 1 / 60f; + + public static void BakeToPrefab (SkeletonDataAsset skeletonDataAsset, ExposedList skins, string outputPath = "", bool bakeAnimations = true, bool bakeIK = true, SendMessageOptions eventOptions = SendMessageOptions.DontRequireReceiver) { + if (skeletonDataAsset == null || skeletonDataAsset.GetSkeletonData(true) == null) { + Debug.LogError("Could not export Spine Skeleton because SkeletonDataAsset is null or invalid!"); + return; + } + + if (outputPath == "") { + outputPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(skeletonDataAsset)).Replace('\\', '/') + "/Baked"; + System.IO.Directory.CreateDirectory(outputPath); + } + + var skeletonData = skeletonDataAsset.GetSkeletonData(true); + bool hasAnimations = bakeAnimations && skeletonData.Animations.Count > 0; + UnityEditor.Animations.AnimatorController controller = null; + if (hasAnimations) { + string controllerPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " Controller.controller"; + bool newAnimContainer = false; + + var runtimeController = AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController)); + + if (runtimeController != null) { + controller = (UnityEditor.Animations.AnimatorController)runtimeController; + } else { + controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath); + newAnimContainer = true; + } + + var existingClipTable = new Dictionary(); + var unusedClipNames = new List(); + Object[] animObjs = AssetDatabase.LoadAllAssetsAtPath(controllerPath); + + foreach (Object o in animObjs) { + if (o is AnimationClip) { + var clip = (AnimationClip)o; + existingClipTable.Add(clip.name, clip); + unusedClipNames.Add(clip.name); + } + } + + Dictionary> slotLookup = new Dictionary>(); + + int skinCount = skins.Count; + + for (int s = 0; s < skeletonData.Slots.Count; s++) { + List attachmentNames = new List(); + for (int i = 0; i < skinCount; i++) { + var skin = skins.Items[i]; + var skinEntries = new List(); + skin.GetAttachments(s, skinEntries); + foreach (var entry in skinEntries) { + if (!attachmentNames.Contains(entry.Name)) + attachmentNames.Add(entry.Name); + } + } + slotLookup.Add(s, attachmentNames); + } + + foreach (var anim in skeletonData.Animations) { + + AnimationClip clip = null; + if (existingClipTable.ContainsKey(anim.Name)) { + clip = existingClipTable[anim.Name]; + } + + clip = ExtractAnimation(anim.Name, skeletonData, slotLookup, bakeIK, eventOptions, clip); + + if (unusedClipNames.Contains(clip.name)) { + unusedClipNames.Remove(clip.name); + } else { + AssetDatabase.AddObjectToAsset(clip, controller); + controller.AddMotion(clip); + } + } + + if (newAnimContainer) { + EditorUtility.SetDirty(controller); + AssetDatabase.SaveAssets(); + AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate); + AssetDatabase.Refresh(); + } else { + + foreach (string str in unusedClipNames) { + AnimationClip.DestroyImmediate(existingClipTable[str], true); + } + + EditorUtility.SetDirty(controller); + AssetDatabase.SaveAssets(); + AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate); + AssetDatabase.Refresh(); + } + } + + foreach (var skin in skins) { + bool newPrefab = false; + + string prefabPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " (" + skin.Name + ").prefab"; + + Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)); + + if (prefab == null) { + #if NEW_PREFAB_SYSTEM + GameObject emptyGameObject = new GameObject(); + prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(emptyGameObject, prefabPath, InteractionMode.AutomatedAction); + GameObject.DestroyImmediate(emptyGameObject); + #else + prefab = PrefabUtility.CreateEmptyPrefab(prefabPath); + #endif + newPrefab = true; + } + + Dictionary meshTable = new Dictionary(); + List unusedMeshNames = new List(); + Object[] assets = AssetDatabase.LoadAllAssetsAtPath(prefabPath); + foreach (var obj in assets) { + if (obj is Mesh) { + meshTable.Add(obj.name, (Mesh)obj); + unusedMeshNames.Add(obj.name); + } + } + + GameObject prefabRoot = EditorInstantiation.NewGameObject("root", true); + + Dictionary slotTable = new Dictionary(); + Dictionary boneTable = new Dictionary(); + List boneList = new List(); + + //create bones + for (int i = 0; i < skeletonData.Bones.Count; i++) { + var boneData = skeletonData.Bones.Items[i]; + Transform boneTransform = EditorInstantiation.NewGameObject(boneData.Name, true).transform; + boneTransform.parent = prefabRoot.transform; + boneTable.Add(boneTransform.name, boneTransform); + boneList.Add(boneTransform); + } + + for (int i = 0; i < skeletonData.Bones.Count; i++) { + + var boneData = skeletonData.Bones.Items[i]; + Transform boneTransform = boneTable[boneData.Name]; + Transform parentTransform = null; + if (i > 0) + parentTransform = boneTable[boneData.Parent.Name]; + else + parentTransform = boneTransform.parent; + + boneTransform.parent = parentTransform; + boneTransform.localPosition = new Vector3(boneData.X, boneData.Y, 0); + var tm = boneData.TransformMode; + if (tm.InheritsRotation()) + boneTransform.localRotation = Quaternion.Euler(0, 0, boneData.Rotation); + else + boneTransform.rotation = Quaternion.Euler(0, 0, boneData.Rotation); + + if (tm.InheritsScale()) + boneTransform.localScale = new Vector3(boneData.ScaleX, boneData.ScaleY, 1); + } + + //create slots and attachments + for (int slotIndex = 0; slotIndex < skeletonData.Slots.Count; slotIndex++) { + var slotData = skeletonData.Slots.Items[slotIndex]; + Transform slotTransform = EditorInstantiation.NewGameObject(slotData.Name, true).transform; + slotTransform.parent = prefabRoot.transform; + slotTable.Add(slotData.Name, slotTransform); + + var skinEntries = new List(); + skin.GetAttachments(slotIndex, skinEntries); + if (skin != skeletonData.DefaultSkin) + skeletonData.DefaultSkin.GetAttachments(slotIndex, skinEntries); + + for (int a = 0; a < skinEntries.Count; a++) { + var attachment = skinEntries[a].Attachment; + string attachmentName = skinEntries[a].Name; + string attachmentMeshName = "[" + slotData.Name + "] " + attachmentName; + Vector3 offset = Vector3.zero; + float rotation = 0; + Mesh mesh = null; + Material material = null; + bool isWeightedMesh = false; + + if (meshTable.ContainsKey(attachmentMeshName)) + mesh = meshTable[attachmentMeshName]; + if (attachment is RegionAttachment) { + var regionAttachment = (RegionAttachment)attachment; + offset.x = regionAttachment.X; + offset.y = regionAttachment.Y; + rotation = regionAttachment.Rotation; + mesh = ExtractRegionAttachment(attachmentMeshName, regionAttachment, mesh); + material = attachment.GetMaterial(); + unusedMeshNames.Remove(attachmentMeshName); + if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false) + AssetDatabase.AddObjectToAsset(mesh, prefab); + } else if (attachment is MeshAttachment) { + var meshAttachment = (MeshAttachment)attachment; + isWeightedMesh = (meshAttachment.Bones != null); + offset.x = 0; + offset.y = 0; + rotation = 0; + + if (isWeightedMesh) + mesh = ExtractWeightedMeshAttachment(attachmentMeshName, meshAttachment, slotIndex, skeletonData, boneList, mesh); + else + mesh = ExtractMeshAttachment(attachmentMeshName, meshAttachment, mesh); + + material = attachment.GetMaterial(); + unusedMeshNames.Remove(attachmentMeshName); + if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false) + AssetDatabase.AddObjectToAsset(mesh, prefab); + } else + continue; + + Transform attachmentTransform = EditorInstantiation.NewGameObject(attachmentName, true).transform; + + attachmentTransform.parent = slotTransform; + attachmentTransform.localPosition = offset; + attachmentTransform.localRotation = Quaternion.Euler(0, 0, rotation); + + if (isWeightedMesh) { + attachmentTransform.position = Vector3.zero; + attachmentTransform.rotation = Quaternion.identity; + var skinnedMeshRenderer = attachmentTransform.gameObject.AddComponent(); + skinnedMeshRenderer.rootBone = boneList[0]; + skinnedMeshRenderer.bones = boneList.ToArray(); + skinnedMeshRenderer.sharedMesh = mesh; + } else { + attachmentTransform.gameObject.AddComponent().sharedMesh = mesh; + attachmentTransform.gameObject.AddComponent(); + } + + attachmentTransform.GetComponent().sharedMaterial = material; + attachmentTransform.GetComponent().sortingOrder = slotIndex; + + if (attachmentName != slotData.AttachmentName) + attachmentTransform.gameObject.SetActive(false); + } + + } + + foreach (var slotData in skeletonData.Slots) { + Transform slotTransform = slotTable[slotData.Name]; + slotTransform.parent = boneTable[slotData.BoneData.Name]; + slotTransform.localPosition = Vector3.zero; + slotTransform.localRotation = Quaternion.identity; + slotTransform.localScale = Vector3.one; + } + + if (hasAnimations) { + var animator = prefabRoot.AddComponent(); + animator.applyRootMotion = false; + animator.runtimeAnimatorController = (RuntimeAnimatorController)controller; + EditorGUIUtility.PingObject(controller); + } + + if (newPrefab) { + #if NEW_PREFAB_SYSTEM + PrefabUtility.SaveAsPrefabAssetAndConnect(prefabRoot, prefabPath, InteractionMode.AutomatedAction); + #else + PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ConnectToPrefab); + #endif + } else { + + foreach (string str in unusedMeshNames) { + Mesh.DestroyImmediate(meshTable[str], true); + } + + #if NEW_PREFAB_SYSTEM + PrefabUtility.SaveAsPrefabAssetAndConnect(prefabRoot, prefabPath, InteractionMode.AutomatedAction); + #else + PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ReplaceNameBased); + #endif + } + + + EditorGUIUtility.PingObject(prefab); + + AssetDatabase.Refresh(); + AssetDatabase.SaveAssets(); + + GameObject.DestroyImmediate(prefabRoot); + + } + } + + #region Attachment Baking + static Bone DummyBone; + static Slot DummySlot; + + internal static Bone GetDummyBone () { + if (DummyBone != null) + return DummyBone; + + SkeletonData skelData = new SkeletonData(); + BoneData data = new BoneData(0, "temp", null) { + ScaleX = 1, + ScaleY = 1, + Length = 100 + }; + + skelData.Bones.Add(data); + + Skeleton skeleton = new Skeleton(skelData); + + Bone bone = new Bone(data, skeleton, null); + bone.UpdateWorldTransform(); + + DummyBone = bone; + + return DummyBone; + } + + internal static Slot GetDummySlot () { + if (DummySlot != null) + return DummySlot; + + Bone bone = GetDummyBone(); + + SlotData data = new SlotData(0, "temp", bone.Data); + Slot slot = new Slot(data, bone); + DummySlot = slot; + return DummySlot; + } + + internal static Mesh ExtractRegionAttachment (string name, RegionAttachment attachment, Mesh mesh = null, bool centered = true) { + var bone = GetDummyBone(); + + if (centered) { + bone.X = -attachment.X; + bone.Y = -attachment.Y; + } + + bone.UpdateWorldTransform(); + + Vector2[] uvs = ExtractUV(attachment.UVs); + float[] floatVerts = new float[8]; + attachment.ComputeWorldVertices(bone, floatVerts, 0); + Vector3[] verts = ExtractVerts(floatVerts); + + //unrotate verts now that they're centered + if (centered) { + for (int i = 0; i < verts.Length; i++) + verts[i] = Quaternion.Euler(0, 0, -attachment.Rotation) * verts[i]; + } + + int[] triangles = { 1, 3, 0, 2, 3, 1 }; + Color color = attachment.GetColor(); + + if (mesh == null) + mesh = new Mesh(); + + mesh.triangles = new int[0]; + + mesh.vertices = verts; + mesh.uv = uvs; + mesh.triangles = triangles; + mesh.colors = new [] { color, color, color, color }; + mesh.RecalculateBounds(); + mesh.RecalculateNormals(); + mesh.name = name; + + return mesh; + } + + internal static Mesh ExtractMeshAttachment (string name, MeshAttachment attachment, Mesh mesh = null) { + var slot = GetDummySlot(); + + slot.Bone.X = 0; + slot.Bone.Y = 0; + slot.Bone.UpdateWorldTransform(); + + Vector2[] uvs = ExtractUV(attachment.UVs); + float[] floatVerts = new float[attachment.WorldVerticesLength]; + attachment.ComputeWorldVertices(slot, floatVerts); + Vector3[] verts = ExtractVerts(floatVerts); + + int[] triangles = attachment.Triangles; + Color color = attachment.GetColor(); + + if (mesh == null) + mesh = new Mesh(); + + mesh.triangles = new int[0]; + + mesh.vertices = verts; + mesh.uv = uvs; + mesh.triangles = triangles; + Color[] colors = new Color[verts.Length]; + for (int i = 0; i < verts.Length; i++) + colors[i] = color; + + mesh.colors = colors; + mesh.RecalculateBounds(); + mesh.RecalculateNormals(); + mesh.name = name; + + return mesh; + } + + public class BoneWeightContainer { + public struct Pair { + public Transform bone; + public float weight; + + public Pair (Transform bone, float weight) { + this.bone = bone; + this.weight = weight; + } + } + + public List bones; + public List weights; + public List pairs; + + + public BoneWeightContainer () { + this.bones = new List(); + this.weights = new List(); + this.pairs = new List(); + } + + public void Add (Transform transform, float weight) { + bones.Add(transform); + weights.Add(weight); + + pairs.Add(new Pair(transform, weight)); + } + } + + internal static Mesh ExtractWeightedMeshAttachment (string name, MeshAttachment attachment, int slotIndex, SkeletonData skeletonData, List boneList, Mesh mesh = null) { + if (!attachment.IsWeighted()) + throw new System.ArgumentException("Mesh is not weighted.", "attachment"); + + Skeleton skeleton = new Skeleton(skeletonData); + skeleton.UpdateWorldTransform(); + + float[] floatVerts = new float[attachment.WorldVerticesLength]; + attachment.ComputeWorldVertices(skeleton.Slots.Items[slotIndex], floatVerts); + + Vector2[] uvs = ExtractUV(attachment.UVs); + Vector3[] verts = ExtractVerts(floatVerts); + + int[] triangles = attachment.Triangles; + Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A); + + mesh = (mesh == null) ? new Mesh() : mesh; + + mesh.triangles = new int[0]; + + mesh.vertices = verts; + mesh.uv = uvs; + mesh.triangles = triangles; + Color[] colors = new Color[verts.Length]; + for (int i = 0; i < verts.Length; i++) + colors[i] = color; + + mesh.colors = colors; + mesh.name = name; + mesh.RecalculateNormals(); + mesh.RecalculateBounds(); + + // Handle weights and binding + var weightTable = new Dictionary(); + var warningBuilder = new System.Text.StringBuilder(); + + int[] bones = attachment.Bones; + float[] weights = attachment.Vertices; + for (int w = 0, v = 0, b = 0, n = bones.Length; v < n; w += 2) { + + int nn = bones[v++] + v; + for (; v < nn; v++, b += 3) { + Transform boneTransform = boneList[bones[v]]; + int vIndex = w / 2; + BoneWeightContainer container; + if (weightTable.ContainsKey(vIndex)) + container = weightTable[vIndex]; + else { + container = new BoneWeightContainer(); + weightTable.Add(vIndex, container); + } + + float weight = weights[b + 2]; + container.Add(boneTransform, weight); + } + } + + BoneWeight[] boneWeights = new BoneWeight[weightTable.Count]; + + for (int i = 0; i < weightTable.Count; i++) { + BoneWeight bw = new BoneWeight(); + var container = weightTable[i]; + + var pairs = container.pairs.OrderByDescending(pair => pair.weight).ToList(); + + for (int b = 0; b < pairs.Count; b++) { + if (b > 3) { + if (warningBuilder.Length == 0) + warningBuilder.Insert(0, "[Weighted Mesh: " + name + "]\r\nUnity only supports 4 weight influences per vertex! The 4 strongest influences will be used.\r\n"); + + warningBuilder.AppendFormat("{0} ignored on vertex {1}!\r\n", pairs[b].bone.name, i); + continue; + } + + int boneIndex = boneList.IndexOf(pairs[b].bone); + float weight = pairs[b].weight; + + switch (b) { + case 0: + bw.boneIndex0 = boneIndex; + bw.weight0 = weight; + break; + case 1: + bw.boneIndex1 = boneIndex; + bw.weight1 = weight; + break; + case 2: + bw.boneIndex2 = boneIndex; + bw.weight2 = weight; + break; + case 3: + bw.boneIndex3 = boneIndex; + bw.weight3 = weight; + break; + } + } + + boneWeights[i] = bw; + } + + Matrix4x4[] bindPoses = new Matrix4x4[boneList.Count]; + for (int i = 0; i < boneList.Count; i++) { + bindPoses[i] = boneList[i].worldToLocalMatrix; + } + + mesh.boneWeights = boneWeights; + mesh.bindposes = bindPoses; + + string warningString = warningBuilder.ToString(); + if (warningString.Length > 0) + Debug.LogWarning(warningString); + + + return mesh; + } + + internal static Vector2[] ExtractUV (float[] floats) { + Vector2[] arr = new Vector2[floats.Length / 2]; + + for (int i = 0; i < floats.Length; i += 2) { + arr[i / 2] = new Vector2(floats[i], floats[i + 1]); + } + + return arr; + } + + internal static Vector3[] ExtractVerts (float[] floats) { + Vector3[] arr = new Vector3[floats.Length / 2]; + + for (int i = 0; i < floats.Length; i += 2) { + arr[i / 2] = new Vector3(floats[i], floats[i + 1], 0);// *scale; + } + + return arr; + } +#endregion + +#region Animation Baking + static AnimationClip ExtractAnimation (string name, SkeletonData skeletonData, Dictionary> slotLookup, bool bakeIK, SendMessageOptions eventOptions, AnimationClip clip = null) { + var animation = skeletonData.FindAnimation(name); + + var timelines = animation.Timelines; + + if (clip == null) { + clip = new AnimationClip(); + } else { + clip.ClearCurves(); + AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]); + } + + clip.name = name; + + Skeleton skeleton = new Skeleton(skeletonData); + + List ignoreRotateTimelineIndexes = new List(); + + if (bakeIK) { + foreach (IkConstraint i in skeleton.IkConstraints) { + foreach (Bone b in i.Bones) { + int index = skeleton.FindBoneIndex(b.Data.Name); + ignoreRotateTimelineIndexes.Add(index); + BakeBoneConstraints(b, animation, clip); + } + } + } + + foreach (Bone b in skeleton.Bones) { + if (!b.Data.TransformMode.InheritsRotation()) { + int index = skeleton.FindBoneIndex(b.Data.Name); + + if (ignoreRotateTimelineIndexes.Contains(index) == false) { + ignoreRotateTimelineIndexes.Add(index); + BakeBoneConstraints(b, animation, clip); + } + } + } + + foreach (Timeline t in timelines) { + skeleton.SetToSetupPose(); + + if (t is ScaleTimeline) { + ParseScaleTimeline(skeleton, (ScaleTimeline)t, clip); + } else if (t is TranslateTimeline) { + ParseTranslateTimeline(skeleton, (TranslateTimeline)t, clip); + } else if (t is RotateTimeline) { + //bypass any rotation keys if they're going to get baked anyway to prevent localEulerAngles vs Baked collision + if (ignoreRotateTimelineIndexes.Contains(((RotateTimeline)t).BoneIndex) == false) + ParseRotateTimeline(skeleton, (RotateTimeline)t, clip); + } else if (t is AttachmentTimeline) { + ParseAttachmentTimeline(skeleton, (AttachmentTimeline)t, slotLookup, clip); + } else if (t is EventTimeline) { + ParseEventTimeline((EventTimeline)t, clip, eventOptions); + } + + } + + var settings = AnimationUtility.GetAnimationClipSettings(clip); + settings.loopTime = true; + settings.stopTime = Mathf.Max(clip.length, 0.001f); + + SetAnimationSettings(clip, settings); + + clip.EnsureQuaternionContinuity(); + + EditorUtility.SetDirty(clip); + + return clip; + } + + static int BinarySearch (float[] values, float target) { + int low = 0; + int high = values.Length - 2; + if (high == 0) return 1; + int current = (int)((uint)high >> 1); + while (true) { + if (values[(current + 1)] <= target) + low = current + 1; + else + high = current; + + if (low == high) return (low + 1); + current = (int)((uint)(low + high) >> 1); + } + } + + static void BakeBoneConstraints (Bone bone, Spine.Animation animation, AnimationClip clip) { + Skeleton skeleton = bone.Skeleton; + bool inheritRotation = bone.Data.TransformMode.InheritsRotation(); + + animation.Apply(skeleton, 0, 0, false, null, 1f, MixBlend.Setup, MixDirection.In); + skeleton.UpdateWorldTransform(); + float duration = animation.Duration; + + AnimationCurve curve = new AnimationCurve(); + + List keys = new List(); + + float rotation = bone.AppliedRotation; + if (!inheritRotation) + rotation = GetUninheritedAppliedRotation(bone); + + keys.Add(new Keyframe(0, rotation, 0, 0)); + + int listIndex = 1; + + float r = rotation; + + int steps = Mathf.CeilToInt(duration / BakeIncrement); + + float currentTime = 0; + float angle = rotation; + + for (int i = 1; i <= steps; i++) { + currentTime += BakeIncrement; + if (i == steps) + currentTime = duration; + + animation.Apply(skeleton, 0, currentTime, true, null, 1f, MixBlend.Setup, MixDirection.In); + skeleton.UpdateWorldTransform(); + + int pIndex = listIndex - 1; + + Keyframe pk = keys[pIndex]; + + pk = keys[pIndex]; + + rotation = inheritRotation ? bone.AppliedRotation : GetUninheritedAppliedRotation(bone); + + angle += Mathf.DeltaAngle(angle, rotation); + + r = angle; + + float rOut = (r - pk.value) / (currentTime - pk.time); + + pk.outTangent = rOut; + + keys.Add(new Keyframe(currentTime, r, rOut, 0)); + + keys[pIndex] = pk; + + listIndex++; + } + + curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray())); + + string path = GetPath(bone.Data); + string propertyName = "localEulerAnglesBaked"; + + EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x"); + AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve()); + EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y"); + AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve()); + EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z"); + AnimationUtility.SetEditorCurve(clip, zBind, curve); + } + + static void ParseTranslateTimeline (Skeleton skeleton, TranslateTimeline timeline, AnimationClip clip) { + var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex]; + var bone = skeleton.Bones.Items[timeline.BoneIndex]; + + AnimationCurve xCurve = new AnimationCurve(); + AnimationCurve yCurve = new AnimationCurve(); + AnimationCurve zCurve = new AnimationCurve(); + + float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3]; + + float currentTime = timeline.Frames[0]; + + List xKeys = new List(); + List yKeys = new List(); + + xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] + boneData.X, 0, 0)); + yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] + boneData.Y, 0, 0)); + + int listIndex = 1; + int frameIndex = 1; + int f = 3; + float[] frames = timeline.Frames; + skeleton.SetToSetupPose(); + float lastTime = 0; + while (currentTime < endTime) { + int pIndex = listIndex - 1; + + float curveType = timeline.GetCurveType(frameIndex - 1); + if (curveType == 0) { + //linear + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + float x = frames[f + 1] + boneData.X; + float y = frames[f + 2] + boneData.Y; + + float xOut = (x - px.value) / (time - px.time); + float yOut = (y - py.value) / (time - py.time); + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(time, x, xOut, 0)); + yKeys.Add(new Keyframe(time, y, yOut, 0)); + + xKeys[pIndex] = px; + yKeys[pIndex] = py; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 1) { + //stepped + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + float x = frames[f + 1] + boneData.X; + float y = frames[f + 2] + boneData.Y; + + float xOut = float.PositiveInfinity; + float yOut = float.PositiveInfinity; + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(time, x, xOut, 0)); + yKeys.Add(new Keyframe(time, y, yOut, 0)); + + xKeys[pIndex] = px; + yKeys[pIndex] = py; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 2) { + + //bezier + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + + int steps = Mathf.FloorToInt((time - px.time) / BakeIncrement); + + for (int i = 1; i <= steps; i++) { + currentTime += BakeIncrement; + if (i == steps) + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + px = xKeys[listIndex - 1]; + py = yKeys[listIndex - 1]; + + float xOut = (bone.X - px.value) / (currentTime - px.time); + float yOut = (bone.Y - py.value) / (currentTime - py.time); + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(currentTime, bone.X, xOut, 0)); + yKeys.Add(new Keyframe(currentTime, bone.Y, yOut, 0)); + + xKeys[listIndex - 1] = px; + yKeys[listIndex - 1] = py; + + listIndex++; + lastTime = currentTime; + } + } + + frameIndex++; + f += 3; + } + + xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray())); + yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray())); + + + + string path = GetPath(boneData); + const string propertyName = "localPosition"; + + clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve); + clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve); + clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve); + } + + static void ParseScaleTimeline (Skeleton skeleton, ScaleTimeline timeline, AnimationClip clip) { + var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex]; + var bone = skeleton.Bones.Items[timeline.BoneIndex]; + + AnimationCurve xCurve = new AnimationCurve(); + AnimationCurve yCurve = new AnimationCurve(); + AnimationCurve zCurve = new AnimationCurve(); + + float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3]; + + float currentTime = timeline.Frames[0]; + + List xKeys = new List(); + List yKeys = new List(); + + xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] * boneData.ScaleX, 0, 0)); + yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] * boneData.ScaleY, 0, 0)); + + int listIndex = 1; + int frameIndex = 1; + int f = 3; + float[] frames = timeline.Frames; + skeleton.SetToSetupPose(); + float lastTime = 0; + while (currentTime < endTime) { + int pIndex = listIndex - 1; + float curveType = timeline.GetCurveType(frameIndex - 1); + + if (curveType == 0) { + //linear + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + float x = frames[f + 1] * boneData.ScaleX; + float y = frames[f + 2] * boneData.ScaleY; + + float xOut = (x - px.value) / (time - px.time); + float yOut = (y - py.value) / (time - py.time); + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(time, x, xOut, 0)); + yKeys.Add(new Keyframe(time, y, yOut, 0)); + + xKeys[pIndex] = px; + yKeys[pIndex] = py; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 1) { + //stepped + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + float x = frames[f + 1] * boneData.ScaleX; + float y = frames[f + 2] * boneData.ScaleY; + + float xOut = float.PositiveInfinity; + float yOut = float.PositiveInfinity; + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(time, x, xOut, 0)); + yKeys.Add(new Keyframe(time, y, yOut, 0)); + + xKeys[pIndex] = px; + yKeys[pIndex] = py; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 2) { + //bezier + Keyframe px = xKeys[pIndex]; + Keyframe py = yKeys[pIndex]; + + float time = frames[f]; + + int steps = Mathf.FloorToInt((time - px.time) / BakeIncrement); + + for (int i = 1; i <= steps; i++) { + currentTime += BakeIncrement; + if (i == steps) + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + px = xKeys[listIndex - 1]; + py = yKeys[listIndex - 1]; + + float xOut = (bone.ScaleX - px.value) / (currentTime - px.time); + float yOut = (bone.ScaleY - py.value) / (currentTime - py.time); + + px.outTangent = xOut; + py.outTangent = yOut; + + xKeys.Add(new Keyframe(currentTime, bone.ScaleX, xOut, 0)); + yKeys.Add(new Keyframe(currentTime, bone.ScaleY, yOut, 0)); + + xKeys[listIndex - 1] = px; + yKeys[listIndex - 1] = py; + + listIndex++; + lastTime = currentTime; + } + } + + frameIndex++; + f += 3; + } + + xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray())); + yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray())); + + string path = GetPath(boneData); + string propertyName = "localScale"; + + clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve); + clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve); + clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve); + } + + static void ParseRotateTimeline (Skeleton skeleton, RotateTimeline timeline, AnimationClip clip) { + var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex]; + var bone = skeleton.Bones.Items[timeline.BoneIndex]; + + var curve = new AnimationCurve(); + + float endTime = timeline.Frames[(timeline.FrameCount * 2) - 2]; + + float currentTime = timeline.Frames[0]; + + var keys = new List(); + + float rotation = timeline.Frames[1] + boneData.Rotation; + + keys.Add(new Keyframe(timeline.Frames[0], rotation, 0, 0)); + + int listIndex = 1; + int frameIndex = 1; + int f = 2; + float[] frames = timeline.Frames; + skeleton.SetToSetupPose(); + float lastTime = 0; + float angle = rotation; + while (currentTime < endTime) { + int pIndex = listIndex - 1; + float curveType = timeline.GetCurveType(frameIndex - 1); + + if (curveType == 0) { + //linear + Keyframe pk = keys[pIndex]; + + float time = frames[f]; + + rotation = frames[f + 1] + boneData.Rotation; + angle += Mathf.DeltaAngle(angle, rotation); + float r = angle; + + float rOut = (r - pk.value) / (time - pk.time); + + pk.outTangent = rOut; + + keys.Add(new Keyframe(time, r, rOut, 0)); + + keys[pIndex] = pk; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 1) { + //stepped + + Keyframe pk = keys[pIndex]; + + float time = frames[f]; + + rotation = frames[f + 1] + boneData.Rotation; + angle += Mathf.DeltaAngle(angle, rotation); + float r = angle; + + float rOut = float.PositiveInfinity; + + pk.outTangent = rOut; + + keys.Add(new Keyframe(time, r, rOut, 0)); + + keys[pIndex] = pk; + + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + + lastTime = time; + listIndex++; + } else if (curveType == 2) { + //bezier + Keyframe pk = keys[pIndex]; + + float time = frames[f]; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + skeleton.UpdateWorldTransform(); + + rotation = frames[f + 1] + boneData.Rotation; + angle += Mathf.DeltaAngle(angle, rotation); + float r = angle; + + int steps = Mathf.FloorToInt((time - pk.time) / BakeIncrement); + + for (int i = 1; i <= steps; i++) { + currentTime += BakeIncrement; + if (i == steps) + currentTime = time; + + timeline.Apply(skeleton, lastTime, currentTime, null, 1, MixBlend.Setup, MixDirection.In); + skeleton.UpdateWorldTransform(); + pk = keys[listIndex - 1]; + + rotation = bone.Rotation; + angle += Mathf.DeltaAngle(angle, rotation); + r = angle; + + float rOut = (r - pk.value) / (currentTime - pk.time); + + pk.outTangent = rOut; + + keys.Add(new Keyframe(currentTime, r, rOut, 0)); + + keys[listIndex - 1] = pk; + + listIndex++; + lastTime = currentTime; + } + } + + frameIndex++; + f += 2; + } + + curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray())); + + string path = GetPath(boneData); + const string propertyName = "localEulerAnglesBaked"; + + EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x"); + AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve()); + EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y"); + AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve()); + EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z"); + AnimationUtility.SetEditorCurve(clip, zBind, curve); + } + + static void ParseEventTimeline (EventTimeline timeline, AnimationClip clip, SendMessageOptions eventOptions) { + float[] frames = timeline.Frames; + var events = timeline.Events; + + var animEvents = new List(); + for (int i = 0, n = frames.Length; i < n; i++) { + var spineEvent = events[i]; + string eventName = spineEvent.Data.Name; + if (SpineEditorUtilities.Preferences.mecanimEventIncludeFolderName) + eventName = eventName.Replace("/", ""); // calls method FolderNameEventName() + else + eventName = eventName.Substring(eventName.LastIndexOf('/') + 1); // calls method EventName() + var unityAnimationEvent = new AnimationEvent { + time = frames[i], + functionName = eventName, + messageOptions = eventOptions + }; + + if (!string.IsNullOrEmpty(spineEvent.String)) { + unityAnimationEvent.stringParameter = spineEvent.String; + } else if (spineEvent.Int != 0) { + unityAnimationEvent.intParameter = spineEvent.Int; + } else if (spineEvent.Float != 0) { + unityAnimationEvent.floatParameter = spineEvent.Float; + } // else, paramless function/Action. + + animEvents.Add(unityAnimationEvent); + } + + AnimationUtility.SetAnimationEvents(clip, animEvents.ToArray()); + } + + static void ParseAttachmentTimeline (Skeleton skeleton, AttachmentTimeline timeline, Dictionary> slotLookup, AnimationClip clip) { + var attachmentNames = slotLookup[timeline.SlotIndex]; + + string bonePath = GetPath(skeleton.Slots.Items[timeline.SlotIndex].Bone.Data); + string slotPath = bonePath + "/" + skeleton.Slots.Items[timeline.SlotIndex].Data.Name; + + Dictionary curveTable = new Dictionary(); + + foreach (string str in attachmentNames) { + curveTable.Add(str, new AnimationCurve()); + } + + float[] frames = timeline.Frames; + + if (frames[0] != 0) { + string startingName = skeleton.Slots.Items[timeline.SlotIndex].Data.AttachmentName; + foreach (var pair in curveTable) { + if (startingName == "" || startingName == null) { + pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity)); + } else { + if (pair.Key == startingName) { + pair.Value.AddKey(new Keyframe(0, 1, float.PositiveInfinity, float.PositiveInfinity)); + } else { + pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity)); + } + } + } + } + + float currentTime = timeline.Frames[0]; + float endTime = frames[frames.Length - 1]; + int f = 0; + while (currentTime < endTime) { + float time = frames[f]; + + int frameIndex = (time >= frames[frames.Length - 1] ? frames.Length : BinarySearch(frames, time)) - 1; + + string name = timeline.AttachmentNames[frameIndex]; + foreach (var pair in curveTable) { + if (name == "") { + pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity)); + } else { + if (pair.Key == name) { + pair.Value.AddKey(new Keyframe(time, 1, float.PositiveInfinity, float.PositiveInfinity)); + } else { + pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity)); + } + } + } + + currentTime = time; + f += 1; + } + + foreach (var pair in curveTable) { + string path = slotPath + "/" + pair.Key; + string prop = "m_IsActive"; + + clip.SetCurve(path, typeof(GameObject), prop, pair.Value); + } + } + + static AnimationCurve EnsureCurveKeyCount (AnimationCurve curve) { + if (curve.length == 1) + curve.AddKey(curve.keys[0].time + 0.25f, curve.keys[0].value); + + return curve; + } + + static float GetUninheritedAppliedRotation (Bone b) { + Bone parent = b.Parent; + float angle = b.AppliedRotation; + + while (parent != null) { + angle -= parent.AppliedRotation; + parent = parent.Parent; + } + + return angle; + } +#endregion +#endregion + +#region Region Baking + public static GameObject BakeRegion (SpineAtlasAsset atlasAsset, AtlasRegion region, bool autoSave = true) { + atlasAsset.GetAtlas(); // Initializes atlasAsset. + + string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset); + string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath).Replace('\\', '/'); + string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name); + string bakedPrefabPath = Path.Combine(bakedDirPath, AssetUtility.GetPathSafeName(region.name) + ".prefab").Replace("\\", "/"); + + GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject)); + GameObject root; + Mesh mesh; + bool isNewPrefab = false; + + if (!Directory.Exists(bakedDirPath)) + Directory.CreateDirectory(bakedDirPath); + + if (prefab == null) { + root = EditorInstantiation.NewGameObject("temp", true, typeof(MeshFilter), typeof(MeshRenderer)); + #if NEW_PREFAB_SYSTEM + prefab = PrefabUtility.SaveAsPrefabAsset(root, bakedPrefabPath); + #else + prefab = PrefabUtility.CreatePrefab(bakedPrefabPath, root); + #endif + + isNewPrefab = true; + Object.DestroyImmediate(root); + } + + mesh = (Mesh)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(Mesh)); + + Material mat = null; + mesh = atlasAsset.GenerateMesh(region.name, mesh, out mat); + if (isNewPrefab) { + AssetDatabase.AddObjectToAsset(mesh, prefab); + prefab.GetComponent().sharedMesh = mesh; + } + + EditorUtility.SetDirty(mesh); + EditorUtility.SetDirty(prefab); + + if (autoSave) { + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + } + + prefab.GetComponent().sharedMaterial = mat; + + return prefab; + } +#endregion + + static string GetPath (BoneData b) { + return GetPathRecurse(b).Substring(1); + } + + static string GetPathRecurse (BoneData b) { + if (b == null) return ""; + return GetPathRecurse(b.Parent) + "/" + b.Name; + } + + static void SetAnimationSettings (AnimationClip clip, AnimationClipSettings settings) { + AnimationUtility.SetAnimationClipSettings(clip, settings); + } + + + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs.meta new file mode 100644 index 0000000..37b13c9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBaker.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 687d9be457ea4eb44bf09c35c95ee5cd +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs new file mode 100644 index 0000000..62870d0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs @@ -0,0 +1,174 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace Spine.Unity.Editor { + + using Editor = UnityEditor.Editor; + using Icons = SpineEditorUtilities.Icons; + + public class SkeletonBakingWindow : EditorWindow { + const bool IsUtilityWindow = true; + + [MenuItem("CONTEXT/SkeletonDataAsset/Skeleton Baking", false, 5000)] + public static void Init (MenuCommand command) { + var window = EditorWindow.GetWindow(IsUtilityWindow); + window.minSize = new Vector2(330f, 530f); + window.maxSize = new Vector2(600f, 1000f); + window.titleContent = new GUIContent("Skeleton Baking", Icons.spine); + window.skeletonDataAsset = command.context as SkeletonDataAsset; + window.Show(); + } + + public SkeletonDataAsset skeletonDataAsset; + [SpineSkin(dataField:"skeletonDataAsset")] + public string skinToBake = "default"; + + // Settings + bool bakeAnimations = false; + bool bakeIK = true; + SendMessageOptions bakeEventOptions; + + SerializedObject so; + Skin bakeSkin; + + + void DataAssetChanged () { + bakeSkin = null; + } + + void OnGUI () { + so = so ?? new SerializedObject(this); + + EditorGUIUtility.wideMode = true; + EditorGUILayout.LabelField("Spine Skeleton Prefab Baking", EditorStyles.boldLabel); + + const string BakingWarningMessage = "\nSkeleton baking is not the primary use case for Spine skeletons." + + "\nUse baking if you have specialized uses, such as simplified skeletons with movement driven by physics." + + + "\n\nBaked Skeletons do not support the following:" + + "\n\tDisabled rotation or scale inheritance" + + "\n\tLocal Shear" + + "\n\tAll Constraint types" + + "\n\tWeighted mesh verts with more than 4 bound bones" + + + "\n\nBaked Animations do not support the following:" + + "\n\tMesh Deform Keys" + + "\n\tColor Keys" + + "\n\tDraw Order Keys" + + + "\n\nAnimation Curves are sampled at 60fps and are not realtime." + + "\nConstraint animations are also baked into animation curves." + + "\nSee SkeletonBaker.cs comments for full details.\n"; + + EditorGUILayout.HelpBox(BakingWarningMessage, MessageType.Info, true); + + EditorGUI.BeginChangeCheck(); + var skeletonDataAssetProperty = so.FindProperty("skeletonDataAsset"); + EditorGUILayout.PropertyField(skeletonDataAssetProperty, SpineInspectorUtility.TempContent("SkeletonDataAsset", Icons.spine)); + if (EditorGUI.EndChangeCheck()) { + so.ApplyModifiedProperties(); + DataAssetChanged(); + } + EditorGUILayout.Space(); + + if (skeletonDataAsset == null) return; + var skeletonData = skeletonDataAsset.GetSkeletonData(false); + if (skeletonData == null) return; + bool hasExtraSkins = skeletonData.Skins.Count > 1; + + using (new SpineInspectorUtility.BoxScope(false)) { + EditorGUILayout.LabelField(skeletonDataAsset.name, EditorStyles.boldLabel); + using (new SpineInspectorUtility.IndentScope()) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Bones: " + skeletonData.Bones.Count, Icons.bone)); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Slots: " + skeletonData.Slots.Count, Icons.slotRoot)); + + if (hasExtraSkins) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Skins: " + skeletonData.Skins.Count, Icons.skinsRoot)); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Current skin attachments: " + (bakeSkin == null ? 0 : bakeSkin.Attachments.Count), Icons.skinPlaceholder)); + } else if (skeletonData.Skins.Count == 1) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Skins: 1 (only default Skin)", Icons.skinsRoot)); + } + + int totalAttachments = 0; + foreach (var s in skeletonData.Skins) + totalAttachments += s.Attachments.Count; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Total Attachments: " + totalAttachments, Icons.genericAttachment)); + } + } + using (new SpineInspectorUtility.BoxScope(false)) { + EditorGUILayout.LabelField("Animations", EditorStyles.boldLabel); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Animations: " + skeletonData.Animations.Count, Icons.animation)); + + using (new SpineInspectorUtility.IndentScope()) { + bakeAnimations = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Bake Animations", Icons.animationRoot), bakeAnimations); + using (new EditorGUI.DisabledScope(!bakeAnimations)) { + using (new SpineInspectorUtility.IndentScope()) { + bakeIK = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Bake IK", Icons.constraintIK), bakeIK); + bakeEventOptions = (SendMessageOptions)EditorGUILayout.EnumPopup(SpineInspectorUtility.TempContent("Event Options", Icons.userEvent), bakeEventOptions); + } + } + } + } + EditorGUILayout.Space(); + + if (!string.IsNullOrEmpty(skinToBake) && UnityEngine.Event.current.type == EventType.Repaint) + bakeSkin = skeletonData.FindSkin(skinToBake) ?? skeletonData.DefaultSkin; + + var prefabIcon = EditorGUIUtility.FindTexture("PrefabModel Icon"); + + if (hasExtraSkins) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(so.FindProperty("skinToBake")); + if (EditorGUI.EndChangeCheck()) { + so.ApplyModifiedProperties(); + Repaint(); + } + + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent(string.Format("Bake Skeleton with Skin ({0})", (bakeSkin == null ? "default" : bakeSkin.Name)), prefabIcon))) { + SkeletonBaker.BakeToPrefab(skeletonDataAsset, new ExposedList(new[] { bakeSkin }), "", bakeAnimations, bakeIK, bakeEventOptions); + } + + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent(string.Format("Bake All ({0} skins)", skeletonData.Skins.Count), prefabIcon))) { + SkeletonBaker.BakeToPrefab(skeletonDataAsset, skeletonData.Skins, "", bakeAnimations, bakeIK, bakeEventOptions); + } + } else { + if (SpineInspectorUtility.LargeCenteredButton(SpineInspectorUtility.TempContent("Bake Skeleton", prefabIcon))) { + SkeletonBaker.BakeToPrefab(skeletonDataAsset, new ExposedList(new[] { bakeSkin }), "", bakeAnimations, bakeIK, bakeEventOptions); + } + + } + + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs.meta new file mode 100644 index 0000000..4e1aa1d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonBakingWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 868b0caae5b3e65408ece1ab400c4a99 +timeCreated: 1495203966 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs new file mode 100644 index 0000000..4170a55 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs @@ -0,0 +1,592 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// With contributions from: Mitch Thompson + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#else +#define NO_PREFAB_MESH +#endif + +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using UnityEditor.AnimatedValues; + +namespace Spine.Unity.Editor { + using Editor = UnityEditor.Editor; + using Icons = SpineEditorUtilities.Icons; + + public class SkeletonDebugWindow : EditorWindow { + + const bool IsUtilityWindow = true; + internal static bool showBoneNames, showPaths = true, showShapes = true, showConstraints = true; + + [MenuItem("CONTEXT/SkeletonRenderer/Open Skeleton Debug Window", false, 5000)] + public static void Init () { + var window = EditorWindow.GetWindow(IsUtilityWindow); + window.minSize = new Vector2(330f, 360f); + window.maxSize = new Vector2(600f, 4000f); + window.titleContent = new GUIContent("Skeleton Debug", Icons.spine); + window.Show(); + window.OnSelectionChange(); + } + + + static AnimBool showSkeleton = new AnimBool(true); + static AnimBool showSlotsTree = new AnimBool(false); + static AnimBool showConstraintsTree = new AnimBool(false); + static AnimBool showDrawOrderTree = new AnimBool(false); + static AnimBool showEventDataTree = new AnimBool(false); + static AnimBool showDataTree = new AnimBool(false); + static AnimBool showInspectBoneTree = new AnimBool(false); + + Vector2 scrollPos; + + GUIContent SlotsRootLabel, SkeletonRootLabel; + GUIStyle BoldFoldoutStyle; + + public SkeletonRenderer skeletonRenderer; + Skeleton skeleton; + Skin activeSkin; + bool isPrefab; + + SerializedProperty bpo; + Bone bone; + + [SpineBone(dataField:"skeletonRenderer")] + public string boneName; + + readonly Dictionary> attachmentTable = new Dictionary>(); + + static bool staticLostValues = true; + + void OnSceneGUI (SceneView sceneView) { + if (skeleton == null || skeletonRenderer == null || !skeletonRenderer.valid || isPrefab) + return; + + var transform = skeletonRenderer.transform; + if (showPaths) SpineHandles.DrawPaths(transform, skeleton); + if (showConstraints) SpineHandles.DrawConstraints(transform, skeleton); + if (showBoneNames) SpineHandles.DrawBoneNames(transform, skeleton); + if (showShapes) SpineHandles.DrawBoundingBoxes(transform, skeleton); + + if (bone != null) { + SpineHandles.DrawBone(skeletonRenderer.transform, bone, 1.5f, Color.cyan); + Handles.Label(bone.GetWorldPosition(skeletonRenderer.transform) + (Vector3.down * 0.15f), bone.Data.Name, SpineHandles.BoneNameStyle); + } + } + + void OnSelectionChange () { + #if UNITY_2019_1_OR_NEWER + SceneView.duringSceneGui -= this.OnSceneGUI; + SceneView.duringSceneGui += this.OnSceneGUI; + #else + SceneView.onSceneGUIDelegate -= this.OnSceneGUI; + SceneView.onSceneGUIDelegate += this.OnSceneGUI; + #endif + + bool noSkeletonRenderer = false; + + var selectedObject = Selection.activeGameObject; + if (selectedObject == null) { + noSkeletonRenderer = true; + } else { + var selectedSkeletonRenderer = selectedObject.GetComponent(); + if (selectedSkeletonRenderer == null) { + noSkeletonRenderer = true; + } else if (skeletonRenderer != selectedSkeletonRenderer) { + + bone = null; + if (skeletonRenderer != null && skeletonRenderer.SkeletonDataAsset != selectedSkeletonRenderer.SkeletonDataAsset) + boneName = null; + + skeletonRenderer = selectedSkeletonRenderer; + skeletonRenderer.Initialize(false); + skeletonRenderer.LateUpdate(); + skeleton = skeletonRenderer.skeleton; +#if NEW_PREFAB_SYSTEM + isPrefab = false; +#else + isPrefab |= PrefabUtility.GetPrefabType(selectedObject) == PrefabType.Prefab; +#endif + UpdateAttachments(); + } + } + + if (noSkeletonRenderer) Clear(); + Repaint(); + } + + void Clear () { + skeletonRenderer = null; + skeleton = null; + attachmentTable.Clear(); + isPrefab = false; + boneName = string.Empty; + bone = null; + #if UNITY_2019_1_OR_NEWER + SceneView.duringSceneGui -= this.OnSceneGUI; + #else + SceneView.onSceneGUIDelegate -= this.OnSceneGUI; + #endif + } + + void OnDestroy () { + Clear(); + } + + static void FalseDropDown (string label, string stringValue, Texture2D icon = null, bool disabledGroup = false) { + if (disabledGroup) EditorGUI.BeginDisabledGroup(true); + var pos = EditorGUILayout.GetControlRect(true); + pos = EditorGUI.PrefixLabel(pos, SpineInspectorUtility.TempContent(label)); + GUI.Button(pos, SpineInspectorUtility.TempContent(stringValue, icon), EditorStyles.popup); + if (disabledGroup) EditorGUI.EndDisabledGroup(); + } + + // Window GUI + void OnGUI () { + bool requireRepaint = false; + + if (staticLostValues) { + Clear(); + OnSelectionChange(); + staticLostValues = false; + requireRepaint = true; + } + + if (SlotsRootLabel == null) { + SlotsRootLabel = new GUIContent("Slots", Icons.slotRoot); + SkeletonRootLabel = new GUIContent("Skeleton", Icons.skeleton); + BoldFoldoutStyle = new GUIStyle(EditorStyles.foldout); + BoldFoldoutStyle.fontStyle = FontStyle.Bold; + BoldFoldoutStyle.stretchWidth = true; + BoldFoldoutStyle.fixedWidth = 0; + } + + + EditorGUILayout.Space(); + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.ObjectField(SpineInspectorUtility.TempContent("Debug Selection", Icons.spine), skeletonRenderer, typeof(SkeletonRenderer), true); + EditorGUI.EndDisabledGroup(); + + if (skeleton == null || skeletonRenderer == null) { + EditorGUILayout.HelpBox("No SkeletonRenderer Spine GameObject selected.", MessageType.Info); + return; + } + + if (isPrefab) { + EditorGUILayout.HelpBox("SkeletonDebug only debugs Spine GameObjects in the scene.", MessageType.Warning); + return; + } + + if (!skeletonRenderer.valid) { + EditorGUILayout.HelpBox("Spine Component is invalid. Check SkeletonData Asset.", MessageType.Error); + return; + } + + if (activeSkin != skeleton.Skin) + UpdateAttachments(); + + scrollPos = EditorGUILayout.BeginScrollView(scrollPos); + + using (new SpineInspectorUtility.BoxScope(false)) { + if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Skeleton.SetToSetupPose()"))) { + skeleton.SetToSetupPose(); + requireRepaint = true; + } + + EditorGUI.BeginChangeCheck(); + EditorGUILayout.LabelField("Scene View", EditorStyles.boldLabel); + using (new SpineInspectorUtility.LabelWidthScope()) { + showBoneNames = EditorGUILayout.Toggle("Show Bone Names", showBoneNames); + showPaths = EditorGUILayout.Toggle("Show Paths", showPaths); + showShapes = EditorGUILayout.Toggle("Show Shapes", showShapes); + showConstraints = EditorGUILayout.Toggle("Show Constraints", showConstraints); + } + requireRepaint |= EditorGUI.EndChangeCheck(); + + + // Skeleton + showSkeleton.target = EditorGUILayout.Foldout(showSkeleton.target, SkeletonRootLabel, BoldFoldoutStyle); + if (showSkeleton.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showSkeleton.faded)) { + EditorGUI.BeginChangeCheck(); + + EditorGUI.BeginDisabledGroup(true); + FalseDropDown(".Skin", skeleton.Skin != null ? skeletonRenderer.Skeleton.Skin.Name : "", Icons.skin); + EditorGUI.EndDisabledGroup(); + + // Flip + skeleton.ScaleX = EditorGUILayout.DelayedFloatField(".ScaleX", skeleton.ScaleX); + skeleton.ScaleY = EditorGUILayout.DelayedFloatField(".ScaleY", skeleton.ScaleY); + //EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(160f)); + ////EditorGUILayout.LabelField("Scale", GUILayout.Width(EditorGUIUtility.labelWidth - 20f)); + //GUILayout.EndHorizontal(); + + // Color + skeleton.SetColor(EditorGUILayout.ColorField(".R .G .B .A", skeleton.GetColor())); + + requireRepaint |= EditorGUI.EndChangeCheck(); + } + } + } + + // Bone + showInspectBoneTree.target = EditorGUILayout.Foldout(showInspectBoneTree.target, SpineInspectorUtility.TempContent("Bone", Icons.bone), BoldFoldoutStyle); + if (showInspectBoneTree.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showInspectBoneTree.faded)) { + showBoneNames = EditorGUILayout.Toggle("Show Bone Names", showBoneNames); + if (bpo == null) bpo = new SerializedObject(this).FindProperty("boneName"); + EditorGUILayout.PropertyField(bpo, SpineInspectorUtility.TempContent("Bone")); + if (!string.IsNullOrEmpty(bpo.stringValue)) { + if (bone == null || bone.Data.Name != bpo.stringValue) { + bone = skeleton.FindBone(bpo.stringValue); + } + + if (bone != null) { + using (new EditorGUI.DisabledGroupScope(true)) { + var wm = EditorGUIUtility.wideMode; + EditorGUIUtility.wideMode = true; + EditorGUILayout.Slider("Local Rotation", ViewRound(bone.Rotation), -180f, 180f); + EditorGUILayout.Vector2Field("Local Position", RoundVector2(bone.X, bone.Y)); + EditorGUILayout.Vector2Field("Local Scale", RoundVector2(bone.ScaleX, bone.ScaleY)); + EditorGUILayout.Vector2Field("Local Shear", RoundVector2(bone.ShearX, bone.ShearY)); + + EditorGUILayout.Space(); + + var boneParent = bone.Parent; + if (boneParent != null) FalseDropDown("Parent", boneParent.Data.Name, Icons.bone); + + const string RoundFormat = "0.##"; + var lw = EditorGUIUtility.labelWidth; + var fw = EditorGUIUtility.fieldWidth; + EditorGUIUtility.labelWidth *= 0.25f; + EditorGUIUtility.fieldWidth *= 0.5f; + EditorGUILayout.LabelField("LocalToWorld"); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.Space(); + EditorGUILayout.TextField(".A", bone.A.ToString(RoundFormat)); + EditorGUILayout.TextField(".B", bone.B.ToString(RoundFormat)); + EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.Space(); + EditorGUILayout.TextField(".C", bone.C.ToString(RoundFormat)); + EditorGUILayout.TextField(".D", bone.D.ToString(RoundFormat)); + EditorGUILayout.EndHorizontal(); + + EditorGUIUtility.labelWidth = lw * 0.5f; + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.Space(); + EditorGUILayout.Space(); + EditorGUILayout.TextField(".WorldX", bone.WorldX.ToString(RoundFormat)); + EditorGUILayout.TextField(".WorldY", bone.WorldY.ToString(RoundFormat)); + EditorGUILayout.EndHorizontal(); + + EditorGUIUtility.labelWidth = lw; + EditorGUIUtility.fieldWidth = fw; + EditorGUIUtility.wideMode = wm; + + } + } + requireRepaint = true; + } else { + bone = null; + } + } + } + } + + // Slots + int preSlotsIndent = EditorGUI.indentLevel; + showSlotsTree.target = EditorGUILayout.Foldout(showSlotsTree.target, SlotsRootLabel, BoldFoldoutStyle); + if (showSlotsTree.faded > 0) { + using (new EditorGUILayout.FadeGroupScope(showSlotsTree.faded)) { + if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Skeleton.SetSlotsToSetupPose()"))) { + skeleton.SetSlotsToSetupPose(); + requireRepaint = true; + } + + int baseIndent = EditorGUI.indentLevel; + foreach (KeyValuePair> pair in attachmentTable) { + Slot slot = pair.Key; + + using (new EditorGUILayout.HorizontalScope()) { + EditorGUI.indentLevel = baseIndent + 1; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); + EditorGUI.BeginChangeCheck(); + Color c = EditorGUILayout.ColorField(new Color(slot.R, slot.G, slot.B, slot.A), GUILayout.Width(60)); + if (EditorGUI.EndChangeCheck()) { + slot.SetColor(c); + requireRepaint = true; + } + } + + foreach (var skinEntry in pair.Value) { + var attachment = skinEntry.Attachment; + GUI.contentColor = slot.Attachment == attachment ? Color.white : Color.grey; + EditorGUI.indentLevel = baseIndent + 2; + var icon = Icons.GetAttachmentIcon(attachment); + bool isAttached = (attachment == slot.Attachment); + bool swap = EditorGUILayout.ToggleLeft(SpineInspectorUtility.TempContent(attachment.Name, icon), attachment == slot.Attachment); + if (isAttached != swap) { + slot.Attachment = isAttached ? null : attachment; + requireRepaint = true; + } + GUI.contentColor = Color.white; + } + } + } + } + EditorGUI.indentLevel = preSlotsIndent; + + // Constraints + const string NoneText = ""; + showConstraintsTree.target = EditorGUILayout.Foldout(showConstraintsTree.target, SpineInspectorUtility.TempContent("Constraints", Icons.constraintRoot), BoldFoldoutStyle); + if (showConstraintsTree.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showConstraintsTree.faded)) { + const float MixMin = 0f; + const float MixMax = 1f; + EditorGUI.BeginChangeCheck(); + showConstraints = EditorGUILayout.Toggle("Show Constraints", showConstraints); + requireRepaint |= EditorGUI.EndChangeCheck(); + + EditorGUILayout.Space(); + + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("IK Constraints ({0})", skeleton.IkConstraints.Count), Icons.constraintIK), EditorStyles.boldLabel); + using (new SpineInspectorUtility.IndentScope()) { + if (skeleton.IkConstraints.Count > 0) { + foreach (var c in skeleton.IkConstraints) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintIK)); + FalseDropDown("Goal", c.Data.Target.Name, Icons.bone, true); + using (new EditorGUI.DisabledGroupScope(true)) { + EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Data.Uniform", tooltip: "Uniformly scales a bone when Ik stretches or compresses."), c.Data.Uniform); + } + + EditorGUI.BeginChangeCheck(); + c.Mix = EditorGUILayout.Slider("Mix", c.Mix, MixMin, MixMax); + c.BendDirection = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Bend Clockwise", tooltip: "IkConstraint.BendDirection == 1 if clockwise; -1 if counterclockwise."), c.BendDirection > 0) ? 1 : -1; + c.Compress = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Compress", tooltip: "Compress single bone IK when the target too close. Not applied when parent bone has nonuniform scale."), c.Compress); + c.Stretch = EditorGUILayout.Toggle(SpineInspectorUtility.TempContent("Stretch", tooltip: "Stretch the parent bone when the target is out of range. Not applied when parent bone has nonuniform scale."), c.Stretch); + if (EditorGUI.EndChangeCheck()) requireRepaint = true; + + EditorGUILayout.Space(); + } + + } else { + EditorGUILayout.LabelField(NoneText); + } + } + + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("Transform Constraints ({0})", skeleton.TransformConstraints.Count), Icons.constraintTransform), EditorStyles.boldLabel); + using (new SpineInspectorUtility.IndentScope()) { + if (skeleton.TransformConstraints.Count > 0) { + foreach (var c in skeleton.TransformConstraints) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintTransform)); + EditorGUI.BeginDisabledGroup(true); + FalseDropDown("Goal", c.Data.Target.Name, Icons.bone); + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginChangeCheck(); + c.TranslateMix = EditorGUILayout.Slider("TranslateMix", c.TranslateMix, MixMin, MixMax); + c.RotateMix = EditorGUILayout.Slider("RotateMix", c.RotateMix, MixMin, MixMax); + c.ScaleMix = EditorGUILayout.Slider("ScaleMix", c.ScaleMix, MixMin, MixMax); + c.ShearMix = EditorGUILayout.Slider("ShearMix", c.ShearMix, MixMin, MixMax); + if (EditorGUI.EndChangeCheck()) requireRepaint = true; + + EditorGUILayout.Space(); + } + } else { + EditorGUILayout.LabelField(NoneText); + } + } + + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(string.Format("Path Constraints ({0})", skeleton.PathConstraints.Count), Icons.constraintPath), EditorStyles.boldLabel); + + EditorGUI.BeginChangeCheck(); + showPaths = EditorGUILayout.Toggle("Show Paths", showPaths); + requireRepaint |= EditorGUI.EndChangeCheck(); + + using (new SpineInspectorUtility.IndentScope()) { + if (skeleton.PathConstraints.Count > 0) { + foreach (var c in skeleton.PathConstraints) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(c.Data.Name, Icons.constraintPath)); + EditorGUI.BeginDisabledGroup(true); + FalseDropDown("Path Slot", c.Data.Target.Name, Icons.slot); + var activeAttachment = c.Target.Attachment; + FalseDropDown("Active Path", activeAttachment != null ? activeAttachment.Name : "", activeAttachment is PathAttachment ? Icons.path : null); + EditorGUILayout.LabelField("PositionMode." + c.Data.PositionMode); + EditorGUILayout.LabelField("SpacingMode." + c.Data.SpacingMode); + EditorGUILayout.LabelField("RotateMode." + c.Data.RotateMode); + EditorGUI.EndDisabledGroup(); + + EditorGUI.BeginChangeCheck(); + c.RotateMix = EditorGUILayout.Slider("RotateMix", c.RotateMix, MixMin, MixMax); + c.TranslateMix = EditorGUILayout.Slider("TranslateMix", c.TranslateMix, MixMin, MixMax); + c.Position = EditorGUILayout.FloatField("Position", c.Position); + c.Spacing = EditorGUILayout.FloatField("Spacing", c.Spacing); + if (EditorGUI.EndChangeCheck()) requireRepaint = true; + + EditorGUILayout.Space(); + } + + } else { + EditorGUILayout.LabelField(NoneText); + } + } + } + } + } + + showDrawOrderTree.target = EditorGUILayout.Foldout(showDrawOrderTree.target, SpineInspectorUtility.TempContent("Draw Order and Separators", Icons.slotRoot), BoldFoldoutStyle); + + //var separatorSlotNamesField = + //SpineInspectorUtility.ge + if (showDrawOrderTree.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showDrawOrderTree.faded)) { + + const string SeparatorString = "------------- v SEPARATOR v -------------"; + + if (Application.isPlaying) { + foreach (var slot in skeleton.DrawOrder) { + if (skeletonRenderer.separatorSlots.Contains(slot)) EditorGUILayout.LabelField(SeparatorString); + + using (new EditorGUI.DisabledScope(!slot.Bone.Active)) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); + } + } + } else { + foreach (var slot in skeleton.DrawOrder) { + var slotNames = SkeletonRendererInspector.GetSeparatorSlotNames(skeletonRenderer); + for (int i = 0, n = slotNames.Length; i < n; i++) { + if (string.Equals(slotNames[i], slot.Data.Name, System.StringComparison.Ordinal)) { + EditorGUILayout.LabelField(SeparatorString); + break; + } + } + using (new EditorGUI.DisabledScope(!slot.Bone.Active)) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot), GUILayout.ExpandWidth(false)); + } + } + } + + } + } + } + + showEventDataTree.target = EditorGUILayout.Foldout(showEventDataTree.target, SpineInspectorUtility.TempContent("Events", Icons.userEvent), BoldFoldoutStyle); + if (showEventDataTree.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showEventDataTree.faded)) { + if (skeleton.Data.Events.Count > 0) { + foreach (var e in skeleton.Data.Events) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(e.Name, Icons.userEvent)); + } + } else { + EditorGUILayout.LabelField(NoneText); + } + } + } + } + + showDataTree.target = EditorGUILayout.Foldout(showDataTree.target, SpineInspectorUtility.TempContent("Data Counts", Icons.spine), BoldFoldoutStyle); + if (showDataTree.faded > 0) { + using (new SpineInspectorUtility.IndentScope()) { + using (new EditorGUILayout.FadeGroupScope(showDataTree.faded)) { + using (new SpineInspectorUtility.LabelWidthScope()) { + var skeletonData = skeleton.Data; + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Bones", Icons.bone, "Skeleton.Data.Bones"), new GUIContent(skeletonData.Bones.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Slots", Icons.slotRoot, "Skeleton.Data.Slots"), new GUIContent(skeletonData.Slots.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Skins", Icons.skinsRoot, "Skeleton.Data.Skins"), new GUIContent(skeletonData.Skins.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Events", Icons.userEvent, "Skeleton.Data.Events"), new GUIContent(skeletonData.Events.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("IK Constraints", Icons.constraintIK, "Skeleton.Data.IkConstraints"), new GUIContent(skeletonData.IkConstraints.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Transform Constraints", Icons.constraintTransform, "Skeleton.Data.TransformConstraints"), new GUIContent(skeletonData.TransformConstraints.Count.ToString())); + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Path Constraints", Icons.constraintPath, "Skeleton.Data.PathConstraints"), new GUIContent(skeletonData.PathConstraints.Count.ToString())); + } + } + } + } + + if (IsAnimating(showSlotsTree, showSkeleton, showConstraintsTree, showDrawOrderTree, showEventDataTree, showInspectBoneTree, showDataTree)) + Repaint(); + } + + if (requireRepaint) { + skeletonRenderer.LateUpdate(); + Repaint(); + SceneView.RepaintAll(); + } + + EditorGUILayout.EndScrollView(); + } + + static float ViewRound (float x) { + const float Factor = 100f; + const float Divisor = 1f/Factor; + return Mathf.Round(x * Factor) * Divisor; + } + + static Vector2 RoundVector2 (float x, float y) { + const float Factor = 100f; + const float Divisor = 1f/Factor; + return new Vector2(Mathf.Round(x * Factor) * Divisor, Mathf.Round(y * Factor) * Divisor); + } + + static bool IsAnimating (params AnimBool[] animBools) { + foreach (var a in animBools) + if (a.isAnimating) return true; + return false; + } + + void UpdateAttachments () { + //skeleton = skeletonRenderer.skeleton; + Skin defaultSkin = skeleton.Data.DefaultSkin; + Skin skin = skeleton.Skin ?? defaultSkin; + bool notDefaultSkin = skin != defaultSkin; + + attachmentTable.Clear(); + for (int i = skeleton.Slots.Count - 1; i >= 0; i--) { + var attachments = new List(); + attachmentTable.Add(skeleton.Slots.Items[i], attachments); + // Add skin attachments. + skin.GetAttachments(i, attachments); + if (notDefaultSkin && defaultSkin != null) // Add default skin attachments. + defaultSkin.GetAttachments(i, attachments); + } + + activeSkin = skeleton.Skin; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs.meta new file mode 100644 index 0000000..d3697a0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SkeletonDebugWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7093e73ff3cf6c543ac5865980070b49 +timeCreated: 1494837950 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs new file mode 100644 index 0000000..0f64454 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs @@ -0,0 +1,317 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2017_2_OR_NEWER +#define NEWPLAYMODECALLBACKS +#endif + +#if UNITY_2018_3_OR_NEWER +#define NEW_PREFERENCES_SETTINGS_PROVIDER +#endif + +using UnityEngine; +using UnityEditor; +using System.Threading; + +namespace Spine.Unity.Editor { + + public class SpinePreferences : ScriptableObject { + + #if NEW_PREFERENCES_SETTINGS_PROVIDER + static int wasPreferencesDirCreated = 0; + static int wasPreferencesAssetCreated = 0; + #endif + + public const string SPINE_SETTINGS_ASSET_PATH = "Assets/Jarvis/Editor/Setting/Spine/SpineSettings.asset"; + + #if SPINE_TK2D + internal const float DEFAULT_DEFAULT_SCALE = 1f; + #else + internal const float DEFAULT_DEFAULT_SCALE = 0.01f; + #endif + public float defaultScale = DEFAULT_DEFAULT_SCALE; + + internal const float DEFAULT_DEFAULT_MIX = 0.2f; + public float defaultMix = DEFAULT_DEFAULT_MIX; + + internal const string DEFAULT_DEFAULT_SHADER = "Spine/Skeleton"; + public string defaultShader = DEFAULT_DEFAULT_SHADER; + + internal const float DEFAULT_DEFAULT_ZSPACING = 0f; + public float defaultZSpacing = DEFAULT_DEFAULT_ZSPACING; + + internal const bool DEFAULT_DEFAULT_INSTANTIATE_LOOP = true; + public bool defaultInstantiateLoop = DEFAULT_DEFAULT_INSTANTIATE_LOOP; + + internal const bool DEFAULT_SHOW_HIERARCHY_ICONS = true; + public bool showHierarchyIcons = DEFAULT_SHOW_HIERARCHY_ICONS; + + internal const bool DEFAULT_SET_TEXTUREIMPORTER_SETTINGS = true; + public bool setTextureImporterSettings = DEFAULT_SET_TEXTUREIMPORTER_SETTINGS; + + internal const string DEFAULT_TEXTURE_SETTINGS_REFERENCE = ""; + public string textureSettingsReference = DEFAULT_TEXTURE_SETTINGS_REFERENCE; + + public bool UsesPMAWorkflow { + get { + return IsPMAWorkflow(textureSettingsReference); + } + } + public static bool IsPMAWorkflow(string textureSettingsReference) { + if (textureSettingsReference == null) + return true; + string settingsReference = textureSettingsReference.ToLower(); + if (settingsReference.Contains("straight") || !settingsReference.Contains("pma")) + return false; + return true; + } + + public const string DEFAULT_BLEND_MODE_MULTIPLY_MATERIAL = "SkeletonPMAMultiply"; + public const string DEFAULT_BLEND_MODE_SCREEN_MATERIAL = "SkeletonPMAScreen"; + public const string DEFAULT_BLEND_MODE_ADDITIVE_MATERIAL = "SkeletonPMAAdditive"; + + public Material blendModeMaterialMultiply = null; + public Material blendModeMaterialScreen = null; + public Material blendModeMaterialAdditive = null; + + public string FindPathOfAsset (string assetName) { + string typeSearchString = assetName; + string[] guids = AssetDatabase.FindAssets(typeSearchString); + if (guids.Length > 0) { + return AssetDatabase.GUIDToAssetPath(guids[0]); + } + return null; + } + + public Material BlendModeMaterialMultiply { + get { + if (blendModeMaterialMultiply == null) { + string path = FindPathOfAsset(DEFAULT_BLEND_MODE_MULTIPLY_MATERIAL); + blendModeMaterialMultiply = AssetDatabase.LoadAssetAtPath(path); + } + return blendModeMaterialMultiply; + } + } + public Material BlendModeMaterialScreen { + get { + if (blendModeMaterialScreen == null) { + string path = FindPathOfAsset(DEFAULT_BLEND_MODE_SCREEN_MATERIAL); + blendModeMaterialScreen = AssetDatabase.LoadAssetAtPath(path); + } + return blendModeMaterialScreen; + } + } + public Material BlendModeMaterialAdditive { + get { + if (blendModeMaterialAdditive == null) { + string path = FindPathOfAsset(DEFAULT_BLEND_MODE_ADDITIVE_MATERIAL); + blendModeMaterialAdditive = AssetDatabase.LoadAssetAtPath(path); + } + return blendModeMaterialAdditive; + } + } + + internal const bool DEFAULT_ATLASTXT_WARNING = true; + public bool atlasTxtImportWarning = DEFAULT_ATLASTXT_WARNING; + + internal const bool DEFAULT_TEXTUREIMPORTER_WARNING = true; + public bool textureImporterWarning = DEFAULT_TEXTUREIMPORTER_WARNING; + + internal const bool DEFAULT_COMPONENTMATERIAL_WARNING = true; + public bool componentMaterialWarning = DEFAULT_COMPONENTMATERIAL_WARNING; + + public const float DEFAULT_MIPMAPBIAS = -0.5f; + + public const bool DEFAULT_AUTO_RELOAD_SCENESKELETONS = true; + public bool autoReloadSceneSkeletons = DEFAULT_AUTO_RELOAD_SCENESKELETONS; + + public const string SCENE_ICONS_SCALE_KEY = "SPINE_SCENE_ICONS_SCALE"; + internal const float DEFAULT_SCENE_ICONS_SCALE = 1f; + [Range(0.01f, 2f)] + public float handleScale = DEFAULT_SCENE_ICONS_SCALE; + + public const bool DEFAULT_MECANIM_EVENT_INCLUDE_FOLDERNAME = true; + public bool mecanimEventIncludeFolderName = DEFAULT_MECANIM_EVENT_INCLUDE_FOLDERNAME; + + // Timeline extension module + public const bool DEFAULT_TIMELINE_USE_BLEND_DURATION = true; + public bool timelineUseBlendDuration = DEFAULT_TIMELINE_USE_BLEND_DURATION; + +#if NEW_PREFERENCES_SETTINGS_PROVIDER + public static void Load () { + GetOrCreateSettings(); + } + + static SpinePreferences settings = null; + + internal static SpinePreferences GetOrCreateSettings () { + if (settings != null) + return settings; + + settings = AssetDatabase.LoadAssetAtPath(SPINE_SETTINGS_ASSET_PATH); + if (settings == null) + settings = FindSpinePreferences(); + if (settings == null) + { + settings = ScriptableObject.CreateInstance(); + SpineEditorUtilities.OldPreferences.CopyOldToNewPreferences(ref settings); + // Multiple threads may be calling this method during import, creating the folder + // multiple times with ascending number suffix. Atomic wasPreferencesDirCreated int + // variable is used to prevent any redundant create operations. + if (!AssetDatabase.IsValidFolder("Assets/Editor") && Interlocked.Exchange(ref wasPreferencesDirCreated, 1) == 0) + AssetDatabase.CreateFolder("Assets", "Editor"); + if (Interlocked.Exchange(ref wasPreferencesAssetCreated, 1) == 0) + AssetDatabase.CreateAsset(settings, SPINE_SETTINGS_ASSET_PATH); + } + return settings; + } + + static SpinePreferences FindSpinePreferences () { + string typeSearchString = " t:SpinePreferences"; + string[] guids = AssetDatabase.FindAssets(typeSearchString); + foreach (string guid in guids) { + string path = AssetDatabase.GUIDToAssetPath(guid); + var preferences = AssetDatabase.LoadAssetAtPath(path); + if (preferences != null) + return preferences; + } + return null; + } + + public static void HandlePreferencesGUI (SerializedObject settings) { + + float prevLabelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 250; + + using (new EditorGUI.IndentLevelScope()) { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(settings.FindProperty("showHierarchyIcons"), new GUIContent("Show Hierarchy Icons", "Show relevant icons on GameObjects with Spine Components on them. Disable this if you have large, complex scenes.")); + if (EditorGUI.EndChangeCheck()) { +#if NEWPLAYMODECALLBACKS + SpineEditorUtilities.HierarchyHandler.IconsOnPlaymodeStateChanged(PlayModeStateChange.EnteredEditMode); +#else + SpineEditorUtilities.HierarchyHandler.IconsOnPlaymodeStateChanged(); +#endif + } + + EditorGUILayout.PropertyField(settings.FindProperty("autoReloadSceneSkeletons"), new GUIContent("Auto-reload scene components", "Reloads Skeleton components in the scene whenever their SkeletonDataAsset is modified. This makes it so changes in the SkeletonDataAsset inspector are immediately reflected. This may be slow when your scenes have large numbers of SkeletonRenderers or SkeletonGraphic.")); + + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("Auto-Import Settings", EditorStyles.boldLabel); + { + SpineEditorUtilities.FloatPropertyField(settings.FindProperty("defaultMix"), new GUIContent("Default Mix", "The Default Mix Duration for newly imported SkeletonDataAssets."), min: 0f); + SpineEditorUtilities.FloatPropertyField(settings.FindProperty("defaultScale"), new GUIContent("Default SkeletonData Scale", "The Default skeleton import scale for newly imported SkeletonDataAssets."), min: 0.0000001f); + + SpineEditorUtilities.ShaderPropertyField(settings.FindProperty("defaultShader"), new GUIContent("Default Shader"), SpinePreferences.DEFAULT_DEFAULT_SHADER); + + EditorGUILayout.PropertyField(settings.FindProperty("setTextureImporterSettings"), new GUIContent("Apply Atlas Texture Settings", "Apply reference settings for Texture Importers.")); + var textureSettingsRef = settings.FindProperty("textureSettingsReference"); + SpineEditorUtilities.PresetAssetPropertyField(textureSettingsRef, new GUIContent("Atlas Texture Settings", "Apply the selected texture import settings at newly imported atlas textures. When exporting atlas textures from Spine with \"Premultiply alpha\" enabled (the default), you can leave it at \"PMATexturePreset\". If you have disabled \"Premultiply alpha\", set it to \"StraightAlphaTexturePreset\". You can also create your own TextureImporter Preset asset and assign it here.")); + if (string.IsNullOrEmpty(textureSettingsRef.stringValue)) { + var pmaTextureSettingsReferenceGUIDS = AssetDatabase.FindAssets("PMATexturePreset"); + if (pmaTextureSettingsReferenceGUIDS.Length > 0) { + var assetPath = AssetDatabase.GUIDToAssetPath(pmaTextureSettingsReferenceGUIDS[0]); + if (!string.IsNullOrEmpty(assetPath)) + textureSettingsRef.stringValue = assetPath; + } + } + + EditorGUILayout.PropertyField(settings.FindProperty("blendModeMaterialAdditive"), new GUIContent("Additive Material", "Additive blend mode Material template.")); + EditorGUILayout.PropertyField(settings.FindProperty("blendModeMaterialMultiply"), new GUIContent("Multiply Material", "Multiply blend mode Material template.")); + EditorGUILayout.PropertyField(settings.FindProperty("blendModeMaterialScreen"), new GUIContent("Screen Material", "Screen blend mode Material template.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Warnings", EditorStyles.boldLabel); + { + EditorGUILayout.PropertyField(settings.FindProperty("atlasTxtImportWarning"), new GUIContent("Atlas Extension Warning", "Log a warning and recommendation whenever a `.atlas` file is found.")); + EditorGUILayout.PropertyField(settings.FindProperty("textureImporterWarning"), new GUIContent("Texture Settings Warning", "Log a warning and recommendation whenever Texture Import Settings are detected that could lead to undesired effects, e.g. white border artifacts.")); + EditorGUILayout.PropertyField(settings.FindProperty("componentMaterialWarning"), new GUIContent("Component & Material Warning", "Log a warning and recommendation whenever Component and Material settings are not compatible.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Editor Instantiation", EditorStyles.boldLabel); + { + EditorGUILayout.Slider(settings.FindProperty("defaultZSpacing"), -0.1f, 0f, new GUIContent("Default Slot Z-Spacing")); + EditorGUILayout.PropertyField(settings.FindProperty("defaultInstantiateLoop"), new GUIContent("Default Loop", "Spawn Spine GameObjects with loop enabled.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Mecanim Bake Settings", EditorStyles.boldLabel); + { + EditorGUILayout.PropertyField(settings.FindProperty("mecanimEventIncludeFolderName"), new GUIContent("Include Folder Name in Event", "When enabled, Mecanim events will call methods named 'FolderNameEventName', when disabled it will call 'EventName'.")); + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Handles and Gizmos", EditorStyles.boldLabel); + { + EditorGUI.BeginChangeCheck(); + var scaleProperty = settings.FindProperty("handleScale"); + EditorGUILayout.PropertyField(scaleProperty, new GUIContent("Editor Bone Scale")); + if (EditorGUI.EndChangeCheck()) { + EditorPrefs.SetFloat(SpinePreferences.SCENE_ICONS_SCALE_KEY, scaleProperty.floatValue); + SceneView.RepaintAll(); + } + } + + #if SPINE_TK2D_DEFINE + bool isTK2DDefineSet = true; + #else + bool isTK2DDefineSet = false; + #endif + bool isTK2DAllowed = SpineEditorUtilities.SpineTK2DEditorUtility.IsTK2DAllowed; + if (SpineEditorUtilities.SpineTK2DEditorUtility.IsTK2DInstalled() || isTK2DDefineSet) { + GUILayout.Space(20); + EditorGUILayout.LabelField("3rd Party Settings", EditorStyles.boldLabel); + using (new GUILayout.HorizontalScope()) { + EditorGUILayout.PrefixLabel("Define TK2D"); + if (isTK2DAllowed && GUILayout.Button("Enable", GUILayout.Width(64))) + SpineEditorUtilities.SpineTK2DEditorUtility.EnableTK2D(); + if (GUILayout.Button("Disable", GUILayout.Width(64))) + SpineEditorUtilities.SpineTK2DEditorUtility.DisableTK2D(); + } + #if !SPINE_TK2D_DEFINE + if (!isTK2DAllowed) { + EditorGUILayout.LabelField("To allow TK2D support, please modify line 67 in", EditorStyles.boldLabel); + EditorGUILayout.LabelField("Spine/Editor/spine-unity/Editor/Util./BuildSettings.cs", EditorStyles.boldLabel); + } + #endif + } + + GUILayout.Space(20); + EditorGUILayout.LabelField("Timeline Extension", EditorStyles.boldLabel); + { + EditorGUILayout.PropertyField(settings.FindProperty("timelineUseBlendDuration"), new GUIContent("Use Blend Duration", "When enabled, MixDuration will be synced with timeline clip transition duration 'Ease In Duration'.")); + } + } + EditorGUIUtility.labelWidth = prevLabelWidth; + } +#endif // NEW_PREFERENCES_SETTINGS_PROVIDER + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs.meta new file mode 100644 index 0000000..b473afe --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpinePreferences.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b29e98153ec2fbd44b8f7da1b41194e8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs new file mode 100644 index 0000000..3e6d866 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs @@ -0,0 +1,170 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace Spine.Unity.Editor { + + using Editor = UnityEditor.Editor; + using Icons = SpineEditorUtilities.Icons; + + public class SpriteAtlasImportWindow : EditorWindow { + const bool IsUtilityWindow = false; + + [MenuItem("Window/Spine/SpriteAtlas Import", false, 5000)] + public static void Init (MenuCommand command) { + var window = EditorWindow.GetWindow(IsUtilityWindow); + window.minSize = new Vector2(284f, 256f); + window.maxSize = new Vector2(500f, 256f); + window.titleContent = new GUIContent("Spine SpriteAtlas Import", Icons.spine); + window.Show(); + } + + public UnityEngine.U2D.SpriteAtlas spriteAtlasAsset; + public TextAsset skeletonDataFile; + public SpineSpriteAtlasAsset spineSpriteAtlasAsset; + + SerializedObject so; + + void OnEnable () { + if (!SpineSpriteAtlasAsset.AnySpriteAtlasNeedsRegionsLoaded()) + return; + EditorApplication.update -= SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + EditorApplication.update += SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + } + + void OnDisable () { + EditorApplication.update -= SpineSpriteAtlasAsset.UpdateWhenEditorPlayModeStarted; + } + + void OnGUI () { + so = so ?? new SerializedObject(this); + + EditorGUIUtility.wideMode = true; + EditorGUILayout.LabelField("Spine SpriteAtlas Import", EditorStyles.boldLabel); + + using (new SpineInspectorUtility.BoxScope()) { + EditorGUI.BeginChangeCheck(); + var spriteAtlasAssetProperty = so.FindProperty("spriteAtlasAsset"); + EditorGUILayout.PropertyField(spriteAtlasAssetProperty, new GUIContent("SpriteAtlas", EditorGUIUtility.IconContent("SpriteAtlas Icon").image)); + if (EditorGUI.EndChangeCheck()) { + so.ApplyModifiedProperties(); + if (spriteAtlasAsset != null) { + if (AssetUtility.SpriteAtlasSettingsNeedAdjustment(spriteAtlasAsset)) { + AssetUtility.AdjustSpriteAtlasSettings(spriteAtlasAsset); + } + GenerateAssetsFromSpriteAtlas(spriteAtlasAsset); + } + } + + var spineSpriteAtlasAssetProperty = so.FindProperty("spineSpriteAtlasAsset"); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(spineSpriteAtlasAssetProperty, new GUIContent("SpineSpriteAtlasAsset", EditorGUIUtility.IconContent("ScriptableObject Icon").image)); + if (spineSpriteAtlasAssetProperty.objectReferenceValue == null) { + spineSpriteAtlasAssetProperty.objectReferenceValue = spineSpriteAtlasAsset = FindSpineSpriteAtlasAsset(spriteAtlasAsset); + } + if (EditorGUI.EndChangeCheck()) { + so.ApplyModifiedProperties(); + } + EditorGUILayout.Space(); + + using (new EditorGUI.DisabledScope(spineSpriteAtlasAsset == null)) { + if (SpineInspectorUtility.LargeCenteredButton(new GUIContent("Load regions by entering Play mode"))) { + GenerateAssetsFromSpriteAtlas(spriteAtlasAsset); + SpineSpriteAtlasAsset.UpdateByStartingEditorPlayMode(); + } + } + + using (new SpineInspectorUtility.BoxScope()) { + if (spriteAtlasAsset == null) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Please assign SpriteAtlas file.", Icons.warning), GUILayout.Height(46)); + } + else if (spineSpriteAtlasAsset == null || spineSpriteAtlasAsset.RegionsNeedLoading) { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Please hit 'Load regions ..' to load\nregion info. Play mode is started\nand stopped automatically.", Icons.warning), GUILayout.Height(54)); + } + else { + EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("SpriteAtlas imported\nsuccessfully.", Icons.spine), GUILayout.Height(46)); + } + } + } + + bool isAtlasComplete = (spineSpriteAtlasAsset != null && !spineSpriteAtlasAsset.RegionsNeedLoading); + bool canImportSkeleton = (spriteAtlasAsset != null && skeletonDataFile != null); + using (new SpineInspectorUtility.BoxScope()) { + + using (new EditorGUI.DisabledScope(!isAtlasComplete)) { + var skeletonDataAssetProperty = so.FindProperty("skeletonDataFile"); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(skeletonDataAssetProperty, SpineInspectorUtility.TempContent("Skeleton json/skel file", Icons.spine)); + if (EditorGUI.EndChangeCheck()) { + so.ApplyModifiedProperties(); + } + EditorGUILayout.Space(); + } + using (new EditorGUI.DisabledScope(!canImportSkeleton)) { + if (SpineInspectorUtility.LargeCenteredButton(new GUIContent("Import Skeleton"))) { + //AssetUtility.IngestSpriteAtlas(spriteAtlasAsset, null); + string skeletonPath = AssetDatabase.GetAssetPath(skeletonDataFile); + string[] skeletons = new string[] { skeletonPath }; + AssetUtility.ImportSpineContent(skeletons, null); + } + } + } + } + + void GenerateAssetsFromSpriteAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlasAsset) { + AssetUtility.IngestSpriteAtlas(spriteAtlasAsset, null); + string texturePath; + if (AssetUtility.GeneratePngFromSpriteAtlas(spriteAtlasAsset, out texturePath)) { + Debug.Log(string.Format("Generated SpriteAtlas texture '{0}'", texturePath), spriteAtlasAsset); + } + } + + SpineSpriteAtlasAsset FindSpineSpriteAtlasAsset (UnityEngine.U2D.SpriteAtlas spriteAtlasAsset) { + string path = AssetDatabase.GetAssetPath(spriteAtlasAsset).Replace(".spriteatlas", AssetUtility.SpriteAtlasSuffix + ".asset"); + if (System.IO.File.Exists(path)) { + return AssetDatabase.LoadAssetAtPath(path); + } + return null; + } + + SkeletonDataAsset FindSkeletonDataAsset (TextAsset skeletonDataFile) { + string path = AssetDatabase.GetAssetPath(skeletonDataFile); + path = path.Replace(".json", AssetUtility.SkeletonDataSuffix + ".asset"); + path = path.Replace(".skel.bytes", AssetUtility.SkeletonDataSuffix + ".asset"); + if (System.IO.File.Exists(path)) { + return AssetDatabase.LoadAssetAtPath(path); + } + return null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs.meta new file mode 100644 index 0000000..2eb64bd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Editor/Windows/SpriteAtlasImportWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5b99b091defeef439a0cb8c99fd8a51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules.meta new file mode 100644 index 0000000..51ffc9e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ef0ff8deb3a288646a1dd7243a918196 +folderAsset: yes +timeCreated: 1527569389 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator.meta new file mode 100644 index 0000000..40aec39 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1bf8fd476d074f449bbae932a1c8a360 +folderAsset: yes +timeCreated: 1527569465 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor.meta new file mode 100644 index 0000000..1d2ca48 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 211465c9f045fd142abe552a6ffdc799 +folderAsset: yes +timeCreated: 1457405813 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs new file mode 100644 index 0000000..79d4d9e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs @@ -0,0 +1,58 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using Spine.Unity.Editor; + +namespace Spine.Unity.Examples { + [CustomEditor(typeof(SkeletonPartsRenderer))] + public class SkeletonRenderPartInspector : UnityEditor.Editor { + SpineInspectorUtility.SerializedSortingProperties sortingProperties; + + void OnEnable () { + sortingProperties = new SpineInspectorUtility.SerializedSortingProperties(SpineInspectorUtility.GetRenderersSerializedObject(serializedObject)); + } + + public override void OnInspectorGUI () { + SpineInspectorUtility.SortingPropertyFields(sortingProperties, true); + + if (!serializedObject.isEditingMultipleObjects) { + EditorGUILayout.Space(); + if (SpineInspectorUtility.LargeCenteredButton(new GUIContent("Select SkeletonRenderer", SpineEditorUtilities.Icons.spine))) { + var thisSkeletonPartsRenderer = target as SkeletonPartsRenderer; + var srs = thisSkeletonPartsRenderer.GetComponentInParent(); + if (srs != null && srs.partsRenderers.Contains(thisSkeletonPartsRenderer) && srs.SkeletonRenderer != null) + Selection.activeGameObject = srs.SkeletonRenderer.gameObject; + } + } + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs.meta new file mode 100644 index 0000000..a97d662 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonPartsRendererInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 30e43037bf4433645ad70266f34c1c8b +timeCreated: 1458051036 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs new file mode 100644 index 0000000..1971259 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs @@ -0,0 +1,323 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using UnityEditor; + +using System.Collections.Generic; + +using Spine.Unity; +using Spine.Unity.Editor; + +namespace Spine.Unity.Examples { + + [CustomEditor(typeof(SkeletonRenderSeparator))] + public class SkeletonRenderSeparatorInspector : UnityEditor.Editor { + SkeletonRenderSeparator component; + + // Properties + SerializedProperty skeletonRenderer_, copyPropertyBlock_, copyMeshRendererFlags_, partsRenderers_; + static bool partsRenderersExpanded = false; + + // For separator field. + SerializedObject skeletonRendererSerializedObject; + SerializedProperty separatorNamesProp; + static bool skeletonRendererExpanded = true; + bool slotsReapplyRequired = false; + bool partsRendererInitRequired = false; + + void OnEnable () { + if (component == null) + component = target as SkeletonRenderSeparator; + + skeletonRenderer_ = serializedObject.FindProperty("skeletonRenderer"); + copyPropertyBlock_ = serializedObject.FindProperty("copyPropertyBlock"); + copyMeshRendererFlags_ = serializedObject.FindProperty("copyMeshRendererFlags"); + + var partsRenderers = component.partsRenderers; + partsRenderers_ = serializedObject.FindProperty("partsRenderers"); + partsRenderers_.isExpanded = partsRenderersExpanded || // last state + partsRenderers.Contains(null) || // null items found + partsRenderers.Count < 1 || // no parts renderers + (skeletonRenderer_.objectReferenceValue != null && SkeletonRendererSeparatorCount + 1 > partsRenderers.Count); // not enough parts renderers + } + + int SkeletonRendererSeparatorCount { + get { + if (Application.isPlaying) + return component.SkeletonRenderer.separatorSlots.Count; + else + return separatorNamesProp == null ? 0 : separatorNamesProp.arraySize; + } + } + + public override void OnInspectorGUI () { + + // Restore mesh part for undo logic after undo of "Add Parts Renderer". + // Triggers regeneration and assignment of the mesh filter's mesh. + + bool isMeshFilterAlwaysNull = false; + #if UNITY_EDITOR && NEW_PREFAB_SYSTEM + // Don't store mesh or material at the prefab, otherwise it will permanently reload + var prefabType = UnityEditor.PrefabUtility.GetPrefabAssetType(component); + if (UnityEditor.PrefabUtility.IsPartOfPrefabAsset(component) && + (prefabType == UnityEditor.PrefabAssetType.Regular || prefabType == UnityEditor.PrefabAssetType.Variant)) { + isMeshFilterAlwaysNull = true; + } + #endif + + if (!isMeshFilterAlwaysNull && component.GetComponent() && component.GetComponent().sharedMesh == null) { + component.OnDisable(); + component.OnEnable(); + } + + var componentRenderers = component.partsRenderers; + int totalParts; + + using (new SpineInspectorUtility.LabelWidthScope()) { + bool componentEnabled = component.enabled; + bool checkBox = EditorGUILayout.Toggle("Enable Separator", componentEnabled); + if (checkBox != componentEnabled) + component.enabled = checkBox; + if (component.SkeletonRenderer.disableRenderingOnOverride && !component.enabled) + EditorGUILayout.HelpBox("By default, SkeletonRenderer's MeshRenderer is disabled while the SkeletonRenderSeparator takes over rendering. It is re-enabled when SkeletonRenderSeparator is disabled.", MessageType.Info); + + EditorGUILayout.PropertyField(copyPropertyBlock_); + EditorGUILayout.PropertyField(copyMeshRendererFlags_); + } + + // SkeletonRenderer Box + using (new SpineInspectorUtility.BoxScope(false)) { + // Fancy SkeletonRenderer foldout reference field + { + EditorGUI.indentLevel++; + EditorGUI.BeginChangeCheck(); + var foldoutSkeletonRendererRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); + EditorGUI.PropertyField(foldoutSkeletonRendererRect, skeletonRenderer_); + if (EditorGUI.EndChangeCheck()) + serializedObject.ApplyModifiedProperties(); + if (component.SkeletonRenderer != null) { + skeletonRendererExpanded = EditorGUI.Foldout(foldoutSkeletonRendererRect, skeletonRendererExpanded, ""); + } + EditorGUI.indentLevel--; + } + + int separatorCount = 0; + EditorGUI.BeginChangeCheck(); + if (component.SkeletonRenderer != null) { + // Separators from SkeletonRenderer + { + bool skeletonRendererMismatch = skeletonRendererSerializedObject != null && skeletonRendererSerializedObject.targetObject != component.SkeletonRenderer; + if (separatorNamesProp == null || skeletonRendererMismatch) { + if (component.SkeletonRenderer != null) { + skeletonRendererSerializedObject = new SerializedObject(component.SkeletonRenderer); + separatorNamesProp = skeletonRendererSerializedObject.FindProperty("separatorSlotNames"); + separatorNamesProp.isExpanded = true; + } + } + + if (separatorNamesProp != null) { + if (skeletonRendererExpanded) { + EditorGUI.indentLevel++; + SkeletonRendererInspector.SeparatorsField(separatorNamesProp); + EditorGUI.indentLevel--; + } + separatorCount = this.SkeletonRendererSeparatorCount; + } + } + + if (SkeletonRendererSeparatorCount == 0) { + EditorGUILayout.HelpBox("Separators are empty. Change the size to 1 and choose a slot if you want the render to be separated.", MessageType.Info); + } + } + + if (EditorGUI.EndChangeCheck()) { + skeletonRendererSerializedObject.ApplyModifiedProperties(); + + if (!Application.isPlaying) + slotsReapplyRequired = true; + } + + + totalParts = separatorCount + 1; + var counterStyle = skeletonRendererExpanded ? EditorStyles.label : EditorStyles.miniLabel; + EditorGUILayout.LabelField(string.Format("{0}: separates into {1}.", SpineInspectorUtility.Pluralize(separatorCount, "separator", "separators"), SpineInspectorUtility.Pluralize(totalParts, "part", "parts") ), counterStyle); + } + + // Parts renderers + using (new SpineInspectorUtility.BoxScope(false)) { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.partsRenderers_, true); + EditorGUI.indentLevel--; + + // Null items warning + bool nullItemsFound = componentRenderers.Contains(null); + if (nullItemsFound) + EditorGUILayout.HelpBox("Some items in the parts renderers list are null and may cause problems.\n\nYou can right-click on that element and choose 'Delete Array Element' to remove it.", MessageType.Warning); + + // (Button) Match Separators count + if (separatorNamesProp != null) { + int currentRenderers = 0; + foreach (var r in componentRenderers) { + if (r != null) + currentRenderers++; + } + int extraRenderersNeeded = totalParts - currentRenderers; + + if (component.enabled && component.SkeletonRenderer != null && extraRenderersNeeded > 0) { + EditorGUILayout.HelpBox(string.Format("Insufficient parts renderers. Some parts will not be rendered."), MessageType.Warning); + string addMissingLabel = string.Format("Add the missing renderer{1} ({0}) ", extraRenderersNeeded, SpineInspectorUtility.PluralThenS(extraRenderersNeeded)); + if (GUILayout.Button(addMissingLabel, GUILayout.Height(30f))) { + AddPartsRenderer(extraRenderersNeeded); + DetectOrphanedPartsRenderers(component); + partsRendererInitRequired = true; + } + } + } + + if (partsRenderers_.isExpanded != partsRenderersExpanded) partsRenderersExpanded = partsRenderers_.isExpanded; + if (partsRenderers_.isExpanded) { + using (new EditorGUILayout.HorizontalScope()) { + // (Button) Destroy Renderers button + if (componentRenderers.Count > 0) { + if (GUILayout.Button("Clear Parts Renderers")) { + // Do you really want to destroy all? + Undo.RegisterCompleteObjectUndo(component, "Clear Parts Renderers"); + if (EditorUtility.DisplayDialog("Destroy Renderers", "Do you really want to destroy all the Parts Renderer GameObjects in the list?", "Destroy", "Cancel")) { + foreach (var r in componentRenderers) { + if (r != null) + Undo.DestroyObjectImmediate(r.gameObject); + } + componentRenderers.Clear(); + // Do you also want to destroy orphans? (You monster.) + DetectOrphanedPartsRenderers(component); + } + } + } + + // (Button) Add Part Renderer button + if (GUILayout.Button("Add Parts Renderer")) { + AddPartsRenderer(1); + partsRendererInitRequired = true; + } + } + } + } + + serializedObject.ApplyModifiedProperties(); + + if (partsRendererInitRequired) { + Undo.RegisterCompleteObjectUndo(component.GetComponent(), "Add Parts Renderers"); + component.OnEnable(); + partsRendererInitRequired = false; + } + + if (slotsReapplyRequired && UnityEngine.Event.current.type == EventType.Repaint) { + component.SkeletonRenderer.ReapplySeparatorSlotNames(); + component.SkeletonRenderer.LateUpdate(); + SceneView.RepaintAll(); + slotsReapplyRequired = false; + } + } + + public void AddPartsRenderer (int count) { + var componentRenderers = component.partsRenderers; + bool emptyFound = componentRenderers.Contains(null); + if (emptyFound) { + bool userClearEntries = EditorUtility.DisplayDialog("Empty entries found", "Null entries found. Do you want to remove null entries before adding the new renderer? ", "Clear Empty Entries", "Don't Clear"); + if (userClearEntries) componentRenderers.RemoveAll(x => x == null); + } + + Undo.RegisterCompleteObjectUndo(component, "Add Parts Renderers"); + for (int i = 0; i < count; i++) { + int index = componentRenderers.Count; + var smr = SkeletonPartsRenderer.NewPartsRendererGameObject(component.transform, index.ToString()); + Undo.RegisterCreatedObjectUndo(smr.gameObject, "New Parts Renderer GameObject."); + componentRenderers.Add(smr); + + // increment renderer sorting order. + if (index == 0) continue; + var prev = componentRenderers[index - 1]; if (prev == null) continue; + + var prevMeshRenderer = prev.GetComponent(); + var currentMeshRenderer = smr.GetComponent(); + if (prevMeshRenderer == null || currentMeshRenderer == null) continue; + + int prevSortingLayer = prevMeshRenderer.sortingLayerID; + int prevSortingOrder = prevMeshRenderer.sortingOrder; + currentMeshRenderer.sortingLayerID = prevSortingLayer; + currentMeshRenderer.sortingOrder = prevSortingOrder + SkeletonRenderSeparator.DefaultSortingOrderIncrement; + } + + } + + /// Detects orphaned parts renderers and offers to delete them. + public void DetectOrphanedPartsRenderers (SkeletonRenderSeparator component) { + var children = component.GetComponentsInChildren(); + + var orphans = new System.Collections.Generic.List(); + foreach (var r in children) { + if (!component.partsRenderers.Contains(r)) + orphans.Add(r); + } + + if (orphans.Count > 0) { + if (EditorUtility.DisplayDialog("Destroy Submesh Renderers", "Unassigned renderers were found. Do you want to delete them? (These may belong to another Render Separator in the same hierarchy. If you don't have another Render Separator component in the children of this GameObject, it's likely safe to delete. Warning: This operation cannot be undone.)", "Delete", "Cancel")) { + foreach (var o in orphans) { + Undo.DestroyObjectImmediate(o.gameObject); + } + } + } + } + + #region SkeletonRenderer Context Menu Item + [MenuItem ("CONTEXT/SkeletonRenderer/Add Skeleton Render Separator")] + static void AddRenderSeparatorComponent (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + var newComponent = skeletonRenderer.gameObject.AddComponent(); + + Undo.RegisterCreatedObjectUndo(newComponent, "Add SkeletonRenderSeparator"); + } + + // Validate + [MenuItem ("CONTEXT/SkeletonRenderer/Add Skeleton Render Separator", true)] + static bool ValidateAddRenderSeparatorComponent (MenuCommand cmd) { + var skeletonRenderer = cmd.context as SkeletonRenderer; + var separator = skeletonRenderer.GetComponent(); + bool separatorNotOnObject = separator == null; + return separatorNotOnObject; + } + #endregion + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs.meta new file mode 100644 index 0000000..7e8e658 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d2a5062cfe5dd4344831cda4723128af +timeCreated: 1458067064 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes.meta new file mode 100644 index 0000000..34d8d7e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 18ee2876d53412642bbfa1070a1b947f +folderAsset: yes +timeCreated: 1527569487 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor.meta new file mode 100644 index 0000000..80a6cfc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1ad4318c20ec5674a9f4d7f786afd681 +folderAsset: yes +timeCreated: 1496449217 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs new file mode 100644 index 0000000..8899952 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs @@ -0,0 +1,47 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using Spine.Unity.Deprecated; +using System; + +namespace Spine.Unity.Editor { + using Editor = UnityEditor.Editor; + + [Obsolete("The spine-unity 3.7 runtime introduced SkeletonDataModifierAssets BlendModeMaterials which replaced SlotBlendModes. Will be removed in spine-unity 3.9.", false)] + public class SlotBlendModesEditor : Editor { + + [MenuItem("CONTEXT/SkeletonRenderer/Add Slot Blend Modes Component")] + static void AddSlotBlendModesComponent (MenuCommand command) { + var skeletonRenderer = (SkeletonRenderer)command.context; + skeletonRenderer.gameObject.AddComponent(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs.meta new file mode 100644 index 0000000..21d0e26 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Editor/spine-unity/Modules/SlotBlendModes/Editor/SlotBlendModesEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cbec7dc66dca80a419477536c23b7a0d +timeCreated: 1496449255 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime.meta new file mode 100644 index 0000000..b6b0c1b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ddb0e27aa2258854a8d171196f395b87 +folderAsset: yes +timeCreated: 1527569312 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp.meta new file mode 100644 index 0000000..81ebc4e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a60dd41ef13d98647b9f963089feb7b0 +folderAsset: yes +timeCreated: 1456265151 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs new file mode 100644 index 0000000..70c1b33 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs @@ -0,0 +1,1819 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + + /// + /// A simple container for a list of timelines and a name. + public class Animation { + internal String name; + internal ExposedList timelines; + internal HashSet timelineIds; + internal float duration; + + public Animation (string name, ExposedList timelines, float duration) { + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + if (timelines == null) throw new ArgumentNullException("timelines", "timelines cannot be null."); + // Note: avoiding reallocations by adding all hash set entries at + // once (EnsureCapacity() is only available in newer .Net versions). + int[] propertyIDs = new int[timelines.Count]; + for (int i = 0; i < timelines.Count; ++i) { + propertyIDs[i] = timelines.Items[i].PropertyId; + } + this.timelineIds = new HashSet(propertyIDs); + this.name = name; + this.timelines = timelines; + this.duration = duration; + } + + public ExposedList Timelines { get { return timelines; } set { timelines = value; } } + + /// The duration of the animation in seconds, which is the highest time of all keys in the timeline. + public float Duration { get { return duration; } set { duration = value; } } + + /// The animation's name, which is unique across all animations in the skeleton. + public string Name { get { return name; } } + + /// Whether the timeline with the property id is contained in this animation. + public bool HasTimeline (int id) { + return timelineIds.Contains(id); + } + + /// Applies all the animation's timelines to the specified skeleton. + /// + public void Apply (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList events, float alpha, MixBlend blend, + MixDirection direction) { + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + + if (loop && duration != 0) { + time %= duration; + if (lastTime > 0) lastTime %= duration; + } + + ExposedList timelines = this.timelines; + for (int i = 0, n = timelines.Count; i < n; i++) + timelines.Items[i].Apply(skeleton, lastTime, time, events, alpha, blend, direction); + } + + override public string ToString () { + return name; + } + + /// After the first and before the last entry. + /// Index of first value greater than the target. + internal static int BinarySearch (float[] values, float target, int step) { + int low = 0; + int high = values.Length / step - 2; + if (high == 0) return step; + int current = (int)((uint)high >> 1); + while (true) { + if (values[(current + 1) * step] <= target) + low = current + 1; + else + high = current; + if (low == high) return (low + 1) * step; + current = (int)((uint)(low + high) >> 1); + } + } + + /// After the first and before the last entry. + internal static int BinarySearch (float[] values, float target) { + int low = 0; + int high = values.Length - 2; + if (high == 0) return 1; + int current = (int)((uint)high >> 1); + while (true) { + if (values[current + 1] <= target) + low = current + 1; + else + high = current; + if (low == high) return (low + 1); + current = (int)((uint)(low + high) >> 1); + } + } + + internal static int LinearSearch (float[] values, float target, int step) { + for (int i = 0, last = values.Length - step; i <= last; i += step) + if (values[i] > target) return i; + return -1; + } + } + + /// + /// The interface for all timelines. + public interface Timeline { + /// Applies this timeline to the skeleton. + /// The skeleton the timeline is being applied to. This provides access to the bones, slots, and other + /// skeleton components the timeline may change. + /// The time this timeline was last applied. Timelines such as trigger only at specific + /// times rather than every frame. In that case, the timeline triggers everything between lastTime + /// (exclusive) and time (inclusive). + /// The time within the animation. Most timelines find the key before and the key after this time so they can + /// interpolate between the keys. + /// If any events are fired, they are added to this list. Can be null to ignore firing events or if the + /// timeline does not fire events. + /// 0 applies the current or setup value (depending on blend). 1 applies the timeline value. + /// Between 0 and 1 applies a value between the current or setup value and the timeline value. By adjusting + /// alpha over time, an animation can be mixed in or out. alpha can also be useful to + /// apply animations on top of each other (layered). + /// Controls how mixing is applied when alpha < 1. + /// Indicates whether the timeline is mixing in or out. Used by timelines which perform instant transitions, + /// such as or , and other such as {@link ScaleTimeline}. + void Apply (Skeleton skeleton, float lastTime, float time, ExposedList events, float alpha, MixBlend blend, MixDirection direction); + /// Uniquely encodes both the type of this timeline and the skeleton property that it affects. + int PropertyId { get; } + } + + /// + /// Controls how a timeline is mixed with the setup or current pose. + /// + public enum MixBlend { + + /// Transitions from the setup value to the timeline value (the current value is not used). Before the first key, the setup + /// value is set. + Setup, + + /// + /// + /// Transitions from the current value to the timeline value. Before the first key, transitions from the current value to + /// the setup value. Timelines which perform instant transitions, such as or + /// , use the setup value before the first key. + /// + /// First is intended for the first animations applied, not for animations layered on top of those. + /// + First, + + /// + /// + /// Transitions from the current value to the timeline value. No change is made before the first key (the current value is + /// kept until the first key). + /// + /// Replace is intended for animations layered on top of others, not for the first animations applied. + /// + Replace, + + /// + /// + /// Transitions from the current value to the current value plus the timeline value. No change is made before the first key + /// (the current value is kept until the first key). + /// + /// Add is intended for animations layered on top of others, not for the first animations applied. + /// + Add + } + + /// + /// Indicates whether a timeline's alpha is mixing out over time toward 0 (the setup or current pose value) or + /// mixing in toward 1 (the timeline's value). + /// + public enum MixDirection { + In, + Out + } + + internal enum TimelineType { + Rotate = 0, Translate, Scale, Shear, // + Attachment, Color, Deform, // + Event, DrawOrder, // + IkConstraint, TransformConstraint, // + PathConstraintPosition, PathConstraintSpacing, PathConstraintMix, // + TwoColor + } + + /// An interface for timelines which change the property of a bone. + public interface IBoneTimeline { + /// The index of the bone in that will be changed. + int BoneIndex { get; } + } + + /// An interface for timelines which change the property of a slot. + public interface ISlotTimeline { + /// The index of the slot in that will be changed. + int SlotIndex { get; } + } + + /// The base class for timelines that use interpolation between key frame values. + abstract public class CurveTimeline : Timeline { + protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2; + protected const int BEZIER_SIZE = 10 * 2 - 1; + + internal float[] curves; // type, x, y, ... + /// The number of key frames for this timeline. + public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } } + + public CurveTimeline (int frameCount) { + if (frameCount <= 0) throw new ArgumentOutOfRangeException("frameCount must be > 0: "); + curves = new float[(frameCount - 1) * BEZIER_SIZE]; + } + + abstract public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, MixDirection direction); + + abstract public int PropertyId { get; } + + /// Sets the specified key frame to linear interpolation. + public void SetLinear (int frameIndex) { + curves[frameIndex * BEZIER_SIZE] = LINEAR; + } + + /// Sets the specified key frame to stepped interpolation. + public void SetStepped (int frameIndex) { + curves[frameIndex * BEZIER_SIZE] = STEPPED; + } + + /// Returns the interpolation type for the specified key frame. + /// Linear is 0, stepped is 1, Bezier is 2. + public float GetCurveType (int frameIndex) { + int index = frameIndex * BEZIER_SIZE; + if (index == curves.Length) return LINEAR; + float type = curves[index]; + if (type == LINEAR) return LINEAR; + if (type == STEPPED) return STEPPED; + return BEZIER; + } + + /// Sets the specified key frame to Bezier interpolation. cx1 and cx2 are from 0 to 1, + /// representing the percent of time between the two key frames. cy1 and cy2 are the percent of the + /// difference between the key frame's values. + public void SetCurve (int frameIndex, float cx1, float cy1, float cx2, float cy2) { + float tmpx = (-cx1 * 2 + cx2) * 0.03f, tmpy = (-cy1 * 2 + cy2) * 0.03f; + float dddfx = ((cx1 - cx2) * 3 + 1) * 0.006f, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006f; + float ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy; + float dfx = cx1 * 0.3f + tmpx + dddfx * 0.16666667f, dfy = cy1 * 0.3f + tmpy + dddfy * 0.16666667f; + + int i = frameIndex * BEZIER_SIZE; + float[] curves = this.curves; + curves[i++] = BEZIER; + + float x = dfx, y = dfy; + for (int n = i + BEZIER_SIZE - 1; i < n; i += 2) { + curves[i] = x; + curves[i + 1] = y; + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + x += dfx; + y += dfy; + } + } + + /// Returns the interpolated percentage for the specified key frame and linear percentage. + public float GetCurvePercent (int frameIndex, float percent) { + percent = MathUtils.Clamp (percent, 0, 1); + float[] curves = this.curves; + int i = frameIndex * BEZIER_SIZE; + float type = curves[i]; + if (type == LINEAR) return percent; + if (type == STEPPED) return 0; + i++; + float x = 0; + for (int start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) { + x = curves[i]; + if (x >= percent) { + if (i == start) return curves[i + 1] * percent / x; // First point is 0,0. + float prevX = curves[i - 2], prevY = curves[i - 1]; + return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); + } + } + float y = curves[i - 1]; + return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. + } + } + + /// Changes a bone's local . + public class RotateTimeline : CurveTimeline, IBoneTimeline { + public const int ENTRIES = 2; + internal const int PREV_TIME = -2, PREV_ROTATION = -1; + internal const int ROTATION = 1; + + internal int boneIndex; + internal float[] frames; // time, degrees, ... + + public RotateTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount << 1]; + } + + override public int PropertyId { + get { return ((int)TimelineType.Rotate << 24) + boneIndex; } + } + /// The index of the bone in that will be changed. + public int BoneIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.boneIndex = value; + } + get { + return boneIndex; + } + } + /// The time in seconds and rotation in degrees for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// Sets the time in seconds and the rotation in degrees for the specified key frame. + public void SetFrame (int frameIndex, float time, float degrees) { + frameIndex <<= 1; + frames[frameIndex] = time; + frames[frameIndex + ROTATION] = degrees; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Bone bone = skeleton.bones.Items[boneIndex]; + if (!bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + bone.rotation = bone.data.rotation; + return; + case MixBlend.First: + float r = bone.data.rotation - bone.rotation; + bone.rotation += (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + return; + } + return; + } + + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + float r = frames[frames.Length + PREV_ROTATION]; + switch (blend) { + case MixBlend.Setup: + bone.rotation = bone.data.rotation + r * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + r += bone.data.rotation - bone.rotation; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + goto case MixBlend.Add; // Fall through. + + case MixBlend.Add: + bone.rotation += r * alpha; + break; + } + return; + } + + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + float prevRotation = frames[frame + PREV_ROTATION]; + float frameTime = frames[frame]; + float percent = GetCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + // scope for 'r' to prevent compile error. + { + float r = frames[frame + ROTATION] - prevRotation; + r = prevRotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * percent; + switch (blend) { + case MixBlend.Setup: + bone.rotation = bone.data.rotation + (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + r += bone.data.rotation - bone.rotation; + goto case MixBlend.Add; // Fall through. + case MixBlend.Add: + bone.rotation += (r - (16384 - (int)(16384.499999999996 - r / 360)) * 360) * alpha; + break; + } + } + } + } + + /// Changes a bone's local and . + public class TranslateTimeline : CurveTimeline, IBoneTimeline { + public const int ENTRIES = 3; + protected const int PREV_TIME = -3, PREV_X = -2, PREV_Y = -1; + protected const int X = 1, Y = 2; + + internal int boneIndex; + internal float[] frames; // time, x, y, ... + + public TranslateTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.Translate << 24) + boneIndex; } + } + + /// The index of the bone in that will be changed. + public int BoneIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.boneIndex = value; + } + get { + return boneIndex; + } + } + /// The time in seconds, x, and y values for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + + /// Sets the time in seconds, x, and y values for the specified key frame. + public void SetFrame (int frameIndex, float time, float x, float y) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + X] = x; + frames[frameIndex + Y] = y; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Bone bone = skeleton.bones.Items[boneIndex]; + if (!bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + bone.x = bone.data.x; + bone.y = bone.data.y; + return; + case MixBlend.First: + bone.x += (bone.data.x - bone.x) * alpha; + bone.y += (bone.data.y - bone.y) * alpha; + return; + } + return; + } + + float x, y; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + x = frames[frames.Length + PREV_X]; + y = frames[frames.Length + PREV_Y]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + x = frames[frame + PREV_X]; + y = frames[frame + PREV_Y]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + x += (frames[frame + X] - x) * percent; + y += (frames[frame + Y] - y) * percent; + } + switch (blend) { + case MixBlend.Setup: + bone.x = bone.data.x + x * alpha; + bone.y = bone.data.y + y * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + bone.x += (bone.data.x + x - bone.x) * alpha; + bone.y += (bone.data.y + y - bone.y) * alpha; + break; + case MixBlend.Add: + bone.x += x * alpha; + bone.y += y * alpha; + break; + } + } + } + + /// Changes a bone's local and . + public class ScaleTimeline : TranslateTimeline, IBoneTimeline { + public ScaleTimeline (int frameCount) + : base(frameCount) { + } + + override public int PropertyId { + get { return ((int)TimelineType.Scale << 24) + boneIndex; } + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Bone bone = skeleton.bones.Items[boneIndex]; + if (!bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + bone.scaleX = bone.data.scaleX; + bone.scaleY = bone.data.scaleY; + return; + case MixBlend.First: + bone.scaleX += (bone.data.scaleX - bone.scaleX) * alpha; + bone.scaleY += (bone.data.scaleY - bone.scaleY) * alpha; + return; + } + return; + } + + float x, y; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + x = frames[frames.Length + PREV_X] * bone.data.scaleX; + y = frames[frames.Length + PREV_Y] * bone.data.scaleY; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + x = frames[frame + PREV_X]; + y = frames[frame + PREV_Y]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + x = (x + (frames[frame + X] - x) * percent) * bone.data.scaleX; + y = (y + (frames[frame + Y] - y) * percent) * bone.data.scaleY; + } + if (alpha == 1) { + if (blend == MixBlend.Add) { + bone.scaleX += x - bone.data.scaleX; + bone.scaleY += y - bone.data.scaleY; + } else { + bone.scaleX = x; + bone.scaleY = y; + } + } else { + // Mixing out uses sign of setup or current pose, else use sign of key. + float bx, by; + if (direction == MixDirection.Out) { + switch (blend) { + case MixBlend.Setup: + bx = bone.data.scaleX; + by = bone.data.scaleY; + bone.scaleX = bx + (Math.Abs(x) * Math.Sign(bx) - bx) * alpha; + bone.scaleY = by + (Math.Abs(y) * Math.Sign(by) - by) * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + bx = bone.scaleX; + by = bone.scaleY; + bone.scaleX = bx + (Math.Abs(x) * Math.Sign(bx) - bx) * alpha; + bone.scaleY = by + (Math.Abs(y) * Math.Sign(by) - by) * alpha; + break; + case MixBlend.Add: + bx = bone.scaleX; + by = bone.scaleY; + bone.scaleX = bx + (Math.Abs(x) * Math.Sign(bx) - bone.data.scaleX) * alpha; + bone.scaleY = by + (Math.Abs(y) * Math.Sign(by) - bone.data.scaleY) * alpha; + break; + } + } else { + switch (blend) { + case MixBlend.Setup: + bx = Math.Abs(bone.data.scaleX) * Math.Sign(x); + by = Math.Abs(bone.data.scaleY) * Math.Sign(y); + bone.scaleX = bx + (x - bx) * alpha; + bone.scaleY = by + (y - by) * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + bx = Math.Abs(bone.scaleX) * Math.Sign(x); + by = Math.Abs(bone.scaleY) * Math.Sign(y); + bone.scaleX = bx + (x - bx) * alpha; + bone.scaleY = by + (y - by) * alpha; + break; + case MixBlend.Add: + bx = Math.Sign(x); + by = Math.Sign(y); + bone.scaleX = Math.Abs(bone.scaleX) * bx + (x - Math.Abs(bone.data.scaleX) * bx) * alpha; + bone.scaleY = Math.Abs(bone.scaleY) * by + (y - Math.Abs(bone.data.scaleY) * by) * alpha; + break; + } + } + } + } + } + + /// Changes a bone's local and . + public class ShearTimeline : TranslateTimeline, IBoneTimeline { + public ShearTimeline (int frameCount) + : base(frameCount) { + } + + override public int PropertyId { + get { return ((int)TimelineType.Shear << 24) + boneIndex; } + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Bone bone = skeleton.bones.Items[boneIndex]; + if (!bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + bone.shearX = bone.data.shearX; + bone.shearY = bone.data.shearY; + return; + case MixBlend.First: + bone.shearX += (bone.data.shearX - bone.shearX) * alpha; + bone.shearY += (bone.data.shearY - bone.shearY) * alpha; + return; + } + return; + } + + float x, y; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + x = frames[frames.Length + PREV_X]; + y = frames[frames.Length + PREV_Y]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + x = frames[frame + PREV_X]; + y = frames[frame + PREV_Y]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + x = x + (frames[frame + X] - x) * percent; + y = y + (frames[frame + Y] - y) * percent; + } + switch (blend) { + case MixBlend.Setup: + bone.shearX = bone.data.shearX + x * alpha; + bone.shearY = bone.data.shearY + y * alpha; + break; + case MixBlend.First: + case MixBlend.Replace: + bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha; + bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha; + break; + case MixBlend.Add: + bone.shearX += x * alpha; + bone.shearY += y * alpha; + break; + } + } + } + + /// Changes a slot's . + public class ColorTimeline : CurveTimeline, ISlotTimeline { + public const int ENTRIES = 5; + protected const int PREV_TIME = -5, PREV_R = -4, PREV_G = -3, PREV_B = -2, PREV_A = -1; + protected const int R = 1, G = 2, B = 3, A = 4; + + internal int slotIndex; + internal float[] frames; // time, r, g, b, a, ... + + public ColorTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.Color << 24) + slotIndex; } + } + + /// The index of the slot in that will be changed. + public int SlotIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.slotIndex = value; + } + get { + return slotIndex; + } + } + /// The time in seconds, red, green, blue, and alpha values for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// Sets the time in seconds, red, green, blue, and alpha for the specified key frame. + public void SetFrame (int frameIndex, float time, float r, float g, float b, float a) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + R] = r; + frames[frameIndex + G] = g; + frames[frameIndex + B] = b; + frames[frameIndex + A] = a; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Slot slot = skeleton.slots.Items[slotIndex]; + if (!slot.bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + var slotData = slot.data; + switch (blend) { + case MixBlend.Setup: + slot.r = slotData.r; + slot.g = slotData.g; + slot.b = slotData.b; + slot.a = slotData.a; + return; + case MixBlend.First: + slot.r += (slotData.r - slot.r) * alpha; + slot.g += (slotData.g - slot.g) * alpha; + slot.b += (slotData.b - slot.b) * alpha; + slot.a += (slotData.a - slot.a) * alpha; + slot.ClampColor(); + return; + } + return; + } + + float r, g, b, a; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + int i = frames.Length; + r = frames[i + PREV_R]; + g = frames[i + PREV_G]; + b = frames[i + PREV_B]; + a = frames[i + PREV_A]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + r = frames[frame + PREV_R]; + g = frames[frame + PREV_G]; + b = frames[frame + PREV_B]; + a = frames[frame + PREV_A]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + r += (frames[frame + R] - r) * percent; + g += (frames[frame + G] - g) * percent; + b += (frames[frame + B] - b) * percent; + a += (frames[frame + A] - a) * percent; + } + if (alpha == 1) { + slot.r = r; + slot.g = g; + slot.b = b; + slot.a = a; + slot.ClampColor(); + } else { + float br, bg, bb, ba; + if (blend == MixBlend.Setup) { + br = slot.data.r; + bg = slot.data.g; + bb = slot.data.b; + ba = slot.data.a; + } else { + br = slot.r; + bg = slot.g; + bb = slot.b; + ba = slot.a; + } + slot.r = br + ((r - br) * alpha); + slot.g = bg + ((g - bg) * alpha); + slot.b = bb + ((b - bb) * alpha); + slot.a = ba + ((a - ba) * alpha); + slot.ClampColor(); + } + } + } + + /// Changes a slot's and for two color tinting. + public class TwoColorTimeline : CurveTimeline, ISlotTimeline { + public const int ENTRIES = 8; + protected const int PREV_TIME = -8, PREV_R = -7, PREV_G = -6, PREV_B = -5, PREV_A = -4; + protected const int PREV_R2 = -3, PREV_G2 = -2, PREV_B2 = -1; + protected const int R = 1, G = 2, B = 3, A = 4, R2 = 5, G2 = 6, B2 = 7; + + internal int slotIndex; + internal float[] frames; // time, r, g, b, a, r2, g2, b2, ... + + public TwoColorTimeline (int frameCount) : + base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.TwoColor << 24) + slotIndex; } + } + + /// The index of the slot in that will be changed. + public int SlotIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.slotIndex = value; + } + get { + return slotIndex; + } + } + /// The time in seconds, red, green, blue, and alpha values for each key frame. + public float[] Frames { get { return frames; } } + + /// Sets the time in seconds, light, and dark colors for the specified key frame.. + public void SetFrame (int frameIndex, float time, float r, float g, float b, float a, float r2, float g2, float b2) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + R] = r; + frames[frameIndex + G] = g; + frames[frameIndex + B] = b; + frames[frameIndex + A] = a; + frames[frameIndex + R2] = r2; + frames[frameIndex + G2] = g2; + frames[frameIndex + B2] = b2; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Slot slot = skeleton.slots.Items[slotIndex]; + if (!slot.bone.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + var slotData = slot.data; + switch (blend) { + case MixBlend.Setup: + // slot.color.set(slot.data.color); + // slot.darkColor.set(slot.data.darkColor); + slot.r = slotData.r; + slot.g = slotData.g; + slot.b = slotData.b; + slot.a = slotData.a; + slot.ClampColor(); + slot.r2 = slotData.r2; + slot.g2 = slotData.g2; + slot.b2 = slotData.b2; + slot.ClampSecondColor(); + return; + case MixBlend.First: + slot.r += (slot.r - slotData.r) * alpha; + slot.g += (slot.g - slotData.g) * alpha; + slot.b += (slot.b - slotData.b) * alpha; + slot.a += (slot.a - slotData.a) * alpha; + slot.ClampColor(); + slot.r2 += (slot.r2 - slotData.r2) * alpha; + slot.g2 += (slot.g2 - slotData.g2) * alpha; + slot.b2 += (slot.b2 - slotData.b2) * alpha; + slot.ClampSecondColor(); + return; + } + return; + } + + float r, g, b, a, r2, g2, b2; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + int i = frames.Length; + r = frames[i + PREV_R]; + g = frames[i + PREV_G]; + b = frames[i + PREV_B]; + a = frames[i + PREV_A]; + r2 = frames[i + PREV_R2]; + g2 = frames[i + PREV_G2]; + b2 = frames[i + PREV_B2]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + r = frames[frame + PREV_R]; + g = frames[frame + PREV_G]; + b = frames[frame + PREV_B]; + a = frames[frame + PREV_A]; + r2 = frames[frame + PREV_R2]; + g2 = frames[frame + PREV_G2]; + b2 = frames[frame + PREV_B2]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + r += (frames[frame + R] - r) * percent; + g += (frames[frame + G] - g) * percent; + b += (frames[frame + B] - b) * percent; + a += (frames[frame + A] - a) * percent; + r2 += (frames[frame + R2] - r2) * percent; + g2 += (frames[frame + G2] - g2) * percent; + b2 += (frames[frame + B2] - b2) * percent; + } + if (alpha == 1) { + slot.r = r; + slot.g = g; + slot.b = b; + slot.a = a; + slot.ClampColor(); + slot.r2 = r2; + slot.g2 = g2; + slot.b2 = b2; + slot.ClampSecondColor(); + } else { + float br, bg, bb, ba, br2, bg2, bb2; + if (blend == MixBlend.Setup) { + br = slot.data.r; + bg = slot.data.g; + bb = slot.data.b; + ba = slot.data.a; + br2 = slot.data.r2; + bg2 = slot.data.g2; + bb2 = slot.data.b2; + } else { + br = slot.r; + bg = slot.g; + bb = slot.b; + ba = slot.a; + br2 = slot.r2; + bg2 = slot.g2; + bb2 = slot.b2; + } + slot.r = br + ((r - br) * alpha); + slot.g = bg + ((g - bg) * alpha); + slot.b = bb + ((b - bb) * alpha); + slot.a = ba + ((a - ba) * alpha); + slot.ClampColor(); + slot.r2 = br2 + ((r2 - br2) * alpha); + slot.g2 = bg2 + ((g2 - bg2) * alpha); + slot.b2 = bb2 + ((b2 - bb2) * alpha); + slot.ClampSecondColor(); + } + } + + } + + /// Changes a slot's . + public class AttachmentTimeline : Timeline, ISlotTimeline { + internal int slotIndex; + internal float[] frames; // time, ... + internal string[] attachmentNames; + + public AttachmentTimeline (int frameCount) { + frames = new float[frameCount]; + attachmentNames = new String[frameCount]; + } + + public int PropertyId { + get { return ((int)TimelineType.Attachment << 24) + slotIndex; } + } + + /// The number of key frames for this timeline. + public int FrameCount { get { return frames.Length; } } + + /// The index of the slot in that will be changed. + public int SlotIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.slotIndex = value; + } + get { + return slotIndex; + } + } + + /// The time in seconds for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// The attachment name for each key frame. May contain null values to clear the attachment. + public string[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } } + + /// Sets the time in seconds and the attachment name for the specified key frame. + public void SetFrame (int frameIndex, float time, String attachmentName) { + frames[frameIndex] = time; + attachmentNames[frameIndex] = attachmentName; + } + + public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Slot slot = skeleton.slots.Items[slotIndex]; + if (!slot.bone.active) return; + if (direction == MixDirection.Out) { + if (blend == MixBlend.Setup) SetAttachment(skeleton, slot, slot.data.attachmentName); + return; + } + + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + if (blend == MixBlend.Setup || blend == MixBlend.First) SetAttachment(skeleton, slot, slot.data.attachmentName); + return; + } + + int frameIndex; + if (time >= frames[frames.Length - 1]) // Time is after last frame. + frameIndex = frames.Length - 1; + else + frameIndex = Animation.BinarySearch(frames, time) - 1; + + SetAttachment(skeleton, slot, attachmentNames[frameIndex]); + } + + private void SetAttachment (Skeleton skeleton, Slot slot, string attachmentName) { + slot.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slotIndex, attachmentName); + } + } + + /// Changes a slot's to deform a . + public class DeformTimeline : CurveTimeline, ISlotTimeline { + internal int slotIndex; + internal VertexAttachment attachment; + internal float[] frames; // time, ... + internal float[][] frameVertices; + + public DeformTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount]; + frameVertices = new float[frameCount][]; + } + + override public int PropertyId { + get { return ((int)TimelineType.Deform << 27) + attachment.id + slotIndex; } + } + + /// The index of the slot in that will be changed. + public int SlotIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.slotIndex = value; + } + get { + return slotIndex; + } + } + /// The attachment that will be deformed. + public VertexAttachment Attachment { get { return attachment; } set { attachment = value; } } + + /// The time in seconds for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// The vertices for each key frame. + public float[][] Vertices { get { return frameVertices; } set { frameVertices = value; } } + + + /// Sets the time in seconds and the vertices for the specified key frame. + /// Vertex positions for an unweighted VertexAttachment, or deform offsets if it has weights. + public void SetFrame (int frameIndex, float time, float[] vertices) { + frames[frameIndex] = time; + frameVertices[frameIndex] = vertices; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + Slot slot = skeleton.slots.Items[slotIndex]; + if (!slot.bone.active) return; + VertexAttachment vertexAttachment = slot.attachment as VertexAttachment; + if (vertexAttachment == null || vertexAttachment.DeformAttachment != attachment) return; + + var deformArray = slot.Deform; + if (deformArray.Count == 0) blend = MixBlend.Setup; + + float[][] frameVertices = this.frameVertices; + int vertexCount = frameVertices[0].Length; + float[] frames = this.frames; + float[] deform; + + if (time < frames[0]) { // Time is before first frame. + + switch (blend) { + case MixBlend.Setup: + deformArray.Clear(); + return; + case MixBlend.First: + if (alpha == 1) { + deformArray.Clear(); + return; + } + + // deformArray.SetSize(vertexCount) // Ensure size and preemptively set count. + if (deformArray.Capacity < vertexCount) deformArray.Capacity = vertexCount; + deformArray.Count = vertexCount; + deform = deformArray.Items; + + if (vertexAttachment.bones == null) { + // Unweighted vertex positions. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) + deform[i] += (setupVertices[i] - deform[i]) * alpha; + } else { + // Weighted deform offsets. + alpha = 1 - alpha; + for (int i = 0; i < vertexCount; i++) + deform[i] *= alpha; + } + return; + default: + return; + } + + } + + // deformArray.SetSize(vertexCount) // Ensure size and preemptively set count. + if (deformArray.Capacity < vertexCount) deformArray.Capacity = vertexCount; + deformArray.Count = vertexCount; + deform = deformArray.Items; + + if (time >= frames[frames.Length - 1]) { // Time is after last frame. + + float[] lastVertices = frameVertices[frames.Length - 1]; + if (alpha == 1) { + if (blend == MixBlend.Add) { + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, no alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i] - setupVertices[i]; + } else { + // Weighted deform offsets, no alpha. + for (int i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i]; + } + } else { + // Vertex positions or deform offsets, no alpha. + Array.Copy(lastVertices, 0, deform, 0, vertexCount); + } + } else { + switch (blend) { + case MixBlend.Setup: { + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, with alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) { + float setup = setupVertices[i]; + deform[i] = setup + (lastVertices[i] - setup) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (int i = 0; i < vertexCount; i++) + deform[i] = lastVertices[i] * alpha; + } + break; + } + case MixBlend.First: + case MixBlend.Replace: + // Vertex positions or deform offsets, with alpha. + for (int i = 0; i < vertexCount; i++) + deform[i] += (lastVertices[i] - deform[i]) * alpha; + break; + case MixBlend.Add: + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, no alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) + deform[i] += (lastVertices[i] - setupVertices[i]) * alpha; + } else { + // Weighted deform offsets, alpha. + for (int i = 0; i < vertexCount; i++) + deform[i] += lastVertices[i] * alpha; + } + break; + } + } + return; + } + + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time); + float[] prevVertices = frameVertices[frame - 1]; + float[] nextVertices = frameVertices[frame]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); + + if (alpha == 1) { + if (blend == MixBlend.Add) { + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, no alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += prev + (nextVertices[i] - prev) * percent - setupVertices[i]; + } + } else { + // Weighted deform offsets, no alpha. + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += prev + (nextVertices[i] - prev) * percent; + } + } + } else { + // Vertex positions or deform offsets, no alpha. + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] = prev + (nextVertices[i] - prev) * percent; + } + } + } else { + switch (blend) { + case MixBlend.Setup: { + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, with alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i], setup = setupVertices[i]; + deform[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] = (prev + (nextVertices[i] - prev) * percent) * alpha; + } + } + break; + } + case MixBlend.First: + case MixBlend.Replace: { + // Vertex positions or deform offsets, with alpha. + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent - deform[i]) * alpha; + } + break; + } + case MixBlend.Add: { + if (vertexAttachment.bones == null) { + // Unweighted vertex positions, with alpha. + float[] setupVertices = vertexAttachment.vertices; + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent - setupVertices[i]) * alpha; + } + } else { + // Weighted deform offsets, with alpha. + for (int i = 0; i < vertexCount; i++) { + float prev = prevVertices[i]; + deform[i] += (prev + (nextVertices[i] - prev) * percent) * alpha; + } + } + break; + } + } + } + } + } + + /// Fires an when specific animation times are reached. + public class EventTimeline : Timeline { + internal float[] frames; // time, ... + private Event[] events; + + public EventTimeline (int frameCount) { + frames = new float[frameCount]; + events = new Event[frameCount]; + } + + public int PropertyId { + get { return ((int)TimelineType.Event << 24); } + } + + /// The number of key frames for this timeline. + public int FrameCount { get { return frames.Length; } } + + /// The time in seconds for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// The event for each key frame. + public Event[] Events { get { return events; } set { events = value; } } + + /// Sets the time in seconds and the event for the specified key frame. + public void SetFrame (int frameIndex, Event e) { + frames[frameIndex] = e.Time; + events[frameIndex] = e; + } + + /// Fires events for frames > lastTime and <= time. + public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + if (firedEvents == null) return; + float[] frames = this.frames; + int frameCount = frames.Length; + + if (lastTime > time) { // Fire events after last time for looped animations. + Apply(skeleton, lastTime, int.MaxValue, firedEvents, alpha, blend, direction); + lastTime = -1f; + } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. + return; + if (time < frames[0]) return; // Time is before first frame. + + int frame; + if (lastTime < frames[0]) + frame = 0; + else { + frame = Animation.BinarySearch(frames, lastTime); + float frameTime = frames[frame]; + while (frame > 0) { // Fire multiple events with the same frame. + if (frames[frame - 1] != frameTime) break; + frame--; + } + } + for (; frame < frameCount && time >= frames[frame]; frame++) + firedEvents.Add(events[frame]); + } + } + + /// Changes a skeleton's . + public class DrawOrderTimeline : Timeline { + internal float[] frames; // time, ... + private int[][] drawOrders; + + public DrawOrderTimeline (int frameCount) { + frames = new float[frameCount]; + drawOrders = new int[frameCount][]; + } + + public int PropertyId { + get { return ((int)TimelineType.DrawOrder << 24); } + } + + /// The number of key frames for this timeline. + public int FrameCount { get { return frames.Length; } } + + /// The time in seconds for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } // time, ... + + /// The draw order for each key frame. + /// . + public int[][] DrawOrders { get { return drawOrders; } set { drawOrders = value; } } + + /// Sets the time in seconds and the draw order for the specified key frame. + /// For each slot in the index of the new draw order. May be null to use setup pose + /// draw order.. + public void SetFrame (int frameIndex, float time, int[] drawOrder) { + frames[frameIndex] = time; + drawOrders[frameIndex] = drawOrder; + } + + public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + ExposedList drawOrder = skeleton.drawOrder; + ExposedList slots = skeleton.slots; + if (direction == MixDirection.Out) { + if (blend == MixBlend.Setup) Array.Copy(slots.Items, 0, drawOrder.Items, 0, slots.Count); + return; + } + + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + if (blend == MixBlend.Setup || blend == MixBlend.First) Array.Copy(slots.Items, 0, drawOrder.Items, 0, slots.Count); + return; + } + + int frame; + if (time >= frames[frames.Length - 1]) // Time is after last frame. + frame = frames.Length - 1; + else + frame = Animation.BinarySearch(frames, time) - 1; + + int[] drawOrderToSetupIndex = drawOrders[frame]; + if (drawOrderToSetupIndex == null) { + Array.Copy(slots.Items, 0, drawOrder.Items, 0, slots.Count); + } else { + var drawOrderItems = drawOrder.Items; + var slotsItems = slots.Items; + for (int i = 0, n = drawOrderToSetupIndex.Length; i < n; i++) + drawOrderItems[i] = slotsItems[drawOrderToSetupIndex[i]]; + } + } + } + + /// Changes an IK constraint's , , + /// , , and . + public class IkConstraintTimeline : CurveTimeline { + public const int ENTRIES = 6; + private const int PREV_TIME = -6, PREV_MIX = -5, PREV_SOFTNESS = -4, PREV_BEND_DIRECTION = -3, PREV_COMPRESS = -2, + PREV_STRETCH = -1; + private const int MIX = 1, SOFTNESS = 2, BEND_DIRECTION = 3, COMPRESS = 4, STRETCH = 5; + + internal int ikConstraintIndex; + internal float[] frames; // time, mix, softness, bendDirection, compress, stretch, ... + + public IkConstraintTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.IkConstraint << 24) + ikConstraintIndex; } + } + + /// The index of the IK constraint slot in that will be changed. + public int IkConstraintIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.ikConstraintIndex = value; + } + get { + return ikConstraintIndex; + } + } + + /// The time in seconds, mix, softness, bend direction, compress, and stretch for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } + + /// Sets the time in seconds, mix, softness, bend direction, compress, and stretch for the specified key frame. + public void SetFrame (int frameIndex, float time, float mix, float softness, int bendDirection, bool compress, + bool stretch) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + MIX] = mix; + frames[frameIndex + SOFTNESS] = softness; + frames[frameIndex + BEND_DIRECTION] = bendDirection; + frames[frameIndex + COMPRESS] = compress ? 1 : 0; + frames[frameIndex + STRETCH] = stretch ? 1 : 0; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + IkConstraint constraint = skeleton.ikConstraints.Items[ikConstraintIndex]; + if (!constraint.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + constraint.mix = constraint.data.mix; + constraint.softness = constraint.data.softness; + constraint.bendDirection = constraint.data.bendDirection; + constraint.compress = constraint.data.compress; + constraint.stretch = constraint.data.stretch; + return; + case MixBlend.First: + constraint.mix += (constraint.data.mix - constraint.mix) * alpha; + constraint.softness += (constraint.data.softness - constraint.softness) * alpha; + constraint.bendDirection = constraint.data.bendDirection; + constraint.compress = constraint.data.compress; + constraint.stretch = constraint.data.stretch; + return; + } + return; + } + + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + if (blend == MixBlend.Setup) { + constraint.mix = constraint.data.mix + (frames[frames.Length + PREV_MIX] - constraint.data.mix) * alpha; + constraint.softness = constraint.data.softness + + (frames[frames.Length + PREV_SOFTNESS] - constraint.data.softness) * alpha; + if (direction == MixDirection.Out) { + constraint.bendDirection = constraint.data.bendDirection; + constraint.compress = constraint.data.compress; + constraint.stretch = constraint.data.stretch; + } else { + constraint.bendDirection = (int)frames[frames.Length + PREV_BEND_DIRECTION]; + constraint.compress = frames[frames.Length + PREV_COMPRESS] != 0; + constraint.stretch = frames[frames.Length + PREV_STRETCH] != 0; + } + } else { + constraint.mix += (frames[frames.Length + PREV_MIX] - constraint.mix) * alpha; + constraint.softness += (frames[frames.Length + PREV_SOFTNESS] - constraint.softness) * alpha; + if (direction == MixDirection.In) { + constraint.bendDirection = (int)frames[frames.Length + PREV_BEND_DIRECTION]; + constraint.compress = frames[frames.Length + PREV_COMPRESS] != 0; + constraint.stretch = frames[frames.Length + PREV_STRETCH] != 0; + } + } + return; + } + + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + float mix = frames[frame + PREV_MIX]; + float softness = frames[frame + PREV_SOFTNESS]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + if (blend == MixBlend.Setup) { + constraint.mix = constraint.data.mix + (mix + (frames[frame + MIX] - mix) * percent - constraint.data.mix) * alpha; + constraint.softness = constraint.data.softness + + (softness + (frames[frame + SOFTNESS] - softness) * percent - constraint.data.softness) * alpha; + if (direction == MixDirection.Out) { + constraint.bendDirection = constraint.data.bendDirection; + constraint.compress = constraint.data.compress; + constraint.stretch = constraint.data.stretch; + } else { + constraint.bendDirection = (int)frames[frame + PREV_BEND_DIRECTION]; + constraint.compress = frames[frame + PREV_COMPRESS] != 0; + constraint.stretch = frames[frame + PREV_STRETCH] != 0; + } + } else { + constraint.mix += (mix + (frames[frame + MIX] - mix) * percent - constraint.mix) * alpha; + constraint.softness += (softness + (frames[frame + SOFTNESS] - softness) * percent - constraint.softness) * alpha; + if (direction == MixDirection.In) { + constraint.bendDirection = (int)frames[frame + PREV_BEND_DIRECTION]; + constraint.compress = frames[frame + PREV_COMPRESS] != 0; + constraint.stretch = frames[frame + PREV_STRETCH] != 0; + } + } + } + } + + /// Changes a transform constraint's mixes. + public class TransformConstraintTimeline : CurveTimeline { + public const int ENTRIES = 5; + private const int PREV_TIME = -5, PREV_ROTATE = -4, PREV_TRANSLATE = -3, PREV_SCALE = -2, PREV_SHEAR = -1; + private const int ROTATE = 1, TRANSLATE = 2, SCALE = 3, SHEAR = 4; + + internal int transformConstraintIndex; + internal float[] frames; // time, rotate mix, translate mix, scale mix, shear mix, ... + + public TransformConstraintTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.TransformConstraint << 24) + transformConstraintIndex; } + } + + /// The index of the transform constraint slot in that will be changed. + public int TransformConstraintIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.transformConstraintIndex = value; + } + get { + return transformConstraintIndex; + } + } + + /// The time in seconds, rotate mix, translate mix, scale mix, and shear mix for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } // time, rotate mix, translate mix, scale mix, shear mix, ... + + /// The time in seconds, rotate mix, translate mix, scale mix, and shear mix for the specified key frame. + public void SetFrame (int frameIndex, float time, float rotateMix, float translateMix, float scaleMix, float shearMix) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + ROTATE] = rotateMix; + frames[frameIndex + TRANSLATE] = translateMix; + frames[frameIndex + SCALE] = scaleMix; + frames[frameIndex + SHEAR] = shearMix; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + TransformConstraint constraint = skeleton.transformConstraints.Items[transformConstraintIndex]; + if (!constraint.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + TransformConstraintData data = constraint.data; + switch (blend) { + case MixBlend.Setup: + constraint.rotateMix = data.rotateMix; + constraint.translateMix = data.translateMix; + constraint.scaleMix = data.scaleMix; + constraint.shearMix = data.shearMix; + return; + case MixBlend.First: + constraint.rotateMix += (data.rotateMix - constraint.rotateMix) * alpha; + constraint.translateMix += (data.translateMix - constraint.translateMix) * alpha; + constraint.scaleMix += (data.scaleMix - constraint.scaleMix) * alpha; + constraint.shearMix += (data.shearMix - constraint.shearMix) * alpha; + return; + } + return; + } + + float rotate, translate, scale, shear; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + int i = frames.Length; + rotate = frames[i + PREV_ROTATE]; + translate = frames[i + PREV_TRANSLATE]; + scale = frames[i + PREV_SCALE]; + shear = frames[i + PREV_SHEAR]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + rotate = frames[frame + PREV_ROTATE]; + translate = frames[frame + PREV_TRANSLATE]; + scale = frames[frame + PREV_SCALE]; + shear = frames[frame + PREV_SHEAR]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + rotate += (frames[frame + ROTATE] - rotate) * percent; + translate += (frames[frame + TRANSLATE] - translate) * percent; + scale += (frames[frame + SCALE] - scale) * percent; + shear += (frames[frame + SHEAR] - shear) * percent; + } + if (blend == MixBlend.Setup) { + TransformConstraintData data = constraint.data; + constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha; + constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha; + constraint.scaleMix = data.scaleMix + (scale - data.scaleMix) * alpha; + constraint.shearMix = data.shearMix + (shear - data.shearMix) * alpha; + } else { + constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; + constraint.translateMix += (translate - constraint.translateMix) * alpha; + constraint.scaleMix += (scale - constraint.scaleMix) * alpha; + constraint.shearMix += (shear - constraint.shearMix) * alpha; + } + } + } + + /// Changes a path constraint's . + public class PathConstraintPositionTimeline : CurveTimeline { + public const int ENTRIES = 2; + protected const int PREV_TIME = -2, PREV_VALUE = -1; + protected const int VALUE = 1; + + internal int pathConstraintIndex; + internal float[] frames; // time, position, ... + + public PathConstraintPositionTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.PathConstraintPosition << 24) + pathConstraintIndex; } + } + + /// The index of the path constraint slot in that will be changed. + public int PathConstraintIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.pathConstraintIndex = value; + } + get { + return pathConstraintIndex; + } + } + + /// The time in seconds and path constraint position for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } // time, position, ... + + /// Sets the time in seconds and path constraint position for the specified key frame. + public void SetFrame (int frameIndex, float time, float position) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + VALUE] = position; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex]; + if (!constraint.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + constraint.position = constraint.data.position; + return; + case MixBlend.First: + constraint.position += (constraint.data.position - constraint.position) * alpha; + return; + } + return; + } + + float position; + if (time >= frames[frames.Length - ENTRIES]) // Time is after last frame. + position = frames[frames.Length + PREV_VALUE]; + else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + position = frames[frame + PREV_VALUE]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + position += (frames[frame + VALUE] - position) * percent; + } + if (blend == MixBlend.Setup) + constraint.position = constraint.data.position + (position - constraint.data.position) * alpha; + else + constraint.position += (position - constraint.position) * alpha; + } + } + + /// Changes a path constraint's . + public class PathConstraintSpacingTimeline : PathConstraintPositionTimeline { + public PathConstraintSpacingTimeline (int frameCount) + : base(frameCount) { + } + + override public int PropertyId { + get { return ((int)TimelineType.PathConstraintSpacing << 24) + pathConstraintIndex; } + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList events, float alpha, MixBlend blend, + MixDirection direction) { + PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex]; + if (!constraint.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + constraint.spacing = constraint.data.spacing; + return; + case MixBlend.First: + constraint.spacing += (constraint.data.spacing - constraint.spacing) * alpha; + return; + } + return; + } + + float spacing; + if (time >= frames[frames.Length - ENTRIES]) // Time is after last frame. + spacing = frames[frames.Length + PREV_VALUE]; + else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + spacing = frames[frame + PREV_VALUE]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + spacing += (frames[frame + VALUE] - spacing) * percent; + } + + if (blend == MixBlend.Setup) + constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha; + else + constraint.spacing += (spacing - constraint.spacing) * alpha; + } + } + + /// Changes a path constraint's mixes. + public class PathConstraintMixTimeline : CurveTimeline { + public const int ENTRIES = 3; + private const int PREV_TIME = -3, PREV_ROTATE = -2, PREV_TRANSLATE = -1; + private const int ROTATE = 1, TRANSLATE = 2; + + internal int pathConstraintIndex; + internal float[] frames; // time, rotate mix, translate mix, ... + + public PathConstraintMixTimeline (int frameCount) + : base(frameCount) { + frames = new float[frameCount * ENTRIES]; + } + + override public int PropertyId { + get { return ((int)TimelineType.PathConstraintMix << 24) + pathConstraintIndex; } + } + + /// The index of the path constraint slot in that will be changed. + public int PathConstraintIndex { + set { + if (value < 0) throw new ArgumentOutOfRangeException("index must be >= 0."); + this.pathConstraintIndex = value; + } + get { + return pathConstraintIndex; + } + } + + /// The time in seconds, rotate mix, and translate mix for each key frame. + public float[] Frames { get { return frames; } set { frames = value; } } // time, rotate mix, translate mix, ... + + /// The time in seconds, rotate mix, and translate mix for the specified key frame. + public void SetFrame (int frameIndex, float time, float rotateMix, float translateMix) { + frameIndex *= ENTRIES; + frames[frameIndex] = time; + frames[frameIndex + ROTATE] = rotateMix; + frames[frameIndex + TRANSLATE] = translateMix; + } + + override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList firedEvents, float alpha, MixBlend blend, + MixDirection direction) { + PathConstraint constraint = skeleton.pathConstraints.Items[pathConstraintIndex]; + if (!constraint.active) return; + float[] frames = this.frames; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + constraint.rotateMix = constraint.data.rotateMix; + constraint.translateMix = constraint.data.translateMix; + return; + case MixBlend.First: + constraint.rotateMix += (constraint.data.rotateMix - constraint.rotateMix) * alpha; + constraint.translateMix += (constraint.data.translateMix - constraint.translateMix) * alpha; + return; + } + return; + } + + float rotate, translate; + if (time >= frames[frames.Length - ENTRIES]) { // Time is after last frame. + rotate = frames[frames.Length + PREV_ROTATE]; + translate = frames[frames.Length + PREV_TRANSLATE]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, ENTRIES); + rotate = frames[frame + PREV_ROTATE]; + translate = frames[frame + PREV_TRANSLATE]; + float frameTime = frames[frame]; + float percent = GetCurvePercent(frame / ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + rotate += (frames[frame + ROTATE] - rotate) * percent; + translate += (frames[frame + TRANSLATE] - translate) * percent; + } + + if (blend == MixBlend.Setup) { + constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha; + constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha; + } else { + constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; + constraint.translateMix += (translate - constraint.translateMix) * alpha; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs.meta new file mode 100644 index 0000000..cde730f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Animation.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fb7099b9c6ce91740b7041dabb0752c2 +timeCreated: 1456265156 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs new file mode 100644 index 0000000..2ded456 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs @@ -0,0 +1,1408 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + + /// + /// + /// Applies animations over time, queues animations for later playback, mixes (crossfading) between animations, and applies + /// multiple animations on top of each other (layering). + /// + /// See Applying Animations in the Spine Runtimes Guide. + /// + public class AnimationState { + static readonly Animation EmptyAnimation = new Animation("", new ExposedList(), 0); + + /// 1) A previously applied timeline has set this property. + /// Result: Mix from the current pose to the timeline pose. + internal const int Subsequent = 0; + /// 1) This is the first timeline to set this property. + /// 2) The next track entry applied after this one does not have a timeline to set this property. + /// Result: Mix from the setup pose to the timeline pose. + internal const int First = 1; + /// 1) A previously applied timeline has set this property.
+ /// 2) The next track entry to be applied does have a timeline to set this property.
+ /// 3) The next track entry after that one does not have a timeline to set this property.
+ /// Result: Mix from the current pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading + /// animations that key the same property. A subsequent timeline will set this property using a mix. + internal const int HoldSubsequent = 2; + /// 1) This is the first timeline to set this property. + /// 2) The next track entry to be applied does have a timeline to set this property. + /// 3) The next track entry after that one does not have a timeline to set this property. + /// Result: Mix from the setup pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading animations + /// that key the same property. A subsequent timeline will set this property using a mix. + internal const int HoldFirst = 3; + /// 1) This is the first timeline to set this property. + /// 2) The next track entry to be applied does have a timeline to set this property. + /// 3) The next track entry after that one does have a timeline to set this property. + /// 4) timelineHoldMix stores the first subsequent track entry that does not have a timeline to set this property. + /// Result: The same as HOLD except the mix percentage from the timelineHoldMix track entry is used. This handles when more than + /// 2 track entries in a row have a timeline that sets the same property. + /// Eg, A -> B -> C -> D where A, B, and C have a timeline setting same property, but D does not. When A is applied, to avoid + /// "dipping" A is not mixed out, however D (the first entry that doesn't set the property) mixing in is used to mix out A + /// (which affects B and C). Without using D to mix out, A would be applied fully until mixing completes, then snap to the mixed + /// out position. + internal const int HoldMix = 4; + + internal const int Setup = 1, Current = 2; + + protected AnimationStateData data; + private readonly ExposedList tracks = new ExposedList(); + private readonly ExposedList events = new ExposedList(); + // difference to libgdx reference: delegates are used for event callbacks instead of 'final SnapshotArray listeners'. + internal void OnStart (TrackEntry entry) { if (Start != null) Start(entry); } + internal void OnInterrupt (TrackEntry entry) { if (Interrupt != null) Interrupt(entry); } + internal void OnEnd (TrackEntry entry) { if (End != null) End(entry); } + internal void OnDispose (TrackEntry entry) { if (Dispose != null) Dispose(entry); } + internal void OnComplete (TrackEntry entry) { if (Complete != null) Complete(entry); } + internal void OnEvent (TrackEntry entry, Event e) { if (Event != null) Event(entry, e); } + + public delegate void TrackEntryDelegate (TrackEntry trackEntry); + public event TrackEntryDelegate Start, Interrupt, End, Dispose, Complete; + + public delegate void TrackEntryEventDelegate (TrackEntry trackEntry, Event e); + public event TrackEntryEventDelegate Event; + + public void AssignEventSubscribersFrom (AnimationState src) { + Event = src.Event; + Start = src.Start; + Interrupt = src.Interrupt; + End = src.End; + Dispose = src.Dispose; + Complete = src.Complete; + } + + public void AddEventSubscribersFrom (AnimationState src) { + Event += src.Event; + Start += src.Start; + Interrupt += src.Interrupt; + End += src.End; + Dispose += src.Dispose; + Complete += src.Complete; + } + + // end of difference + private readonly EventQueue queue; // Initialized by constructor. + private readonly HashSet propertyIDs = new HashSet(); + private bool animationsChanged; + private float timeScale = 1; + private int unkeyedState; + + private readonly Pool trackEntryPool = new Pool(); + + public AnimationState (AnimationStateData data) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + this.data = data; + this.queue = new EventQueue( + this, + delegate { this.animationsChanged = true; }, + trackEntryPool + ); + } + + /// + /// Increments the track entry , setting queued animations as current if needed. + /// delta time + public void Update (float delta) { + delta *= timeScale; + var tracksItems = tracks.Items; + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry current = tracksItems[i]; + if (current == null) continue; + + current.animationLast = current.nextAnimationLast; + current.trackLast = current.nextTrackLast; + + float currentDelta = delta * current.timeScale; + + if (current.delay > 0) { + current.delay -= currentDelta; + if (current.delay > 0) continue; + currentDelta = -current.delay; + current.delay = 0; + } + + TrackEntry next = current.next; + if (next != null) { + // When the next entry's delay is passed, change to the next entry, preserving leftover time. + float nextTime = current.trackLast - next.delay; + if (nextTime >= 0) { + next.delay = 0; + next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale; + current.trackTime += currentDelta; + SetCurrent(i, next, true); + while (next.mixingFrom != null) { + next.mixTime += delta; + next = next.mixingFrom; + } + continue; + } + } else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) { + // Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom. + tracksItems[i] = null; + queue.End(current); + DisposeNext(current); + continue; + } + if (current.mixingFrom != null && UpdateMixingFrom(current, delta)) { + // End mixing from entries once all have completed. + TrackEntry from = current.mixingFrom; + current.mixingFrom = null; + if (from != null) from.mixingTo = null; + while (from != null) { + queue.End(from); + from = from.mixingFrom; + } + } + + current.trackTime += currentDelta; + } + + queue.Drain(); + } + + /// Returns true when all mixing from entries are complete. + private bool UpdateMixingFrom (TrackEntry to, float delta) { + TrackEntry from = to.mixingFrom; + if (from == null) return true; + + bool finished = UpdateMixingFrom(from, delta); + + from.animationLast = from.nextAnimationLast; + from.trackLast = from.nextTrackLast; + + // Require mixTime > 0 to ensure the mixing from entry was applied at least once. + if (to.mixTime > 0 && to.mixTime >= to.mixDuration) { + // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame). + if (from.totalAlpha == 0 || to.mixDuration == 0) { + to.mixingFrom = from.mixingFrom; + if (from.mixingFrom != null) from.mixingFrom.mixingTo = to; + to.interruptAlpha = from.interruptAlpha; + queue.End(from); + } + return finished; + } + + from.trackTime += delta * from.timeScale; + to.mixTime += delta; + return false; + } + + /// + /// Poses the skeleton using the track entry animations. The animation state is not changed, so can be applied to multiple + /// skeletons to pose them identically. + /// True if any animations were applied. + public bool Apply (Skeleton skeleton) { + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + if (animationsChanged) AnimationsChanged(); + + var events = this.events; + bool applied = false; + var tracksItems = tracks.Items; + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry current = tracksItems[i]; + if (current == null || current.delay > 0) continue; + applied = true; + + // Track 0 animations aren't for layering, so do not show the previously applied animations before the first key. + MixBlend blend = i == 0 ? MixBlend.First : current.mixBlend; + + // Apply mixing from entries first. + float mix = current.alpha; + if (current.mixingFrom != null) + mix *= ApplyMixingFrom(current, skeleton, blend); + else if (current.trackTime >= current.trackEnd && current.next == null) // + mix = 0; // Set to setup pose the last time the entry will be applied. + + // Apply current entry. + float animationLast = current.animationLast, animationTime = current.AnimationTime; + int timelineCount = current.animation.timelines.Count; + var timelines = current.animation.timelines; + var timelinesItems = timelines.Items; + if ((i == 0 && mix == 1) || blend == MixBlend.Add) { + for (int ii = 0; ii < timelineCount; ii++) { + var timeline = timelinesItems[ii]; + if (timeline is AttachmentTimeline) + ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true); + else + timeline.Apply(skeleton, animationLast, animationTime, events, mix, blend, MixDirection.In); + } + } else { + var timelineMode = current.timelineMode.Items; + + bool firstFrame = current.timelinesRotation.Count != timelineCount << 1; + if (firstFrame) current.timelinesRotation.Resize(timelines.Count << 1); + var timelinesRotation = current.timelinesRotation.Items; + + for (int ii = 0; ii < timelineCount; ii++) { + Timeline timeline = timelinesItems[ii]; + MixBlend timelineBlend = timelineMode[ii] == AnimationState.Subsequent ? blend : MixBlend.Setup; + var rotateTimeline = timeline as RotateTimeline; + if (rotateTimeline != null) + ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, + ii << 1, firstFrame); + else if (timeline is AttachmentTimeline) + ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true); + else + timeline.Apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, MixDirection.In); + } + } + QueueEvents(current, animationTime); + events.Clear(false); + current.nextAnimationLast = animationTime; + current.nextTrackLast = current.trackTime; + } + + // Set slots attachments to the setup pose, if needed. This occurs if an animation that is mixing out sets attachments so + // subsequent timelines see any deform, but the subsequent timelines don't set an attachment (eg they are also mixing out or + // the time is before the first key). + int setupState = unkeyedState + Setup; + var slots = skeleton.slots.Items; + for (int i = 0, n = skeleton.slots.Count; i < n; i++) { + Slot slot = (Slot)slots[i]; + if (slot.attachmentState == setupState) { + string attachmentName = slot.data.attachmentName; + slot.Attachment = (attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName)); + } + } + unkeyedState += 2; // Increasing after each use avoids the need to reset attachmentState for every slot. + + queue.Drain(); + return applied; + } + + /// Version of only applying EventTimelines for lightweight off-screen updates. + // Note: This method is not part of the libgdx reference implementation. + public bool ApplyEventTimelinesOnly (Skeleton skeleton) { + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + + var events = this.events; + bool applied = false; + var tracksItems = tracks.Items; + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry current = tracksItems[i]; + if (current == null || current.delay > 0) continue; + applied = true; + + // Apply mixing from entries first. + if (current.mixingFrom != null) + ApplyMixingFromEventTimelinesOnly(current, skeleton); + + // Apply current entry. + float animationLast = current.animationLast, animationTime = current.AnimationTime; + int timelineCount = current.animation.timelines.Count; + var timelines = current.animation.timelines; + var timelinesItems = timelines.Items; + for (int ii = 0; ii < timelineCount; ii++) { + Timeline timeline = timelinesItems[ii]; + if (timeline is EventTimeline) + timeline.Apply(skeleton, animationLast, animationTime, events, 1.0f, MixBlend.Setup, MixDirection.In); + } + QueueEvents(current, animationTime); + events.Clear(false); + current.nextAnimationLast = animationTime; + current.nextTrackLast = current.trackTime; + } + + queue.Drain(); + return applied; + } + + private float ApplyMixingFrom (TrackEntry to, Skeleton skeleton, MixBlend blend) { + TrackEntry from = to.mixingFrom; + if (from.mixingFrom != null) ApplyMixingFrom(from, skeleton, blend); + + float mix; + if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes. + mix = 1; + if (blend == MixBlend.First) blend = MixBlend.Setup; // Tracks > 0 are transparent and can't reset to setup pose. + } else { + mix = to.mixTime / to.mixDuration; + if (mix > 1) mix = 1; + if (blend != MixBlend.First) blend = from.mixBlend; // Track 0 ignores track mix blend. + } + + var eventBuffer = mix < from.eventThreshold ? this.events : null; + bool attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold; + float animationLast = from.animationLast, animationTime = from.AnimationTime; + var timelines = from.animation.timelines; + int timelineCount = timelines.Count; + var timelinesItems = timelines.Items; + float alphaHold = from.alpha * to.interruptAlpha, alphaMix = alphaHold * (1 - mix); + + if (blend == MixBlend.Add) { + for (int i = 0; i < timelineCount; i++) + timelinesItems[i].Apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection.Out); + } else { + var timelineMode = from.timelineMode.Items; + var timelineHoldMix = from.timelineHoldMix.Items; + + bool firstFrame = from.timelinesRotation.Count != timelineCount << 1; + if (firstFrame) from.timelinesRotation.Resize(timelines.Count << 1); // from.timelinesRotation.setSize + var timelinesRotation = from.timelinesRotation.Items; + + from.totalAlpha = 0; + for (int i = 0; i < timelineCount; i++) { + Timeline timeline = timelinesItems[i]; + MixDirection direction = MixDirection.Out; + MixBlend timelineBlend; + float alpha; + switch (timelineMode[i]) { + case AnimationState.Subsequent: + if (!drawOrder && timeline is DrawOrderTimeline) continue; + timelineBlend = blend; + alpha = alphaMix; + break; + case AnimationState.First: + timelineBlend = MixBlend.Setup; + alpha = alphaMix; + break; + case AnimationState.HoldSubsequent: + timelineBlend = blend; + alpha = alphaHold; + break; + case AnimationState.HoldFirst: + timelineBlend = MixBlend.Setup; + alpha = alphaHold; + break; + default: // HoldMix + timelineBlend = MixBlend.Setup; + TrackEntry holdMix = timelineHoldMix[i]; + alpha = alphaHold * Math.Max(0, 1 - holdMix.mixTime / holdMix.mixDuration); + break; + } + from.totalAlpha += alpha; + var rotateTimeline = timeline as RotateTimeline; + if (rotateTimeline != null) { + ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, + i << 1, firstFrame); + } else if (timeline is AttachmentTimeline) { + ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, timelineBlend, attachments); + } else { + if (drawOrder && timeline is DrawOrderTimeline && timelineBlend == MixBlend.Setup) + direction = MixDirection.In; + timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction); + } + } + } + + if (to.mixDuration > 0) QueueEvents(from, animationTime); + this.events.Clear(false); + from.nextAnimationLast = animationTime; + from.nextTrackLast = from.trackTime; + + return mix; + } + + /// Version of only applying EventTimelines for lightweight off-screen updates. + // Note: This method is not part of the libgdx reference implementation. + private float ApplyMixingFromEventTimelinesOnly (TrackEntry to, Skeleton skeleton) { + TrackEntry from = to.mixingFrom; + if (from.mixingFrom != null) ApplyMixingFromEventTimelinesOnly(from, skeleton); + + float mix; + if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes. + mix = 1; + } + else { + mix = to.mixTime / to.mixDuration; + if (mix > 1) mix = 1; + } + + var eventBuffer = mix < from.eventThreshold ? this.events : null; + if (eventBuffer == null) + return mix; + + float animationLast = from.animationLast, animationTime = from.AnimationTime; + var timelines = from.animation.timelines; + int timelineCount = timelines.Count; + var timelinesItems = timelines.Items; + for (int i = 0; i < timelineCount; i++) { + var timeline = timelinesItems[i]; + if (timeline is EventTimeline) + timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, 0, MixBlend.Setup, MixDirection.Out); + } + + if (to.mixDuration > 0) QueueEvents(from, animationTime); + this.events.Clear(false); + from.nextAnimationLast = animationTime; + from.nextTrackLast = from.trackTime; + + return mix; + } + + /// Applies the attachment timeline and sets . + /// False when: 1) the attachment timeline is mixing out, 2) mix < attachmentThreshold, and 3) the timeline + /// is not the last timeline to set the slot's attachment. In that case the timeline is applied only so subsequent + /// timelines see any deform. + private void ApplyAttachmentTimeline (AttachmentTimeline timeline, Skeleton skeleton, float time, MixBlend blend, + bool attachments) { + + Slot slot = skeleton.slots.Items[timeline.slotIndex]; + if (!slot.bone.active) return; + + float[] frames = timeline.frames; + if (time < frames[0]) { // Time is before first frame. + if (blend == MixBlend.Setup || blend == MixBlend.First) + SetAttachment(skeleton, slot, slot.data.attachmentName, attachments); + } + else { + int frameIndex; + if (time >= frames[frames.Length - 1]) // Time is after last frame. + frameIndex = frames.Length - 1; + else + frameIndex = Animation.BinarySearch(frames, time) - 1; + SetAttachment(skeleton, slot, timeline.attachmentNames[frameIndex], attachments); + } + + // If an attachment wasn't set (ie before the first frame or attachments is false), set the setup attachment later. + if (slot.attachmentState <= unkeyedState) slot.attachmentState = unkeyedState + Setup; + } + + private void SetAttachment (Skeleton skeleton, Slot slot, String attachmentName, bool attachments) { + slot.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName); + if (attachments) slot.attachmentState = unkeyedState + Current; + } + + /// + /// Applies the rotate timeline, mixing with the current pose while keeping the same rotation direction chosen as the shortest + /// the first time the mixing was applied. + static private void ApplyRotateTimeline (RotateTimeline timeline, Skeleton skeleton, float time, float alpha, MixBlend blend, + float[] timelinesRotation, int i, bool firstFrame) { + + if (firstFrame) timelinesRotation[i] = 0; + + if (alpha == 1) { + timeline.Apply(skeleton, 0, time, null, 1, blend, MixDirection.In); + return; + } + + Bone bone = skeleton.bones.Items[timeline.boneIndex]; + if (!bone.active) return; + + float[] frames = timeline.frames; + float r1, r2; + if (time < frames[0]) { // Time is before first frame. + switch (blend) { + case MixBlend.Setup: + bone.rotation = bone.data.rotation; + return; + default: + return; + case MixBlend.First: + r1 = bone.rotation; + r2 = bone.data.rotation; + break; + } + } else { + r1 = blend == MixBlend.Setup ? bone.data.rotation : bone.rotation; + if (time >= frames[frames.Length - RotateTimeline.ENTRIES]) // Time is after last frame. + r2 = bone.data.rotation + frames[frames.Length + RotateTimeline.PREV_ROTATION]; + else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, RotateTimeline.ENTRIES); + float prevRotation = frames[frame + RotateTimeline.PREV_ROTATION]; + float frameTime = frames[frame]; + float percent = timeline.GetCurvePercent((frame >> 1) - 1, + 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime)); + + r2 = frames[frame + RotateTimeline.ROTATION] - prevRotation; + r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; + r2 = prevRotation + r2 * percent + bone.data.rotation; + r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; + } + } + + // Mix between rotations using the direction of the shortest route on the first frame. + float total, diff = r2 - r1; + diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360; + if (diff == 0) { + total = timelinesRotation[i]; + } else { + float lastTotal, lastDiff; + if (firstFrame) { + lastTotal = 0; + lastDiff = diff; + } else { + lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops. + lastDiff = timelinesRotation[i + 1]; // Difference between bones. + } + bool current = diff > 0, dir = lastTotal >= 0; + // Detect cross at 0 (not 180). + if (Math.Sign(lastDiff) != Math.Sign(diff) && Math.Abs(lastDiff) <= 90) { + // A cross after a 360 rotation is a loop. + if (Math.Abs(lastTotal) > 180) lastTotal += 360 * Math.Sign(lastTotal); + dir = current; + } + total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal. + if (dir != current) total += 360 * Math.Sign(lastTotal); + timelinesRotation[i] = total; + } + timelinesRotation[i + 1] = diff; + r1 += total * alpha; + bone.rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360; + } + + private void QueueEvents (TrackEntry entry, float animationTime) { + float animationStart = entry.animationStart, animationEnd = entry.animationEnd; + float duration = animationEnd - animationStart; + float trackLastWrapped = entry.trackLast % duration; + + // Queue events before complete. + var events = this.events; + var eventsItems = events.Items; + int i = 0, n = events.Count; + for (; i < n; i++) { + Event e = eventsItems[i]; + if (e.time < trackLastWrapped) break; + if (e.time > animationEnd) continue; // Discard events outside animation start/end. + queue.Event(entry, e); + } + + // Queue complete if completed a loop iteration or the animation. + bool complete = false; + if (entry.loop) + complete = duration == 0 || (trackLastWrapped > entry.trackTime % duration); + else + complete = animationTime >= animationEnd && entry.animationLast < animationEnd; + if (complete) queue.Complete(entry); + + // Queue events after complete. + for (; i < n; i++) { + Event e = eventsItems[i]; + if (e.time < animationStart) continue; // Discard events outside animation start/end. + queue.Event(entry, eventsItems[i]); + } + } + + /// + /// Removes all animations from all tracks, leaving skeletons in their current pose. + /// + /// It may be desired to use to mix the skeletons back to the setup pose, + /// rather than leaving them in their current pose. + /// + public void ClearTracks () { + bool oldDrainDisabled = queue.drainDisabled; + queue.drainDisabled = true; + for (int i = 0, n = tracks.Count; i < n; i++) { + ClearTrack(i); + } + tracks.Clear(); + queue.drainDisabled = oldDrainDisabled; + queue.Drain(); + } + + /// + /// Removes all animations from the track, leaving skeletons in their current pose. + /// + /// It may be desired to use to mix the skeletons back to the setup pose, + /// rather than leaving them in their current pose. + /// + public void ClearTrack (int trackIndex) { + if (trackIndex >= tracks.Count) return; + TrackEntry current = tracks.Items[trackIndex]; + if (current == null) return; + + queue.End(current); + + DisposeNext(current); + + TrackEntry entry = current; + while (true) { + TrackEntry from = entry.mixingFrom; + if (from == null) break; + queue.End(from); + entry.mixingFrom = null; + entry.mixingTo = null; + entry = from; + } + + tracks.Items[current.trackIndex] = null; + + queue.Drain(); + } + + /// Sets the active TrackEntry for a given track number. + private void SetCurrent (int index, TrackEntry current, bool interrupt) { + TrackEntry from = ExpandToIndex(index); + tracks.Items[index] = current; + + if (from != null) { + if (interrupt) queue.Interrupt(from); + current.mixingFrom = from; + from.mixingTo = current; + current.mixTime = 0; + + // Store the interrupted mix percentage. + if (from.mixingFrom != null && from.mixDuration > 0) + current.interruptAlpha *= Math.Min(1, from.mixTime / from.mixDuration); + + from.timelinesRotation.Clear(); // Reset rotation for mixing out, in case entry was mixed in. + } + + queue.Start(current); // triggers AnimationsChanged + } + + + /// Sets an animation by name. + public TrackEntry SetAnimation (int trackIndex, string animationName, bool loop) { + Animation animation = data.skeletonData.FindAnimation(animationName); + if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName"); + return SetAnimation(trackIndex, animation, loop); + } + + /// Sets the current animation for a track, discarding any queued animations. If the formerly current track entry was never + /// applied to a skeleton, it is replaced (not mixed from). + /// If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its + /// duration. In either case determines when the track is cleared. + /// A track entry to allow further customization of animation playback. References to the track entry must not be kept + /// after the event occurs. + public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) { + if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null."); + bool interrupt = true; + TrackEntry current = ExpandToIndex(trackIndex); + if (current != null) { + if (current.nextTrackLast == -1) { + // Don't mix from an entry that was never applied. + tracks.Items[trackIndex] = current.mixingFrom; + queue.Interrupt(current); + queue.End(current); + DisposeNext(current); + current = current.mixingFrom; + interrupt = false; // mixingFrom is current again, but don't interrupt it twice. + } else { + DisposeNext(current); + } + } + TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, current); + SetCurrent(trackIndex, entry, interrupt); + queue.Drain(); + return entry; + } + + /// Queues an animation by name. + /// + public TrackEntry AddAnimation (int trackIndex, string animationName, bool loop, float delay) { + Animation animation = data.skeletonData.FindAnimation(animationName); + if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName"); + return AddAnimation(trackIndex, animation, loop, delay); + } + + /// Adds an animation to be played after the current or last queued animation for a track. If the track is empty, it is + /// equivalent to calling . + /// + /// If > 0, sets . If <= 0, the delay set is the duration of the previous track entry + /// minus any mix duration (from the {@link AnimationStateData}) plus the specified Delay (ie the mix + /// ends at (Delay = 0) or before (Delay < 0) the previous track entry duration). If the + /// previous entry is looping, its next loop completion is used instead of its duration. + /// + /// A track entry to allow further customization of animation playback. References to the track entry must not be kept + /// after the event occurs. + public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) { + if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null."); + + TrackEntry last = ExpandToIndex(trackIndex); + if (last != null) { + while (last.next != null) + last = last.next; + } + + TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, last); + + if (last == null) { + SetCurrent(trackIndex, entry, true); + queue.Drain(); + } else { + last.next = entry; + if (delay <= 0) { + float duration = last.animationEnd - last.animationStart; + if (duration != 0) { + if (last.loop) { + delay += duration * (1 + (int)(last.trackTime / duration)); // Completion of next loop. + } else { + delay += Math.Max(duration, last.trackTime); // After duration, else next update. + } + delay -= data.GetMix(last.animation, animation); + } else + delay = last.trackTime; // Next update. + } + } + + entry.delay = delay; + return entry; + } + + /// + /// Sets an empty animation for a track, discarding any queued animations, and sets the track entry's + /// . An empty animation has no timelines and serves as a placeholder for mixing in or out. + /// + /// Mixing out is done by setting an empty animation with a mix duration using either , + /// , or . Mixing to an empty animation causes + /// the previous animation to be applied less and less over the mix duration. Properties keyed in the previous animation + /// transition to the value from lower tracks or to the setup pose value if no lower tracks key the property. A mix duration of + /// 0 still mixes out over one frame. + /// + /// Mixing in is done by first setting an empty animation, then adding an animation using + /// and on the returned track entry, set the + /// . Mixing from an empty animation causes the new animation to be applied more and + /// more over the mix duration. Properties keyed in the new animation transition from the value from lower tracks or from the + /// setup pose value if no lower tracks key the property to the value keyed in the new animation. + /// + public TrackEntry SetEmptyAnimation (int trackIndex, float mixDuration) { + TrackEntry entry = SetAnimation(trackIndex, AnimationState.EmptyAnimation, false); + entry.mixDuration = mixDuration; + entry.trackEnd = mixDuration; + return entry; + } + + /// + /// Adds an empty animation to be played after the current or last queued animation for a track, and sets the track entry's + /// . If the track is empty, it is equivalent to calling + /// . + /// + /// Track number. + /// Mix duration. + /// If > 0, sets . If <= 0, the delay set is the duration of the previous track entry + /// minus any mix duration plus the specified Delay (ie the mix ends at (Delay = 0) or + /// before (Delay < 0) the previous track entry duration). If the previous entry is looping, its next + /// loop completion is used instead of its duration. + /// A track entry to allow further customization of animation playback. References to the track entry must not be kept + /// after the event occurs. + /// + public TrackEntry AddEmptyAnimation (int trackIndex, float mixDuration, float delay) { + if (delay <= 0) delay -= mixDuration; + TrackEntry entry = AddAnimation(trackIndex, AnimationState.EmptyAnimation, false, delay); + entry.mixDuration = mixDuration; + entry.trackEnd = mixDuration; + return entry; + } + + /// + /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix + /// duration. + public void SetEmptyAnimations (float mixDuration) { + bool oldDrainDisabled = queue.drainDisabled; + queue.drainDisabled = true; + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry current = tracks.Items[i]; + if (current != null) SetEmptyAnimation(current.trackIndex, mixDuration); + } + queue.drainDisabled = oldDrainDisabled; + queue.Drain(); + } + + private TrackEntry ExpandToIndex (int index) { + if (index < tracks.Count) return tracks.Items[index]; + tracks.Resize(index + 1); + return null; + } + + /// Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values. + /// May be null. + private TrackEntry NewTrackEntry (int trackIndex, Animation animation, bool loop, TrackEntry last) { + TrackEntry entry = trackEntryPool.Obtain(); // Pooling + entry.trackIndex = trackIndex; + entry.animation = animation; + entry.loop = loop; + entry.holdPrevious = false; + + entry.eventThreshold = 0; + entry.attachmentThreshold = 0; + entry.drawOrderThreshold = 0; + + entry.animationStart = 0; + entry.animationEnd = animation.Duration; + entry.animationLast = -1; + entry.nextAnimationLast = -1; + + entry.delay = 0; + entry.trackTime = 0; + entry.trackLast = -1; + entry.nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet. + entry.trackEnd = float.MaxValue; // loop ? float.MaxValue : animation.Duration; + entry.timeScale = 1; + + entry.alpha = 1; + entry.interruptAlpha = 1; + entry.mixTime = 0; + entry.mixDuration = (last == null) ? 0 : data.GetMix(last.animation, animation); + return entry; + } + + /// Dispose all track entries queued after the given TrackEntry. + private void DisposeNext (TrackEntry entry) { + TrackEntry next = entry.next; + while (next != null) { + queue.Dispose(next); + next = next.next; + } + entry.next = null; + } + + private void AnimationsChanged () { + animationsChanged = false; + + // Process in the order that animations are applied. + propertyIDs.Clear(); + + var tracksItems = tracks.Items; + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry entry = tracksItems[i]; + if (entry == null) continue; + while (entry.mixingFrom != null) // Move to last entry, then iterate in reverse. + entry = entry.mixingFrom; + + do { + if (entry.mixingTo == null || entry.mixBlend != MixBlend.Add) ComputeHold(entry); + entry = entry.mixingTo; + } while (entry != null); + } + } + + private void ComputeHold (TrackEntry entry) { + TrackEntry to = entry.mixingTo; + var timelines = entry.animation.timelines.Items; + int timelinesCount = entry.animation.timelines.Count; + var timelineMode = entry.timelineMode.Resize(timelinesCount).Items; //timelineMode.setSize(timelinesCount); + entry.timelineHoldMix.Clear(); + var timelineHoldMix = entry.timelineHoldMix.Resize(timelinesCount).Items; //timelineHoldMix.setSize(timelinesCount); + var propertyIDs = this.propertyIDs; + + if (to != null && to.holdPrevious) { + for (int i = 0; i < timelinesCount; i++) + timelineMode[i] = propertyIDs.Add(timelines[i].PropertyId) ? AnimationState.HoldFirst : AnimationState.HoldSubsequent; + + return; + } + + // outer: + for (int i = 0; i < timelinesCount; i++) { + Timeline timeline = timelines[i]; + int id = timeline.PropertyId; + if (!propertyIDs.Add(id)) + timelineMode[i] = AnimationState.Subsequent; + else if (to == null || timeline is AttachmentTimeline || timeline is DrawOrderTimeline + || timeline is EventTimeline || !to.animation.HasTimeline(id)) { + timelineMode[i] = AnimationState.First; + } else { + for (TrackEntry next = to.mixingTo; next != null; next = next.mixingTo) { + if (next.animation.HasTimeline(id)) continue; + if (next.mixDuration > 0) { + timelineMode[i] = AnimationState.HoldMix; + timelineHoldMix[i] = next; + goto continue_outer; // continue outer; + } + break; + } + timelineMode[i] = AnimationState.HoldFirst; + } + continue_outer: {} + } + } + + /// The track entry for the animation currently playing on the track, or null if no animation is currently playing. + public TrackEntry GetCurrent (int trackIndex) { + if (trackIndex >= tracks.Count) return null; + return tracks.Items[trackIndex]; + } + + /// Discards all listener notifications that have not yet been delivered. This can be useful to call from an + /// AnimationState event subscriber when it is known that further notifications that may have been already queued for delivery + /// are not wanted because new animations are being set. + public void ClearListenerNotifications () { + queue.Clear(); + } + + /// + /// Multiplier for the delta time when the animation state is updated, causing time for all animations and mixes to play slower + /// or faster. Defaults to 1. + /// + /// See TrackEntry for affecting a single animation. + /// + public float TimeScale { get { return timeScale; } set { timeScale = value; } } + + /// The AnimationStateData to look up mix durations. + public AnimationStateData Data { + get { + return data; + } + set { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + this.data = value; + } + } + + /// A list of tracks that have animations, which may contain nulls. + public ExposedList Tracks { get { return tracks; } } + + override public string ToString () { + var buffer = new System.Text.StringBuilder(); + for (int i = 0, n = tracks.Count; i < n; i++) { + TrackEntry entry = tracks.Items[i]; + if (entry == null) continue; + if (buffer.Length > 0) buffer.Append(", "); + buffer.Append(entry.ToString()); + } + if (buffer.Length == 0) return ""; + return buffer.ToString(); + } + } + + /// + /// + /// Stores settings and other state for the playback of an animation on an track. + /// + /// References to a track entry must not be kept after the event occurs. + /// + public class TrackEntry : Pool.IPoolable { + internal Animation animation; + + internal TrackEntry next, mixingFrom, mixingTo; + // difference to libgdx reference: delegates are used for event callbacks instead of 'AnimationStateListener listener'. + public event AnimationState.TrackEntryDelegate Start, Interrupt, End, Dispose, Complete; + public event AnimationState.TrackEntryEventDelegate Event; + internal void OnStart () { if (Start != null) Start(this); } + internal void OnInterrupt () { if (Interrupt != null) Interrupt(this); } + internal void OnEnd () { if (End != null) End(this); } + internal void OnDispose () { if (Dispose != null) Dispose(this); } + internal void OnComplete () { if (Complete != null) Complete(this); } + internal void OnEvent (Event e) { if (Event != null) Event(this, e); } + + internal int trackIndex; + + internal bool loop, holdPrevious; + internal float eventThreshold, attachmentThreshold, drawOrderThreshold; + internal float animationStart, animationEnd, animationLast, nextAnimationLast; + internal float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale = 1f; + internal float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha; + internal MixBlend mixBlend = MixBlend.Replace; + internal readonly ExposedList timelineMode = new ExposedList(); + internal readonly ExposedList timelineHoldMix = new ExposedList(); + internal readonly ExposedList timelinesRotation = new ExposedList(); + + // IPoolable.Reset() + public void Reset () { + next = null; + mixingFrom = null; + mixingTo = null; + animation = null; + // replaces 'listener = null;' since delegates are used for event callbacks + Start = null; + Interrupt = null; + End = null; + Dispose = null; + Complete = null; + Event = null; + timelineMode.Clear(); + timelineHoldMix.Clear(); + timelinesRotation.Clear(); + } + + /// The index of the track where this entry is either current or queued. + /// + public int TrackIndex { get { return trackIndex; } } + + /// The animation to apply for this track entry. + public Animation Animation { get { return animation; } } + + /// + /// If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its + /// duration. + public bool Loop { get { return loop; } set { loop = value; } } + + /// + /// + /// Seconds to postpone playing the animation. When this track entry is the current track entry, Delay + /// postpones incrementing the . When this track entry is queued, Delay is the time from + /// the start of the previous animation to when this track entry will become the current track entry (ie when the previous + /// track entry >= this track entry's Delay). + /// + /// affects the delay. + /// + public float Delay { get { return delay; } set { delay = value; } } + + /// + /// Current time in seconds this track entry has been the current track entry. The track time determines + /// . The track time can be set to start the animation at a time other than 0, without affecting + /// looping. + public float TrackTime { get { return trackTime; } set { trackTime = value; } } + + /// + /// + /// The track time in seconds when this animation will be removed from the track. Defaults to the highest possible float + /// value, meaning the animation will be applied until a new animation is set or the track is cleared. If the track end time + /// is reached, no other animations are queued for playback, and mixing from any previous animations is complete, then the + /// properties keyed by the animation are set to the setup pose and the track is cleared. + /// + /// It may be desired to use rather than have the animation + /// abruptly cease being applied. + /// + public float TrackEnd { get { return trackEnd; } set { trackEnd = value; } } + + /// + /// + /// Seconds when this animation starts, both initially and after looping. Defaults to 0. + /// + /// When changing the AnimationStart time, it often makes sense to set to the same + /// value to prevent timeline keys before the start time from triggering. + /// + public float AnimationStart { get { return animationStart; } set { animationStart = value; } } + + /// + /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will + /// loop back to at this time. Defaults to the animation . + /// + public float AnimationEnd { get { return animationEnd; } set { animationEnd = value; } } + + /// + /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this + /// animation is applied, event timelines will fire all events between the AnimationLast time (exclusive) and + /// AnimationTime (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation + /// is applied. + public float AnimationLast { + get { return animationLast; } + set { + animationLast = value; + nextAnimationLast = value; + } + } + + /// + /// Uses to compute the AnimationTime, which is between + /// and . When the TrackTime is 0, the AnimationTime is equal to the + /// AnimationStart time. + /// + public float AnimationTime { + get { + if (loop) { + float duration = animationEnd - animationStart; + if (duration == 0) return animationStart; + return (trackTime % duration) + animationStart; + } + return Math.Min(trackTime + animationStart, animationEnd); + } + } + + /// + /// + /// Multiplier for the delta time when this track entry is updated, causing time for this animation to pass slower or + /// faster. Defaults to 1. + /// + /// is not affected by track entry time scale, so may need to be adjusted to + /// match the animation speed. + /// + /// When using with a Delay <= 0, note the + /// { is set using the mix duration from the , assuming time scale to be 1. If + /// the time scale is not 1, the delay may need to be adjusted. + /// + /// See AnimationState for affecting all animations. + /// + public float TimeScale { get { return timeScale; } set { timeScale = value; } } + + /// + /// + /// Values < 1 mix this animation with the skeleton's current pose (usually the pose resulting from lower tracks). Defaults + /// to 1, which overwrites the skeleton's current pose with this animation. + /// + /// Typically track 0 is used to completely pose the skeleton, then alpha is used on higher tracks. It doesn't make sense to + /// use alpha on track 0 if the skeleton pose is from the last frame render. + /// + public float Alpha { get { return alpha; } set { alpha = value; } } + + /// + /// When the mix percentage ( / ) is less than the + /// EventThreshold, event timelines are applied while this animation is being mixed out. Defaults to 0, so event + /// timelines are not applied while this animation is being mixed out. + /// + public float EventThreshold { get { return eventThreshold; } set { eventThreshold = value; } } + + /// + /// When the mix percentage ( / ) is less than the + /// AttachmentThreshold, attachment timelines are applied while this animation is being mixed out. Defaults to + /// 0, so attachment timelines are not applied while this animation is being mixed out. + /// + public float AttachmentThreshold { get { return attachmentThreshold; } set { attachmentThreshold = value; } } + + /// + /// When the mix percentage ( / ) is less than the + /// DrawOrderThreshold, draw order timelines are applied while this animation is being mixed out. Defaults to 0, + /// so draw order timelines are not applied while this animation is being mixed out. + /// + public float DrawOrderThreshold { get { return drawOrderThreshold; } set { drawOrderThreshold = value; } } + + /// + /// The animation queued to start after this animation, or null. Next makes up a linked list. + public TrackEntry Next { get { return next; } } + + /// + /// Returns true if at least one loop has been completed. + /// + public bool IsComplete { + get { return trackTime >= animationEnd - animationStart; } + } + + /// + /// Seconds from 0 to the when mixing from the previous animation to this animation. May be + /// slightly more than MixDuration when the mix is complete. + public float MixTime { get { return mixTime; } set { mixTime = value; } } + + /// + /// + /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by AnimationStateData + /// based on the animation before this animation (if any). + /// + /// The MixDuration can be set manually rather than use the value from + /// . In that case, the MixDuration can be set for a new + /// track entry only before is first called. + /// + /// When using with a Delay <= 0, note the + /// is set using the mix duration from the , not a mix duration set + /// afterward. + /// + public float MixDuration { get { return mixDuration; } set { mixDuration = value; } } + + /// + /// + /// Controls how properties keyed in the animation are mixed with lower tracks. Defaults to , which + /// replaces the values from the lower tracks with the animation values. adds the animation values to + /// the values from the lower tracks. + /// + /// The MixBlend can be set for a new track entry only before is first + /// called. + /// + public MixBlend MixBlend { get { return mixBlend; } set { mixBlend = value; } } + + /// + /// The track entry for the previous animation when mixing from the previous animation to this animation, or null if no + /// mixing is currently occuring. When mixing from multiple animations, MixingFrom makes up a linked list. + public TrackEntry MixingFrom { get { return mixingFrom; } } + + /// + /// The track entry for the next animation when mixing from this animation to the next animation, or null if no mixing is + /// currently occuring. When mixing to multiple animations, MixingTo makes up a linked list. + public TrackEntry MixingTo { get { return mixingTo; } } + + /// + /// + /// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead + /// of being mixed out. + /// + /// When mixing between animations that key the same property, if a lower track also keys that property then the value will + /// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0% + /// while the second animation mixes from 0% to 100%. Setting HoldPrevious to true applies the first animation + /// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which + /// keys the property, only when a higher track also keys the property. + /// + /// Snapping will occur if HoldPrevious is true and this animation does not key all the same properties as the + /// previous animation. + /// + public bool HoldPrevious { get { return holdPrevious; } set { holdPrevious = value; } } + + /// + /// + /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the + /// long way around when using and starting animations on other tracks. + /// + /// Mixing with involves finding a rotation between two others, which has two possible solutions: + /// the short way or the long way around. The two rotations likely change over time, so which direction is the short or long + /// way also changes. If the short way was always chosen, bones would flip to the other side when that direction became the + /// long way. TrackEntry chooses the short way the first time it is applied and remembers that direction. + /// + public void ResetRotationDirections () { + timelinesRotation.Clear(); + } + + override public string ToString () { + return animation == null ? "" : animation.name; + } + } + + class EventQueue { + private readonly List eventQueueEntries = new List(); + internal bool drainDisabled; + + private readonly AnimationState state; + private readonly Pool trackEntryPool; + internal event Action AnimationsChanged; + + internal EventQueue (AnimationState state, Action HandleAnimationsChanged, Pool trackEntryPool) { + this.state = state; + this.AnimationsChanged += HandleAnimationsChanged; + this.trackEntryPool = trackEntryPool; + } + + struct EventQueueEntry { + public EventType type; + public TrackEntry entry; + public Event e; + + public EventQueueEntry (EventType eventType, TrackEntry trackEntry, Event e = null) { + this.type = eventType; + this.entry = trackEntry; + this.e = e; + } + } + + enum EventType { + Start, Interrupt, End, Dispose, Complete, Event + } + + internal void Start (TrackEntry entry) { + eventQueueEntries.Add(new EventQueueEntry(EventType.Start, entry)); + if (AnimationsChanged != null) AnimationsChanged(); + } + + internal void Interrupt (TrackEntry entry) { + eventQueueEntries.Add(new EventQueueEntry(EventType.Interrupt, entry)); + } + + internal void End (TrackEntry entry) { + eventQueueEntries.Add(new EventQueueEntry(EventType.End, entry)); + if (AnimationsChanged != null) AnimationsChanged(); + } + + internal void Dispose (TrackEntry entry) { + eventQueueEntries.Add(new EventQueueEntry(EventType.Dispose, entry)); + } + + internal void Complete (TrackEntry entry) { + eventQueueEntries.Add(new EventQueueEntry(EventType.Complete, entry)); + } + + internal void Event (TrackEntry entry, Event e) { + eventQueueEntries.Add(new EventQueueEntry(EventType.Event, entry, e)); + } + + /// Raises all events in the queue and drains the queue. + internal void Drain () { + if (drainDisabled) return; + drainDisabled = true; + + var entries = this.eventQueueEntries; + AnimationState state = this.state; + + // Don't cache entries.Count so callbacks can queue their own events (eg, call SetAnimation in AnimationState_Complete). + for (int i = 0; i < entries.Count; i++) { + var queueEntry = entries[i]; + TrackEntry trackEntry = queueEntry.entry; + + switch (queueEntry.type) { + case EventType.Start: + trackEntry.OnStart(); + state.OnStart(trackEntry); + break; + case EventType.Interrupt: + trackEntry.OnInterrupt(); + state.OnInterrupt(trackEntry); + break; + case EventType.End: + trackEntry.OnEnd(); + state.OnEnd(trackEntry); + goto case EventType.Dispose; // Fall through. (C#) + case EventType.Dispose: + trackEntry.OnDispose(); + state.OnDispose(trackEntry); + trackEntryPool.Free(trackEntry); // Pooling + break; + case EventType.Complete: + trackEntry.OnComplete(); + state.OnComplete(trackEntry); + break; + case EventType.Event: + trackEntry.OnEvent(queueEntry.e); + state.OnEvent(trackEntry, queueEntry.e); + break; + } + } + eventQueueEntries.Clear(); + + drainDisabled = false; + } + + internal void Clear () { + eventQueueEntries.Clear(); + } + } + + public class Pool where T : class, new() { + public readonly int max; + readonly Stack freeObjects; + + public int Count { get { return freeObjects.Count; } } + public int Peak { get; private set; } + + public Pool (int initialCapacity = 16, int max = int.MaxValue) { + freeObjects = new Stack(initialCapacity); + this.max = max; + } + + public T Obtain () { + return freeObjects.Count == 0 ? new T() : freeObjects.Pop(); + } + + public void Free (T obj) { + if (obj == null) throw new ArgumentNullException("obj", "obj cannot be null"); + if (freeObjects.Count < max) { + freeObjects.Push(obj); + Peak = Math.Max(Peak, freeObjects.Count); + } + Reset(obj); + } + +// protected void FreeAll (List objects) { +// if (objects == null) throw new ArgumentNullException("objects", "objects cannot be null."); +// var freeObjects = this.freeObjects; +// int max = this.max; +// for (int i = 0; i < objects.Count; i++) { +// T obj = objects[i]; +// if (obj == null) continue; +// if (freeObjects.Count < max) freeObjects.Push(obj); +// Reset(obj); +// } +// Peak = Math.Max(Peak, freeObjects.Count); +// } + + public void Clear () { + freeObjects.Clear(); + } + + protected void Reset (T obj) { + var poolable = obj as IPoolable; + if (poolable != null) poolable.Reset(); + } + + public interface IPoolable { + void Reset (); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs.meta new file mode 100644 index 0000000..a6522a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationState.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ec2f0e7143c8a174994595883f4b1e33 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs new file mode 100644 index 0000000..6cda146 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs @@ -0,0 +1,114 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + + /// Stores mix (crossfade) durations to be applied when AnimationState animations are changed. + public class AnimationStateData { + internal SkeletonData skeletonData; + readonly Dictionary animationToMixTime = new Dictionary(AnimationPairComparer.Instance); + internal float defaultMix; + + /// The SkeletonData to look up animations when they are specified by name. + public SkeletonData SkeletonData { get { return skeletonData; } } + + /// + /// The mix duration to use when no mix duration has been specifically defined between two animations. + public float DefaultMix { get { return defaultMix; } set { defaultMix = value; } } + + public AnimationStateData (SkeletonData skeletonData) { + if (skeletonData == null) throw new ArgumentException("skeletonData cannot be null.", "skeletonData"); + this.skeletonData = skeletonData; + } + + /// Sets a mix duration by animation names. + public void SetMix (string fromName, string toName, float duration) { + Animation from = skeletonData.FindAnimation(fromName); + if (from == null) throw new ArgumentException("Animation not found: " + fromName, "fromName"); + Animation to = skeletonData.FindAnimation(toName); + if (to == null) throw new ArgumentException("Animation not found: " + toName, "toName"); + SetMix(from, to, duration); + } + + /// Sets a mix duration when changing from the specified animation to the other. + /// See TrackEntry.MixDuration. + public void SetMix (Animation from, Animation to, float duration) { + if (from == null) throw new ArgumentNullException("from", "from cannot be null."); + if (to == null) throw new ArgumentNullException("to", "to cannot be null."); + AnimationPair key = new AnimationPair(from, to); + animationToMixTime.Remove(key); + animationToMixTime.Add(key, duration); + } + + /// + /// The mix duration to use when changing from the specified animation to the other, + /// or the DefaultMix if no mix duration has been set. + /// + public float GetMix (Animation from, Animation to) { + if (from == null) throw new ArgumentNullException("from", "from cannot be null."); + if (to == null) throw new ArgumentNullException("to", "to cannot be null."); + AnimationPair key = new AnimationPair(from, to); + float duration; + if (animationToMixTime.TryGetValue(key, out duration)) return duration; + return defaultMix; + } + + public struct AnimationPair { + public readonly Animation a1; + public readonly Animation a2; + + public AnimationPair (Animation a1, Animation a2) { + this.a1 = a1; + this.a2 = a2; + } + + public override string ToString () { + return a1.name + "->" + a2.name; + } + } + + // Avoids boxing in the dictionary. + public class AnimationPairComparer : IEqualityComparer { + public static readonly AnimationPairComparer Instance = new AnimationPairComparer(); + + bool IEqualityComparer.Equals (AnimationPair x, AnimationPair y) { + return ReferenceEquals(x.a1, y.a1) && ReferenceEquals(x.a2, y.a2); + } + + int IEqualityComparer.GetHashCode (AnimationPair obj) { + // from Tuple.CombineHashCodes // return (((h1 << 5) + h1) ^ h2); + int h1 = obj.a1.GetHashCode(); + return (((h1 << 5) + h1) ^ obj.a2.GetHashCode()); + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs.meta new file mode 100644 index 0000000..9890a1f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/AnimationStateData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e03d60c517d9b974db35b9fd144a1d09 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs new file mode 100644 index 0000000..aeaf105 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs @@ -0,0 +1,330 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1) +#define IS_UNITY +#endif + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Reflection; + +#if WINDOWS_STOREAPP +using System.Threading.Tasks; +using Windows.Storage; +#endif + +namespace Spine { + public class Atlas : IEnumerable { + readonly List pages = new List(); + List regions = new List(); + TextureLoader textureLoader; + + #region IEnumerable implementation + public IEnumerator GetEnumerator () { + return regions.GetEnumerator(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { + return regions.GetEnumerator(); + } + #endregion + + public List Regions { get { return regions; } } + public List Pages { get { return pages; } } + + #if !(IS_UNITY) + #if WINDOWS_STOREAPP + private async Task ReadFile(string path, TextureLoader textureLoader) { + var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; + var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false); + using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) { + try { + Load(reader, Path.GetDirectoryName(path), textureLoader); + } catch (Exception ex) { + throw new Exception("Error reading atlas file: " + path, ex); + } + } + } + + public Atlas(string path, TextureLoader textureLoader) { + this.ReadFile(path, textureLoader).Wait(); + } + #else + + public Atlas (string path, TextureLoader textureLoader) { + + #if WINDOWS_PHONE + Stream stream = Microsoft.Xna.Framework.TitleContainer.OpenStream(path); + using (StreamReader reader = new StreamReader(stream)) { + #else + using (StreamReader reader = new StreamReader(path)) { + #endif // WINDOWS_PHONE + + try { + Load(reader, Path.GetDirectoryName(path), textureLoader); + } catch (Exception ex) { + throw new Exception("Error reading atlas file: " + path, ex); + } + + } + } + #endif // WINDOWS_STOREAPP + + #endif + + public Atlas (TextReader reader, string dir, TextureLoader textureLoader) { + Load(reader, dir, textureLoader); + } + + public Atlas (List pages, List regions) { + this.pages = pages; + this.regions = regions; + this.textureLoader = null; + } + + private void Load (TextReader reader, string imagesDir, TextureLoader textureLoader) { + if (textureLoader == null) throw new ArgumentNullException("textureLoader", "textureLoader cannot be null."); + this.textureLoader = textureLoader; + + string[] tuple = new string[4]; + AtlasPage page = null; + while (true) { + string line = reader.ReadLine(); + if (line == null) break; + if (line.Trim().Length == 0) + page = null; + else if (page == null) { + page = new AtlasPage(); + page.name = line; + + if (ReadTuple(reader, tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. + page.width = int.Parse(tuple[0], CultureInfo.InvariantCulture); + page.height = int.Parse(tuple[1], CultureInfo.InvariantCulture); + ReadTuple(reader, tuple); + } + page.format = (Format)Enum.Parse(typeof(Format), tuple[0], false); + + ReadTuple(reader, tuple); + page.minFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[0], false); + page.magFilter = (TextureFilter)Enum.Parse(typeof(TextureFilter), tuple[1], false); + + string direction = ReadValue(reader); + page.uWrap = TextureWrap.ClampToEdge; + page.vWrap = TextureWrap.ClampToEdge; + if (direction == "x") + page.uWrap = TextureWrap.Repeat; + else if (direction == "y") + page.vWrap = TextureWrap.Repeat; + else if (direction == "xy") + page.uWrap = page.vWrap = TextureWrap.Repeat; + + textureLoader.Load(page, Path.Combine(imagesDir, line)); + + pages.Add(page); + + } else { + AtlasRegion region = new AtlasRegion(); + region.name = line; + region.page = page; + + string rotateValue = ReadValue(reader); + if (rotateValue == "true") + region.degrees = 90; + else if (rotateValue == "false") + region.degrees = 0; + else + region.degrees = int.Parse(rotateValue); + region.rotate = region.degrees == 90; + + ReadTuple(reader, tuple); + int x = int.Parse(tuple[0], CultureInfo.InvariantCulture); + int y = int.Parse(tuple[1], CultureInfo.InvariantCulture); + + ReadTuple(reader, tuple); + int width = int.Parse(tuple[0], CultureInfo.InvariantCulture); + int height = int.Parse(tuple[1], CultureInfo.InvariantCulture); + + region.u = x / (float)page.width; + region.v = y / (float)page.height; + if (region.rotate) { + region.u2 = (x + height) / (float)page.width; + region.v2 = (y + width) / (float)page.height; + } else { + region.u2 = (x + width) / (float)page.width; + region.v2 = (y + height) / (float)page.height; + } + region.x = x; + region.y = y; + region.width = Math.Abs(width); + region.height = Math.Abs(height); + + if (ReadTuple(reader, tuple) == 4) { // split is optional + region.splits = new [] {int.Parse(tuple[0], CultureInfo.InvariantCulture), + int.Parse(tuple[1], CultureInfo.InvariantCulture), + int.Parse(tuple[2], CultureInfo.InvariantCulture), + int.Parse(tuple[3], CultureInfo.InvariantCulture)}; + + if (ReadTuple(reader, tuple) == 4) { // pad is optional, but only present with splits + region.pads = new [] {int.Parse(tuple[0], CultureInfo.InvariantCulture), + int.Parse(tuple[1], CultureInfo.InvariantCulture), + int.Parse(tuple[2], CultureInfo.InvariantCulture), + int.Parse(tuple[3], CultureInfo.InvariantCulture)}; + + ReadTuple(reader, tuple); + } + } + + region.originalWidth = int.Parse(tuple[0], CultureInfo.InvariantCulture); + region.originalHeight = int.Parse(tuple[1], CultureInfo.InvariantCulture); + + ReadTuple(reader, tuple); + region.offsetX = int.Parse(tuple[0], CultureInfo.InvariantCulture); + region.offsetY = int.Parse(tuple[1], CultureInfo.InvariantCulture); + + region.index = int.Parse(ReadValue(reader), CultureInfo.InvariantCulture); + + regions.Add(region); + } + } + } + + static string ReadValue (TextReader reader) { + string line = reader.ReadLine(); + int colon = line.IndexOf(':'); + if (colon == -1) throw new Exception("Invalid line: " + line); + return line.Substring(colon + 1).Trim(); + } + + /// Returns the number of tuple values read (1, 2 or 4). + static int ReadTuple (TextReader reader, string[] tuple) { + string line = reader.ReadLine(); + int colon = line.IndexOf(':'); + if (colon == -1) throw new Exception("Invalid line: " + line); + int i = 0, lastMatch = colon + 1; + for (; i < 3; i++) { + int comma = line.IndexOf(',', lastMatch); + if (comma == -1) break; + tuple[i] = line.Substring(lastMatch, comma - lastMatch).Trim(); + lastMatch = comma + 1; + } + tuple[i] = line.Substring(lastMatch).Trim(); + return i + 1; + } + + public void FlipV () { + for (int i = 0, n = regions.Count; i < n; i++) { + AtlasRegion region = regions[i]; + region.v = 1 - region.v; + region.v2 = 1 - region.v2; + } + } + + /// Returns the first region found with the specified name. This method uses string comparison to find the region, so the result + /// should be cached rather than calling this method multiple times. + /// The region, or null. + public AtlasRegion FindRegion (string name) { + for (int i = 0, n = regions.Count; i < n; i++) + if (regions[i].name == name) return regions[i]; + return null; + } + + public void Dispose () { + if (textureLoader == null) return; + for (int i = 0, n = pages.Count; i < n; i++) + textureLoader.Unload(pages[i].rendererObject); + } + } + + public enum Format { + Alpha, + Intensity, + LuminanceAlpha, + RGB565, + RGBA4444, + RGB888, + RGBA8888 + } + + public enum TextureFilter { + Nearest, + Linear, + MipMap, + MipMapNearestNearest, + MipMapLinearNearest, + MipMapNearestLinear, + MipMapLinearLinear + } + + public enum TextureWrap { + MirroredRepeat, + ClampToEdge, + Repeat + } + + public class AtlasPage { + public string name; + public Format format; + public TextureFilter minFilter; + public TextureFilter magFilter; + public TextureWrap uWrap; + public TextureWrap vWrap; + public object rendererObject; + public int width, height; + + public AtlasPage Clone () { + return MemberwiseClone() as AtlasPage; + } + } + + public class AtlasRegion { + public AtlasPage page; + public string name; + public int x, y, width, height; + public float u, v, u2, v2; + public float offsetX, offsetY; + public int originalWidth, originalHeight; + public int index; + public bool rotate; + public int degrees; + public int[] splits; + public int[] pads; + + public AtlasRegion Clone () { + return MemberwiseClone() as AtlasRegion; + } + } + + public interface TextureLoader { + void Load (AtlasPage page, string path); + void Unload (Object texture); + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs.meta new file mode 100644 index 0000000..8fcbba5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Atlas.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 60626307629cc034bafd42c53a901fff +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments.meta new file mode 100644 index 0000000..e1b89fe --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2afe1c6b912aac54abb5925ca4ac52c2 +folderAsset: yes +timeCreated: 1456265152 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs new file mode 100644 index 0000000..52b4059 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs @@ -0,0 +1,109 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + + /// + /// An AttachmentLoader that configures attachments using texture regions from an Atlas. + /// See Loading Skeleton Data in the Spine Runtimes Guide. + /// + public class AtlasAttachmentLoader : AttachmentLoader { + private Atlas[] atlasArray; + + public AtlasAttachmentLoader (params Atlas[] atlasArray) { + if (atlasArray == null) throw new ArgumentNullException("atlas array cannot be null."); + this.atlasArray = atlasArray; + } + + public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) { + AtlasRegion region = FindRegion(path); + if (region == null) throw new ArgumentException(string.Format("Region not found in atlas: {0} (region attachment: {1})", path, name)); + RegionAttachment attachment = new RegionAttachment(name); + attachment.RendererObject = region; + attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); + attachment.regionOffsetX = region.offsetX; + attachment.regionOffsetY = region.offsetY; + attachment.regionWidth = region.width; + attachment.regionHeight = region.height; + attachment.regionOriginalWidth = region.originalWidth; + attachment.regionOriginalHeight = region.originalHeight; + return attachment; + } + + public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) { + AtlasRegion region = FindRegion(path); + if (region == null) throw new ArgumentException(string.Format("Region not found in atlas: {0} (region attachment: {1})", path, name)); + MeshAttachment attachment = new MeshAttachment(name); + attachment.RendererObject = region; + attachment.RegionU = region.u; + attachment.RegionV = region.v; + attachment.RegionU2 = region.u2; + attachment.RegionV2 = region.v2; + attachment.RegionRotate = region.rotate; + attachment.RegionDegrees = region.degrees; + attachment.regionOffsetX = region.offsetX; + attachment.regionOffsetY = region.offsetY; + attachment.regionWidth = region.width; + attachment.regionHeight = region.height; + attachment.regionOriginalWidth = region.originalWidth; + attachment.regionOriginalHeight = region.originalHeight; + return attachment; + } + + public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) { + return new BoundingBoxAttachment(name); + } + + public PathAttachment NewPathAttachment (Skin skin, string name) { + return new PathAttachment(name); + } + + public PointAttachment NewPointAttachment (Skin skin, string name) { + return new PointAttachment(name); + } + + public ClippingAttachment NewClippingAttachment(Skin skin, string name) { + return new ClippingAttachment(name); + } + + public AtlasRegion FindRegion (string name) { + AtlasRegion region; + + for (int i = 0; i < atlasArray.Length; i++) { + region = atlasArray[i].FindRegion(name); + if (region != null) + return region; + } + + return null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs.meta new file mode 100644 index 0000000..7b0e50e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AtlasAttachmentLoader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3e6ff30e27c28344bad3e67d308c94cd +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs new file mode 100644 index 0000000..80918bc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs @@ -0,0 +1,52 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + abstract public class Attachment { + public string Name { get; private set; } + + protected Attachment (string name) { + if (name == null) throw new ArgumentNullException("name", "name cannot be null"); + Name = name; + } + + override public string ToString () { + return Name; + } + + ///Returns a copy of the attachment. + public abstract Attachment Copy (); + } + + public interface IHasRendererObject { + object RendererObject { get; set; } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs.meta new file mode 100644 index 0000000..f396651 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/Attachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 05b56321b2ddd8145a888746bc6ab917 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs new file mode 100644 index 0000000..962376b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs @@ -0,0 +1,48 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine { + public interface AttachmentLoader { + /// May be null to not load any attachment. + RegionAttachment NewRegionAttachment (Skin skin, string name, string path); + + /// May be null to not load any attachment. + MeshAttachment NewMeshAttachment (Skin skin, string name, string path); + + /// May be null to not load any attachment. + BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name); + + /// May be null to not load any attachment + PathAttachment NewPathAttachment (Skin skin, string name); + + PointAttachment NewPointAttachment (Skin skin, string name); + + ClippingAttachment NewClippingAttachment (Skin skin, string name); + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs.meta new file mode 100644 index 0000000..6e765cf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentLoader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 95466a4f5a30dca4aa69e8ee7df8ae85 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs new file mode 100644 index 0000000..09000e5 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs @@ -0,0 +1,34 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine { + public enum AttachmentType { + Region, Boundingbox, Mesh, Linkedmesh, Path, Point, Clipping + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs.meta new file mode 100644 index 0000000..3eb0eb4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/AttachmentType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d6b1941960a9f6f47be3e865554d8695 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs new file mode 100644 index 0000000..f9b7369 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs @@ -0,0 +1,45 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// Attachment that has a polygon for bounds checking. + public class BoundingBoxAttachment : VertexAttachment { + public BoundingBoxAttachment (string name) + : base(name) { + } + + public override Attachment Copy () { + BoundingBoxAttachment copy = new BoundingBoxAttachment(this.Name); + CopyTo(copy); + return copy; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs.meta new file mode 100644 index 0000000..eba3432 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/BoundingBoxAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cd8ad8fc0f5bce448ba26d096ab32e85 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs new file mode 100644 index 0000000..b0aa8db --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs @@ -0,0 +1,48 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class ClippingAttachment : VertexAttachment { + internal SlotData endSlot; + + public SlotData EndSlot { get { return endSlot; } set { endSlot = value; } } + + public ClippingAttachment(string name) : base(name) { + } + + public override Attachment Copy () { + ClippingAttachment copy = new ClippingAttachment(this.Name); + CopyTo(copy); + copy.endSlot = endSlot; + return copy; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs.meta new file mode 100644 index 0000000..fb2404f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/ClippingAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3380954b107f38b4c85a4cdfeceace42 +timeCreated: 1492744746 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs new file mode 100644 index 0000000..fad2ee1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs @@ -0,0 +1,224 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// Attachment that displays a texture region using a mesh. + public class MeshAttachment : VertexAttachment, IHasRendererObject { + internal float regionOffsetX, regionOffsetY, regionWidth, regionHeight, regionOriginalWidth, regionOriginalHeight; + private MeshAttachment parentMesh; + internal float[] uvs, regionUVs; + internal int[] triangles; + internal float r = 1, g = 1, b = 1, a = 1; + internal int hulllength; + + public int HullLength { get { return hulllength; } set { hulllength = value; } } + public float[] RegionUVs { get { return regionUVs; } set { regionUVs = value; } } + /// The UV pair for each vertex, normalized within the entire texture. + public float[] UVs { get { return uvs; } set { uvs = value; } } + public int[] Triangles { get { return triangles; } set { triangles = value; } } + + public float R { get { return r; } set { r = value; } } + public float G { get { return g; } set { g = value; } } + public float B { get { return b; } set { b = value; } } + public float A { get { return a; } set { a = value; } } + + public string Path { get; set; } + public object RendererObject { get; set; } + public float RegionU { get; set; } + public float RegionV { get; set; } + public float RegionU2 { get; set; } + public float RegionV2 { get; set; } + public bool RegionRotate { get; set; } + public int RegionDegrees { get; set; } + public float RegionOffsetX { get { return regionOffsetX; } set { regionOffsetX = value; } } + public float RegionOffsetY { get { return regionOffsetY; } set { regionOffsetY = value; } } // Pixels stripped from the bottom left, unrotated. + public float RegionWidth { get { return regionWidth; } set { regionWidth = value; } } + public float RegionHeight { get { return regionHeight; } set { regionHeight = value; } } // Unrotated, stripped size. + public float RegionOriginalWidth { get { return regionOriginalWidth; } set { regionOriginalWidth = value; } } + public float RegionOriginalHeight { get { return regionOriginalHeight; } set { regionOriginalHeight = value; } } // Unrotated, unstripped size. + + public MeshAttachment ParentMesh { + get { return parentMesh; } + set { + parentMesh = value; + if (value != null) { + bones = value.bones; + vertices = value.vertices; + worldVerticesLength = value.worldVerticesLength; + regionUVs = value.regionUVs; + triangles = value.triangles; + HullLength = value.HullLength; + Edges = value.Edges; + Width = value.Width; + Height = value.Height; + } + } + } + + // Nonessential. + public int[] Edges { get; set; } + public float Width { get; set; } + public float Height { get; set; } + + public MeshAttachment (string name) + : base(name) { + } + + public void UpdateUVs () { + float[] regionUVs = this.regionUVs; + if (this.uvs == null || this.uvs.Length != regionUVs.Length) this.uvs = new float[regionUVs.Length]; + float[] uvs = this.uvs; + float u = RegionU, v = RegionV, width = 0, height = 0; + + if (RegionDegrees == 90) { + float textureHeight = this.regionWidth / (RegionV2 - RegionV); + float textureWidth = this.regionHeight / (RegionU2 - RegionU); + u -= (RegionOriginalHeight - RegionOffsetY - RegionHeight) / textureWidth; + v -= (RegionOriginalWidth - RegionOffsetX - RegionWidth) / textureHeight; + width = RegionOriginalHeight / textureWidth; + height = RegionOriginalWidth / textureHeight; + + for (int i = 0, n = uvs.Length; i < n; i += 2) { + uvs[i] = u + regionUVs[i + 1] * width; + uvs[i + 1] = v + (1 - regionUVs[i]) * height; + } + } else if (RegionDegrees == 180) { + float textureWidth = this.regionWidth / (RegionU2 - RegionU); + float textureHeight = this.regionHeight / (RegionV2 - RegionV); + u -= (RegionOriginalWidth - RegionOffsetX - RegionWidth) / textureWidth; + v -= RegionOffsetY / textureHeight; + width = RegionOriginalWidth / textureWidth; + height = RegionOriginalHeight / textureHeight; + + for (int i = 0, n = uvs.Length; i < n; i += 2) { + uvs[i] = u + (1 - regionUVs[i]) * width; + uvs[i + 1] = v + (1 - regionUVs[i + 1]) * height; + } + } else if (RegionDegrees == 270) { + float textureWidth = this.regionWidth / (RegionU2 - RegionU); + float textureHeight = this.regionHeight / (RegionV2 - RegionV); + u -= RegionOffsetY / textureWidth; + v -= RegionOffsetX / textureHeight; + width = RegionOriginalHeight / textureWidth; + height = RegionOriginalWidth / textureHeight; + + for (int i = 0, n = uvs.Length; iReturns a new mesh with this mesh set as the . + public MeshAttachment NewLinkedMesh () { + MeshAttachment mesh = new MeshAttachment(Name); + mesh.RendererObject = RendererObject; + mesh.regionOffsetX = regionOffsetX; + mesh.regionOffsetY = regionOffsetY; + mesh.regionWidth = regionWidth; + mesh.regionHeight = regionHeight; + mesh.regionOriginalWidth = regionOriginalWidth; + mesh.regionOriginalHeight = regionOriginalHeight; + mesh.RegionDegrees = RegionDegrees; + mesh.RegionRotate = RegionRotate; + mesh.RegionU = RegionU; + mesh.RegionV = RegionV; + mesh.RegionU2 = RegionU2; + mesh.RegionV2 = RegionV2; + + mesh.Path = Path; + mesh.r = r; + mesh.g = g; + mesh.b = b; + mesh.a = a; + + mesh.deformAttachment = deformAttachment; + mesh.ParentMesh = parentMesh != null ? parentMesh : this; + mesh.UpdateUVs(); + return mesh; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs.meta new file mode 100644 index 0000000..72ca3dd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/MeshAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7f7514a003143844b6d01ecc93ed4d5 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs new file mode 100644 index 0000000..375379d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs @@ -0,0 +1,57 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + public class PathAttachment : VertexAttachment { + internal float[] lengths; + internal bool closed, constantSpeed; + + /// The length in the setup pose from the start of the path to the end of each curve. + public float[] Lengths { get { return lengths; } set { lengths = value; } } + public bool Closed { get { return closed; } set { closed = value; } } + public bool ConstantSpeed { get { return constantSpeed; } set { constantSpeed = value; } } + + public PathAttachment (String name) + : base(name) { + } + + public override Attachment Copy () { + PathAttachment copy = new PathAttachment(this.Name); + CopyTo(copy); + copy.lengths = new float[lengths.Length]; + Array.Copy(lengths, 0, copy.lengths, 0, lengths.Length); + copy.closed = closed; + copy.constantSpeed = constantSpeed; + return copy; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs.meta new file mode 100644 index 0000000..f9feef9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PathAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c77d9bf384a1e9f41966464e7e3b4870 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs new file mode 100644 index 0000000..be4668e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs @@ -0,0 +1,67 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine { + /// + /// An attachment which is a single point and a rotation. This can be used to spawn projectiles, particles, etc. A bone can be + /// used in similar ways, but a PointAttachment is slightly less expensive to compute and can be hidden, shown, and placed in a + /// skin. + ///

+ /// See Point Attachments in the Spine User Guide. + ///

+ public class PointAttachment : Attachment { + internal float x, y, rotation; + public float X { get { return x; } set { x = value; } } + public float Y { get { return y; } set { y = value; } } + public float Rotation { get { return rotation; } set { rotation = value; } } + + public PointAttachment (string name) + : base(name) { + } + + public void ComputeWorldPosition (Bone bone, out float ox, out float oy) { + bone.LocalToWorld(this.x, this.y, out ox, out oy); + } + + public float ComputeWorldRotation (Bone bone) { + float cos = MathUtils.CosDeg(rotation), sin = MathUtils.SinDeg(rotation); + float ix = cos * bone.a + sin * bone.b; + float iy = cos * bone.c + sin * bone.d; + return MathUtils.Atan2(iy, ix) * MathUtils.RadDeg; + } + + public override Attachment Copy () { + PointAttachment copy = new PointAttachment(this.Name); + copy.x = x; + copy.y = y; + copy.rotation = rotation; + return copy; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs.meta new file mode 100644 index 0000000..7e28782 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/PointAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4fdde4cc4df0952468946f4f913dcb36 +timeCreated: 1485603478 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs new file mode 100644 index 0000000..460f9b8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs @@ -0,0 +1,208 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// Attachment that displays a texture region. + public class RegionAttachment : Attachment, IHasRendererObject { + public const int BLX = 0; + public const int BLY = 1; + public const int ULX = 2; + public const int ULY = 3; + public const int URX = 4; + public const int URY = 5; + public const int BRX = 6; + public const int BRY = 7; + + internal float x, y, rotation, scaleX = 1, scaleY = 1, width, height; + internal float regionOffsetX, regionOffsetY, regionWidth, regionHeight, regionOriginalWidth, regionOriginalHeight; + internal float[] offset = new float[8], uvs = new float[8]; + internal float r = 1, g = 1, b = 1, a = 1; + + public float X { get { return x; } set { x = value; } } + public float Y { get { return y; } set { y = value; } } + public float Rotation { get { return rotation; } set { rotation = value; } } + public float ScaleX { get { return scaleX; } set { scaleX = value; } } + public float ScaleY { get { return scaleY; } set { scaleY = value; } } + public float Width { get { return width; } set { width = value; } } + public float Height { get { return height; } set { height = value; } } + + public float R { get { return r; } set { r = value; } } + public float G { get { return g; } set { g = value; } } + public float B { get { return b; } set { b = value; } } + public float A { get { return a; } set { a = value; } } + + public string Path { get; set; } + public object RendererObject { get; set; } + public float RegionOffsetX { get { return regionOffsetX; } set { regionOffsetX = value; } } + public float RegionOffsetY { get { return regionOffsetY; } set { regionOffsetY = value; } } // Pixels stripped from the bottom left, unrotated. + public float RegionWidth { get { return regionWidth; } set { regionWidth = value; } } + public float RegionHeight { get { return regionHeight; } set { regionHeight = value; } } // Unrotated, stripped size. + public float RegionOriginalWidth { get { return regionOriginalWidth; } set { regionOriginalWidth = value; } } + public float RegionOriginalHeight { get { return regionOriginalHeight; } set { regionOriginalHeight = value; } } // Unrotated, unstripped size. + + public float[] Offset { get { return offset; } } + public float[] UVs { get { return uvs; } } + + public RegionAttachment (string name) + : base(name) { + } + + public void UpdateOffset () { + float width = this.width; + float height = this.height; + float localX2 = width * 0.5f; + float localY2 = height * 0.5f; + float localX = -localX2; + float localY = -localY2; + if (regionOriginalWidth != 0) { // if (region != null) + localX += regionOffsetX / regionOriginalWidth * width; + localY += regionOffsetY / regionOriginalHeight * height; + localX2 -= (regionOriginalWidth - regionOffsetX - regionWidth) / regionOriginalWidth * width; + localY2 -= (regionOriginalHeight - regionOffsetY - regionHeight) / regionOriginalHeight * height; + } + float scaleX = this.scaleX; + float scaleY = this.scaleY; + localX *= scaleX; + localY *= scaleY; + localX2 *= scaleX; + localY2 *= scaleY; + float rotation = this.rotation; + float cos = MathUtils.CosDeg(rotation); + float sin = MathUtils.SinDeg(rotation); + float x = this.x; + float y = this.y; + float localXCos = localX * cos + x; + float localXSin = localX * sin; + float localYCos = localY * cos + y; + float localYSin = localY * sin; + float localX2Cos = localX2 * cos + x; + float localX2Sin = localX2 * sin; + float localY2Cos = localY2 * cos + y; + float localY2Sin = localY2 * sin; + float[] offset = this.offset; + offset[BLX] = localXCos - localYSin; + offset[BLY] = localYCos + localXSin; + offset[ULX] = localXCos - localY2Sin; + offset[ULY] = localY2Cos + localXSin; + offset[URX] = localX2Cos - localY2Sin; + offset[URY] = localY2Cos + localX2Sin; + offset[BRX] = localX2Cos - localYSin; + offset[BRY] = localYCos + localX2Sin; + } + + public void SetUVs (float u, float v, float u2, float v2, bool rotate) { + float[] uvs = this.uvs; + // UV values differ from RegionAttachment.java + if (rotate) { + uvs[URX] = u; + uvs[URY] = v2; + uvs[BRX] = u; + uvs[BRY] = v; + uvs[BLX] = u2; + uvs[BLY] = v; + uvs[ULX] = u2; + uvs[ULY] = v2; + } else { + uvs[ULX] = u; + uvs[ULY] = v2; + uvs[URX] = u; + uvs[URY] = v; + uvs[BRX] = u2; + uvs[BRY] = v; + uvs[BLX] = u2; + uvs[BLY] = v2; + } + } + + /// Transforms the attachment's four vertices to world coordinates. + /// The parent bone. + /// The output world vertices. Must have a length greater than or equal to offset + 8. + /// The worldVertices index to begin writing values. + /// The number of worldVertices entries between the value pairs written. + public void ComputeWorldVertices (Bone bone, float[] worldVertices, int offset, int stride = 2) { + float[] vertexOffset = this.offset; + float bwx = bone.worldX, bwy = bone.worldY; + float a = bone.a, b = bone.b, c = bone.c, d = bone.d; + float offsetX, offsetY; + + // Vertex order is different from RegionAttachment.java + offsetX = vertexOffset[BRX]; // 0 + offsetY = vertexOffset[BRY]; // 1 + worldVertices[offset] = offsetX * a + offsetY * b + bwx; // bl + worldVertices[offset + 1] = offsetX * c + offsetY * d + bwy; + offset += stride; + + offsetX = vertexOffset[BLX]; // 2 + offsetY = vertexOffset[BLY]; // 3 + worldVertices[offset] = offsetX * a + offsetY * b + bwx; // ul + worldVertices[offset + 1] = offsetX * c + offsetY * d + bwy; + offset += stride; + + offsetX = vertexOffset[ULX]; // 4 + offsetY = vertexOffset[ULY]; // 5 + worldVertices[offset] = offsetX * a + offsetY * b + bwx; // ur + worldVertices[offset + 1] = offsetX * c + offsetY * d + bwy; + offset += stride; + + offsetX = vertexOffset[URX]; // 6 + offsetY = vertexOffset[URY]; // 7 + worldVertices[offset] = offsetX * a + offsetY * b + bwx; // br + worldVertices[offset + 1] = offsetX * c + offsetY * d + bwy; + //offset += stride; + } + + public override Attachment Copy () { + RegionAttachment copy = new RegionAttachment(this.Name); + copy.RendererObject = RendererObject; + copy.regionOffsetX = regionOffsetX; + copy.regionOffsetY = regionOffsetY; + copy.regionWidth = regionWidth; + copy.regionHeight = regionHeight; + copy.regionOriginalWidth = regionOriginalWidth; + copy.regionOriginalHeight = regionOriginalHeight; + copy.Path = Path; + copy.x = x; + copy.y = y; + copy.scaleX = scaleX; + copy.scaleY = scaleY; + copy.rotation = rotation; + copy.width = width; + copy.height = height; + Array.Copy(uvs, 0, copy.uvs, 0, 8); + Array.Copy(offset, 0, copy.offset, 0, 8); + copy.r = r; + copy.g = g; + copy.b = b; + copy.a = a; + return copy; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs.meta new file mode 100644 index 0000000..0477ce4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/RegionAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 89cefdd024734a941952a05d2b5dff71 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs new file mode 100644 index 0000000..2c534de --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs @@ -0,0 +1,156 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// >An attachment with vertices that are transformed by one or more bones and can be deformed by a slot's + /// . + public abstract class VertexAttachment : Attachment { + static int nextID = 0; + static readonly Object nextIdLock = new Object(); + + internal readonly int id; + internal int[] bones; + internal float[] vertices; + internal int worldVerticesLength; + internal VertexAttachment deformAttachment; + + /// Gets a unique ID for this attachment. + public int Id { get { return id; } } + public int[] Bones { get { return bones; } set { bones = value; } } + public float[] Vertices { get { return vertices; } set { vertices = value; } } + public int WorldVerticesLength { get { return worldVerticesLength; } set { worldVerticesLength = value; } } + ///Deform keys for the deform attachment are also applied to this attachment. + /// May be null if no deform keys should be applied. + public VertexAttachment DeformAttachment { get { return deformAttachment; } set { deformAttachment = value; } } + + public VertexAttachment (string name) + : base(name) { + + deformAttachment = this; + lock (VertexAttachment.nextIdLock) { + id = (VertexAttachment.nextID++ & 65535) << 11; + } + } + + public void ComputeWorldVertices (Slot slot, float[] worldVertices) { + ComputeWorldVertices(slot, 0, worldVerticesLength, worldVertices, 0); + } + + /// + /// Transforms the attachment's local to world coordinates. If the slot's is + /// not empty, it is used to deform the vertices. + /// + /// See World transforms in the Spine + /// Runtimes Guide. + /// + /// The index of the first value to transform. Each vertex has 2 values, x and y. + /// The number of world vertex values to output. Must be less than or equal to - start. + /// The output world vertices. Must have a length greater than or equal to + . + /// The index to begin writing values. + /// The number of entries between the value pairs written. + public void ComputeWorldVertices (Slot slot, int start, int count, float[] worldVertices, int offset, int stride = 2) { + count = offset + (count >> 1) * stride; + Skeleton skeleton = slot.bone.skeleton; + var deformArray = slot.deform; + float[] vertices = this.vertices; + int[] bones = this.bones; + if (bones == null) { + if (deformArray.Count > 0) vertices = deformArray.Items; + Bone bone = slot.bone; + float x = bone.worldX, y = bone.worldY; + float a = bone.a, b = bone.b, c = bone.c, d = bone.d; + for (int vv = start, w = offset; w < count; vv += 2, w += stride) { + float vx = vertices[vv], vy = vertices[vv + 1]; + worldVertices[w] = vx * a + vy * b + x; + worldVertices[w + 1] = vx * c + vy * d + y; + } + return; + } + int v = 0, skip = 0; + for (int i = 0; i < start; i += 2) { + int n = bones[v]; + v += n + 1; + skip += n; + } + var skeletonBones = skeleton.bones.Items; + if (deformArray.Count == 0) { + for (int w = offset, b = skip * 3; w < count; w += stride) { + float wx = 0, wy = 0; + int n = bones[v++]; + n += v; + for (; v < n; v++, b += 3) { + Bone bone = skeletonBones[bones[v]]; + float vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } else { + float[] deform = deformArray.Items; + for (int w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) { + float wx = 0, wy = 0; + int n = bones[v++]; + n += v; + for (; v < n; v++, b += 3, f += 2) { + Bone bone = skeletonBones[bones[v]]; + float vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } + } + + ///Does not copy id (generated) or name (set on construction). + internal void CopyTo (VertexAttachment attachment) { + if (bones != null) { + attachment.bones = new int[bones.Length]; + Array.Copy(bones, 0, attachment.bones, 0, bones.Length); + } + else + attachment.bones = null; + + if (vertices != null) { + attachment.vertices = new float[vertices.Length]; + Array.Copy(vertices, 0, attachment.vertices, 0, vertices.Length); + } + else + attachment.vertices = null; + + attachment.worldVerticesLength = worldVerticesLength; + attachment.deformAttachment = deformAttachment; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs.meta new file mode 100644 index 0000000..8481a70 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Attachments/VertexAttachment.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8b40cfb462a8b774891e1604e5360d32 +timeCreated: 1466772712 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs new file mode 100644 index 0000000..0375403 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs @@ -0,0 +1,34 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine { + public enum BlendMode { + Normal, Additive, Multiply, Screen + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs.meta new file mode 100644 index 0000000..c60eb23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BlendMode.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b08ef68b8e39f40498ef24ef12cca281 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs new file mode 100644 index 0000000..5031e24 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs @@ -0,0 +1,366 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// + /// Stores a bone's current pose. + /// + /// A bone has a local transform which is used to compute its world transform. A bone also has an applied transform, which is a + /// local transform that can be applied to compute the world transform. The local transform and applied transform may differ if a + /// constraint or application code modifies the world transform after it was computed from the local transform. + /// + /// + public class Bone : IUpdatable { + static public bool yDown; + + internal BoneData data; + internal Skeleton skeleton; + internal Bone parent; + internal ExposedList children = new ExposedList(); + internal float x, y, rotation, scaleX, scaleY, shearX, shearY; + internal float ax, ay, arotation, ascaleX, ascaleY, ashearX, ashearY; + internal bool appliedValid; + + internal float a, b, worldX; + internal float c, d, worldY; + + internal bool sorted, active; + + public BoneData Data { get { return data; } } + public Skeleton Skeleton { get { return skeleton; } } + public Bone Parent { get { return parent; } } + public ExposedList Children { get { return children; } } + /// Returns false when the bone has not been computed because is true and the + /// active skin does not contain this bone. + public bool Active { get { return active; } } + /// The local X translation. + public float X { get { return x; } set { x = value; } } + /// The local Y translation. + public float Y { get { return y; } set { y = value; } } + /// The local rotation. + public float Rotation { get { return rotation; } set { rotation = value; } } + + /// The local scaleX. + public float ScaleX { get { return scaleX; } set { scaleX = value; } } + + /// The local scaleY. + public float ScaleY { get { return scaleY; } set { scaleY = value; } } + + /// The local shearX. + public float ShearX { get { return shearX; } set { shearX = value; } } + + /// The local shearY. + public float ShearY { get { return shearY; } set { shearY = value; } } + + /// The rotation, as calculated by any constraints. + public float AppliedRotation { get { return arotation; } set { arotation = value; } } + + /// The applied local x translation. + public float AX { get { return ax; } set { ax = value; } } + + /// The applied local y translation. + public float AY { get { return ay; } set { ay = value; } } + + /// The applied local scaleX. + public float AScaleX { get { return ascaleX; } set { ascaleX = value; } } + + /// The applied local scaleY. + public float AScaleY { get { return ascaleY; } set { ascaleY = value; } } + + /// The applied local shearX. + public float AShearX { get { return ashearX; } set { ashearX = value; } } + + /// The applied local shearY. + public float AShearY { get { return ashearY; } set { ashearY = value; } } + + public float A { get { return a; } } + public float B { get { return b; } } + public float C { get { return c; } } + public float D { get { return d; } } + + public float WorldX { get { return worldX; } } + public float WorldY { get { return worldY; } } + public float WorldRotationX { get { return MathUtils.Atan2(c, a) * MathUtils.RadDeg; } } + public float WorldRotationY { get { return MathUtils.Atan2(d, b) * MathUtils.RadDeg; } } + + /// Returns the magnitide (always positive) of the world scale X. + public float WorldScaleX { get { return (float)Math.Sqrt(a * a + c * c); } } + /// Returns the magnitide (always positive) of the world scale Y. + public float WorldScaleY { get { return (float)Math.Sqrt(b * b + d * d); } } + + /// May be null. + public Bone (BoneData data, Skeleton skeleton, Bone parent) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + this.data = data; + this.skeleton = skeleton; + this.parent = parent; + SetToSetupPose(); + } + + /// Same as . This method exists for Bone to implement . + public void Update () { + UpdateWorldTransform(x, y, rotation, scaleX, scaleY, shearX, shearY); + } + + /// Computes the world transform using the parent bone and this bone's local transform. + public void UpdateWorldTransform () { + UpdateWorldTransform(x, y, rotation, scaleX, scaleY, shearX, shearY); + } + + /// Computes the world transform using the parent bone and the specified local transform. + public void UpdateWorldTransform (float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY) { + ax = x; + ay = y; + arotation = rotation; + ascaleX = scaleX; + ascaleY = scaleY; + ashearX = shearX; + ashearY = shearY; + appliedValid = true; + Skeleton skeleton = this.skeleton; + + Bone parent = this.parent; + if (parent == null) { // Root bone. + float rotationY = rotation + 90 + shearY, sx = skeleton.ScaleX, sy = skeleton.ScaleY; + a = MathUtils.CosDeg(rotation + shearX) * scaleX * sx; + b = MathUtils.CosDeg(rotationY) * scaleY * sx; + c = MathUtils.SinDeg(rotation + shearX) * scaleX * sy; + d = MathUtils.SinDeg(rotationY) * scaleY * sy; + worldX = x * sx + skeleton.x; + worldY = y * sy + skeleton.y; + return; + } + + float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; + worldX = pa * x + pb * y + parent.worldX; + worldY = pc * x + pd * y + parent.worldY; + + switch (data.transformMode) { + case TransformMode.Normal: { + float rotationY = rotation + 90 + shearY; + float la = MathUtils.CosDeg(rotation + shearX) * scaleX; + float lb = MathUtils.CosDeg(rotationY) * scaleY; + float lc = MathUtils.SinDeg(rotation + shearX) * scaleX; + float ld = MathUtils.SinDeg(rotationY) * scaleY; + a = pa * la + pb * lc; + b = pa * lb + pb * ld; + c = pc * la + pd * lc; + d = pc * lb + pd * ld; + return; + } + case TransformMode.OnlyTranslation: { + float rotationY = rotation + 90 + shearY; + a = MathUtils.CosDeg(rotation + shearX) * scaleX; + b = MathUtils.CosDeg(rotationY) * scaleY; + c = MathUtils.SinDeg(rotation + shearX) * scaleX; + d = MathUtils.SinDeg(rotationY) * scaleY; + break; + } + case TransformMode.NoRotationOrReflection: { + float s = pa * pa + pc * pc, prx; + if (s > 0.0001f) { + s = Math.Abs(pa * pd - pb * pc) / s; + pa /= skeleton.ScaleX; + pc /= skeleton.ScaleY; + pb = pc * s; + pd = pa * s; + prx = MathUtils.Atan2(pc, pa) * MathUtils.RadDeg; + } else { + pa = 0; + pc = 0; + prx = 90 - MathUtils.Atan2(pd, pb) * MathUtils.RadDeg; + } + float rx = rotation + shearX - prx; + float ry = rotation + shearY - prx + 90; + float la = MathUtils.CosDeg(rx) * scaleX; + float lb = MathUtils.CosDeg(ry) * scaleY; + float lc = MathUtils.SinDeg(rx) * scaleX; + float ld = MathUtils.SinDeg(ry) * scaleY; + a = pa * la - pb * lc; + b = pa * lb - pb * ld; + c = pc * la + pd * lc; + d = pc * lb + pd * ld; + break; + } + case TransformMode.NoScale: + case TransformMode.NoScaleOrReflection: { + float cos = MathUtils.CosDeg(rotation), sin = MathUtils.SinDeg(rotation); + float za = (pa * cos + pb * sin) / skeleton.ScaleX; + float zc = (pc * cos + pd * sin) / skeleton.ScaleY; + float s = (float)Math.Sqrt(za * za + zc * zc); + if (s > 0.00001f) s = 1 / s; + za *= s; + zc *= s; + s = (float)Math.Sqrt(za * za + zc * zc); + if (data.transformMode == TransformMode.NoScale + && (pa * pd - pb * pc < 0) != (skeleton.ScaleX < 0 != skeleton.ScaleY < 0)) s = -s; + + float r = MathUtils.PI / 2 + MathUtils.Atan2(zc, za); + float zb = MathUtils.Cos(r) * s; + float zd = MathUtils.Sin(r) * s; + float la = MathUtils.CosDeg(shearX) * scaleX; + float lb = MathUtils.CosDeg(90 + shearY) * scaleY; + float lc = MathUtils.SinDeg(shearX) * scaleX; + float ld = MathUtils.SinDeg(90 + shearY) * scaleY; + a = za * la + zb * lc; + b = za * lb + zb * ld; + c = zc * la + zd * lc; + d = zc * lb + zd * ld; + break; + } + } + + a *= skeleton.ScaleX; + b *= skeleton.ScaleX; + c *= skeleton.ScaleY; + d *= skeleton.ScaleY; + } + + public void SetToSetupPose () { + BoneData data = this.data; + x = data.x; + y = data.y; + rotation = data.rotation; + scaleX = data.scaleX; + scaleY = data.scaleY; + shearX = data.shearX; + shearY = data.shearY; + } + + /// + /// Computes the individual applied transform values from the world transform. This can be useful to perform processing using + /// the applied transform after the world transform has been modified directly (eg, by a constraint).. + /// + /// Some information is ambiguous in the world transform, such as -1,-1 scale versus 180 rotation. + /// + internal void UpdateAppliedTransform () { + appliedValid = true; + Bone parent = this.parent; + if (parent == null) { + ax = worldX; + ay = worldY; + arotation = MathUtils.Atan2(c, a) * MathUtils.RadDeg; + ascaleX = (float)Math.Sqrt(a * a + c * c); + ascaleY = (float)Math.Sqrt(b * b + d * d); + ashearX = 0; + ashearY = MathUtils.Atan2(a * b + c * d, a * d - b * c) * MathUtils.RadDeg; + return; + } + float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; + float pid = 1 / (pa * pd - pb * pc); + float dx = worldX - parent.worldX, dy = worldY - parent.worldY; + ax = (dx * pd * pid - dy * pb * pid); + ay = (dy * pa * pid - dx * pc * pid); + float ia = pid * pd; + float id = pid * pa; + float ib = pid * pb; + float ic = pid * pc; + float ra = ia * a - ib * c; + float rb = ia * b - ib * d; + float rc = id * c - ic * a; + float rd = id * d - ic * b; + ashearX = 0; + ascaleX = (float)Math.Sqrt(ra * ra + rc * rc); + if (ascaleX > 0.0001f) { + float det = ra * rd - rb * rc; + ascaleY = det / ascaleX; + ashearY = MathUtils.Atan2(ra * rb + rc * rd, det) * MathUtils.RadDeg; + arotation = MathUtils.Atan2(rc, ra) * MathUtils.RadDeg; + } else { + ascaleX = 0; + ascaleY = (float)Math.Sqrt(rb * rb + rd * rd); + ashearY = 0; + arotation = 90 - MathUtils.Atan2(rd, rb) * MathUtils.RadDeg; + } + } + + public void WorldToLocal (float worldX, float worldY, out float localX, out float localY) { + float a = this.a, b = this.b, c = this.c, d = this.d; + float invDet = 1 / (a * d - b * c); + float x = worldX - this.worldX, y = worldY - this.worldY; + localX = (x * d * invDet - y * b * invDet); + localY = (y * a * invDet - x * c * invDet); + } + + public void LocalToWorld (float localX, float localY, out float worldX, out float worldY) { + worldX = localX * a + localY * b + this.worldX; + worldY = localX * c + localY * d + this.worldY; + } + + public float WorldToLocalRotationX { + get { + Bone parent = this.parent; + if (parent == null) return arotation; + float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, a = this.a, c = this.c; + return MathUtils.Atan2(pa * c - pc * a, pd * a - pb * c) * MathUtils.RadDeg; + } + } + + public float WorldToLocalRotationY { + get { + Bone parent = this.parent; + if (parent == null) return arotation; + float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, b = this.b, d = this.d; + return MathUtils.Atan2(pa * d - pc * b, pd * b - pb * d) * MathUtils.RadDeg; + } + } + + public float WorldToLocalRotation (float worldRotation) { + float sin = MathUtils.SinDeg(worldRotation), cos = MathUtils.CosDeg(worldRotation); + return MathUtils.Atan2(a * sin - c * cos, d * cos - b * sin) * MathUtils.RadDeg + rotation - shearX; + } + + public float LocalToWorldRotation (float localRotation) { + localRotation -= rotation - shearX; + float sin = MathUtils.SinDeg(localRotation), cos = MathUtils.CosDeg(localRotation); + return MathUtils.Atan2(cos * c + sin * d, cos * a + sin * b) * MathUtils.RadDeg; + } + + /// + /// Rotates the world transform the specified amount and sets isAppliedValid to false. + /// + /// Degrees. + public void RotateWorld (float degrees) { + float a = this.a, b = this.b, c = this.c, d = this.d; + float cos = MathUtils.CosDeg(degrees), sin = MathUtils.SinDeg(degrees); + this.a = cos * a - sin * c; + this.b = cos * b - sin * d; + this.c = sin * a + cos * c; + this.d = sin * b + cos * d; + appliedValid = false; + } + + override public string ToString () { + return data.name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs.meta new file mode 100644 index 0000000..687d6b9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Bone.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ed00e3a4b386a964fb0f1c7ffd5544e5 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs new file mode 100644 index 0000000..4cb4664 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs @@ -0,0 +1,105 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class BoneData { + internal int index; + internal string name; + internal BoneData parent; + internal float length; + internal float x, y, rotation, scaleX = 1, scaleY = 1, shearX, shearY; + internal TransformMode transformMode = TransformMode.Normal; + internal bool skinRequired; + + /// The index of the bone in Skeleton.Bones + public int Index { get { return index; } } + + /// The name of the bone, which is unique across all bones in the skeleton. + public string Name { get { return name; } } + + /// May be null. + public BoneData Parent { get { return parent; } } + + public float Length { get { return length; } set { length = value; } } + + /// Local X translation. + public float X { get { return x; } set { x = value; } } + + /// Local Y translation. + public float Y { get { return y; } set { y = value; } } + + /// Local rotation. + public float Rotation { get { return rotation; } set { rotation = value; } } + + /// Local scaleX. + public float ScaleX { get { return scaleX; } set { scaleX = value; } } + + /// Local scaleY. + public float ScaleY { get { return scaleY; } set { scaleY = value; } } + + /// Local shearX. + public float ShearX { get { return shearX; } set { shearX = value; } } + + /// Local shearY. + public float ShearY { get { return shearY; } set { shearY = value; } } + + /// The transform mode for how parent world transforms affect this bone. + public TransformMode TransformMode { get { return transformMode; } set { transformMode = value; } } + + ///When true, only updates this bone if the contains this + /// bone. + /// + public bool SkinRequired { get { return skinRequired; } set { skinRequired = value; } } + + /// May be null. + public BoneData (int index, string name, BoneData parent) { + if (index < 0) throw new ArgumentException("index must be >= 0", "index"); + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + this.index = index; + this.name = name; + this.parent = parent; + } + + override public string ToString () { + return name; + } + } + + [Flags] + public enum TransformMode { + //0000 0 Flip Scale Rotation + Normal = 0, // 0000 + OnlyTranslation = 7, // 0111 + NoRotationOrReflection = 1, // 0001 + NoScale = 2, // 0010 + NoScaleOrReflection = 6, // 0110 + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs.meta new file mode 100644 index 0000000..006e3ec --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/BoneData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2cf831005966832449a5de742752e578 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections.meta new file mode 100644 index 0000000..86d3d73 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b41ddd57048a62b41951dbbfd453ab98 +folderAsset: yes +timeCreated: 1565181882 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs new file mode 100644 index 0000000..6af4cc4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs @@ -0,0 +1,633 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +/****************************************************************************** + * Thanks to Travis Parks + * https://github.com/jehugaleahsa/truncon.collections.OrderedDictionary + *****************************************************************************/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; + +namespace Spine.Collections +{ + /// + /// Represents a dictionary that tracks the order that items were added. + /// + /// The type of the dictionary keys. + /// The type of the dictionary values. + /// + /// This dictionary makes it possible to get the index of a key and a key based on an index. + /// It can be costly to find the index of a key because it must be searched for linearly. + /// It can be costly to insert a key/value pair because other key's indexes must be adjusted. + /// It can be costly to remove a key/value pair because other keys' indexes must be adjusted. + /// + [DebuggerDisplay("Count = {Count}")] + [DebuggerTypeProxy(typeof(OrderedDictionaryDebugView<,>))] + public sealed class OrderedDictionary : IDictionary, IList> + { + private readonly Dictionary dictionary; + private readonly List keys; + private readonly List values; + private int version; + + private const string CollectionModifiedMessage = "Collection was modified; enumeration operation may not execute."; + private const string EditReadOnlyListMessage = "An attempt was made to edit a read-only list."; + private const string IndexOutOfRangeMessage = "The index is negative or outside the bounds of the collection."; + + /// + /// Initializes a new instance of an OrderedDictionary. + /// + public OrderedDictionary () + : this(0, null) { + } + + /// + /// Initializes a new instance of an OrderedDictionary. + /// + /// The initial capacity of the dictionary. + /// The capacity is less than zero. + public OrderedDictionary (int capacity) + : this(capacity, null) { + } + + /// + /// Initializes a new instance of an OrderedDictionary. + /// + /// The equality comparer to use to compare keys. + public OrderedDictionary (IEqualityComparer comparer) + : this(0, comparer) { + } + + /// + /// Initializes a new instance of an OrderedDictionary. + /// + /// The initial capacity of the dictionary. + /// The equality comparer to use to compare keys. + public OrderedDictionary (int capacity, IEqualityComparer comparer) { + dictionary = new Dictionary(capacity, comparer ?? EqualityComparer.Default); + keys = new List(capacity); + values = new List(capacity); + } + + /// + /// Gets the equality comparer used to compare keys. + /// + public IEqualityComparer Comparer { + get { + return dictionary.Comparer; + } + } + + /// + /// Adds the given key/value pair to the dictionary. + /// + /// The key to add to the dictionary. + /// The value to associated with the key. + /// The given key already exists in the dictionary. + /// The key is null. + public void Add (TKey key, TValue value) { + dictionary.Add(key, values.Count); + keys.Add(key); + values.Add(value); + ++version; + } + + /// + /// Inserts the given key/value pair at the specified index. + /// + /// The index to insert the key/value pair. + /// The key to insert. + /// The value to insert. + /// The given key already exists in the dictionary. + /// The key is null. + /// The index is negative -or- larger than the size of the dictionary. + public void Insert (int index, TKey key, TValue value) { + if (index < 0 || index > values.Count) { + throw new ArgumentOutOfRangeException("index", index, IndexOutOfRangeMessage); + } + dictionary.Add(key, index); + for (int keyIndex = index; keyIndex != keys.Count; ++keyIndex) { + var otherKey = keys[keyIndex]; + dictionary[otherKey] += 1; + } + keys.Insert(index, key); + values.Insert(index, value); + ++version; + } + + /// + /// Determines whether the given key exists in the dictionary. + /// + /// The key to look for. + /// True if the key exists in the dictionary; otherwise, false. + /// The key is null. + public bool ContainsKey (TKey key) { + return dictionary.ContainsKey(key); + } + + /// + /// Gets the key at the given index. + /// + /// The index of the key to get. + /// The key at the given index. + /// The index is negative -or- larger than the number of keys. + public TKey GetKey (int index) { + return keys[index]; + } + + /// + /// Gets the index of the given key. + /// + /// The key to get the index of. + /// The index of the key in the dictionary -or- -1 if the key is not found. + /// The operation runs in O(n). + public int IndexOf (TKey key) { + int index; + if (dictionary.TryGetValue(key, out index)) { + return index; + } + return -1; + } + + /// + /// Gets the keys in the dictionary in the order they were added. + /// + public KeyCollection Keys { + get { + return new KeyCollection(this.dictionary); + } + } + + /// + /// Removes the key/value pair with the given key from the dictionary. + /// + /// The key of the pair to remove. + /// True if the key was found and the pair removed; otherwise, false. + /// The key is null. + public bool Remove (TKey key) { + int index; + if (dictionary.TryGetValue(key, out index)) { + RemoveAt(index); + return true; + } + return false; + } + + /// + /// Removes the key/value pair at the given index. + /// + /// The index of the key/value pair to remove. + /// The index is negative -or- larger than the size of the dictionary. + public void RemoveAt (int index) { + var key = keys[index]; + for (int keyIndex = index + 1; keyIndex < keys.Count; ++keyIndex) { + var otherKey = keys[keyIndex]; + dictionary[otherKey] -= 1; + } + dictionary.Remove(key); + keys.RemoveAt(index); + values.RemoveAt(index); + ++version; + } + + /// + /// Tries to get the value associated with the given key. If the key is not found, + /// default(TValue) value is stored in the value. + /// + /// The key to get the value for. + /// The value used to hold the results. + /// True if the key was found; otherwise, false. + /// The key is null. + public bool TryGetValue (TKey key, out TValue value) { + int index; + if (dictionary.TryGetValue(key, out index)) { + value = values[index]; + return true; + } + value = default(TValue); + return false; + } + + /// + /// Gets the values in the dictionary. + /// + public ValueCollection Values { + get { + return new ValueCollection(values); + } + } + + /// + /// Gets or sets the value at the given index. + /// + /// The index of the value to get. + /// The value at the given index. + /// The index is negative -or- beyond the length of the dictionary. + public TValue this[int index] { + get { + return values[index]; + } + + set { + values[index] = value; + } + } + + /// + /// Gets or sets the value associated with the given key. + /// + /// The key to get the associated value by or to associate with the value. + /// The value associated with the given key. + /// The key is null. + /// The key is not in the dictionary. + public TValue this[TKey key] { + get { + return values[dictionary[key]]; + } + set { + int index; + if (dictionary.TryGetValue(key, out index)) { + keys[index] = key; + values[index] = value; + } + else { + Add(key, value); + } + } + } + + /// + /// Removes all key/value pairs from the dictionary. + /// + public void Clear () { + dictionary.Clear(); + keys.Clear(); + values.Clear(); + ++version; + } + + /// + /// Gets the number of key/value pairs in the dictionary. + /// + public int Count { + get { + return dictionary.Count; + } + } + + /// + /// Gets the key/value pairs in the dictionary in the order they were added. + /// + /// An enumerator over the key/value pairs in the dictionary. + public IEnumerator> GetEnumerator () { + int startVersion = version; + for (int index = 0; index != keys.Count; ++index) { + var key = keys[index]; + var value = values[index]; + yield return new KeyValuePair(key, value); + if (version != startVersion) { + throw new InvalidOperationException(CollectionModifiedMessage); + } + } + } + + int IList>.IndexOf (KeyValuePair item) { + int index; + if (dictionary.TryGetValue(item.Key, out index) && Equals(values[index], item.Value)) { + return index; + } + return -1; + } + + void IList>.Insert (int index, KeyValuePair item) { + Insert(index, item.Key, item.Value); + } + + KeyValuePair IList>.this[int index] { + get { + TKey key = keys[index]; + TValue value = values[index]; + return new KeyValuePair(key, value); + } + set { + TKey key = keys[index]; + if (dictionary.Comparer.Equals(key, value.Key)) { + dictionary[value.Key] = index; + } + else { + dictionary.Add(value.Key, index); // will throw if key already exists + dictionary.Remove(key); + } + keys[index] = value.Key; + values[index] = value.Value; + } + } + + ICollection IDictionary.Keys { + get { + return Keys; + } + } + + ICollection IDictionary.Values { + get { + return Values; + } + } + + void ICollection>.Add (KeyValuePair item) { + Add(item.Key, item.Value); + } + + bool ICollection>.Contains (KeyValuePair item) { + int index; + if (dictionary.TryGetValue(item.Key, out index) && Equals(values[index], item.Value)) { + return true; + } + return false; + } + + void ICollection>.CopyTo (KeyValuePair[] array, int arrayIndex) { + if (array == null) { + throw new ArgumentNullException("array"); + } + if (arrayIndex < 0) { + throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, IndexOutOfRangeMessage); + } + for (int index = 0; index != keys.Count && arrayIndex < array.Length; ++index, ++arrayIndex) { + var key = keys[index]; + var value = values[index]; + array[arrayIndex] = new KeyValuePair(key, value); + } + } + + bool ICollection>.IsReadOnly { + get { + return false; + } + } + + bool ICollection>.Remove (KeyValuePair item) { + ICollection> self = this; + if (self.Contains(item)) { + return Remove(item.Key); + } + return false; + } + + IEnumerator IEnumerable.GetEnumerator () { + return GetEnumerator(); + } + + /// + /// Wraps the keys in an OrderDictionary. + /// + public sealed class KeyCollection : ICollection + { + private readonly Dictionary dictionary; + + /// + /// Initializes a new instance of a KeyCollection. + /// + /// The OrderedDictionary whose keys to wrap. + /// The dictionary is null. + internal KeyCollection (Dictionary dictionary) { + this.dictionary = dictionary; + } + + /// + /// Copies the keys from the OrderedDictionary to the given array, starting at the given index. + /// + /// The array to copy the keys to. + /// The index into the array to start copying the keys. + /// The array is null. + /// The arrayIndex is negative. + /// The array, starting at the given index, is not large enough to contain all the keys. + public void CopyTo (TKey[] array, int arrayIndex) { + dictionary.Keys.CopyTo(array, arrayIndex); + } + + /// + /// Gets the number of keys in the OrderedDictionary. + /// + public int Count { + get { + return dictionary.Count; + } + } + + /// + /// Gets an enumerator over the keys in the OrderedDictionary. + /// + /// The enumerator. + public IEnumerator GetEnumerator () { + return dictionary.Keys.GetEnumerator(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.Contains (TKey item) { + return dictionary.ContainsKey(item); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + void ICollection.Add (TKey item) { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + void ICollection.Clear () { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.IsReadOnly { + get { + return true; + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.Remove (TKey item) { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + IEnumerator IEnumerable.GetEnumerator () { + return GetEnumerator(); + } + } + + /// + /// Wraps the keys in an OrderDictionary. + /// + public sealed class ValueCollection : ICollection + { + private readonly List values; + + /// + /// Initializes a new instance of a ValueCollection. + /// + /// The OrderedDictionary whose keys to wrap. + /// The dictionary is null. + internal ValueCollection (List values) { + this.values = values; + } + + /// + /// Copies the values from the OrderedDictionary to the given array, starting at the given index. + /// + /// The array to copy the values to. + /// The index into the array to start copying the values. + /// The array is null. + /// The arrayIndex is negative. + /// The array, starting at the given index, is not large enough to contain all the values. + public void CopyTo (TValue[] array, int arrayIndex) { + values.CopyTo(array, arrayIndex); + } + + /// + /// Gets the number of values in the OrderedDictionary. + /// + public int Count { + get { + return values.Count; + } + } + + /// + /// Gets an enumerator over the values in the OrderedDictionary. + /// + /// The enumerator. + public IEnumerator GetEnumerator () { + return values.GetEnumerator(); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.Contains (TValue item) { + return values.Contains(item); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + void ICollection.Add (TValue item) { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + void ICollection.Clear () { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.IsReadOnly { + get { + return true; + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + bool ICollection.Remove (TValue item) { + throw new NotSupportedException(EditReadOnlyListMessage); + } + + IEnumerator IEnumerable.GetEnumerator () { + return GetEnumerator(); + } + } + } + + internal class OrderedDictionaryDebugView + { + private readonly OrderedDictionary dictionary; + + public OrderedDictionaryDebugView (OrderedDictionary dictionary) { + this.dictionary = dictionary; + } + + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public KeyValuePair[] Items { + get { + return dictionary.ToArray(); + } + } + } + + /// + /// Provides extensions methods for constructing instances of . + /// + public static class CollectionExtensions + { + #region ToOrderedDictionary + + /// + /// Creates a new OrderedDictionary from the given collection, using the key selector to extract the key. + /// + /// The type of the items in the collection. + /// The type of the key. + /// The items to created the OrderedDictionary from. + /// A delegate that can extract a key from an item in the collection. + /// An OrderedDictionary mapping the extracted keys to their values. + public static OrderedDictionary ToOrderedDictionary (this IEnumerable source, Func keySelector) { + return ToOrderedDictionary(source, keySelector, null); + } + + /// + /// Creates a new OrderedDictionary from the given collection, using the key selector to extract the key. + /// The key comparer is passed to the OrderedDictionary for comparing the extracted keys. + /// + /// The type of the items in the collection. + /// The type of the key. + /// The items to created the OrderedDictionary from. + /// A delegate that can extract a key from an item in the collection. + /// The key equality comparer to use to compare keys in the dictionary. + /// An OrderedDictionary mapping the extracted keys to their values. + public static OrderedDictionary ToOrderedDictionary ( + this IEnumerable source, + Func keySelector, + IEqualityComparer comparer) { + if (source == null) { + throw new ArgumentNullException("source"); + } + if (keySelector == null) { + throw new ArgumentNullException("keySelector"); + } + var dictionary = new OrderedDictionary(comparer); + foreach (TSource item in source) { + TKey key = keySelector(item); + dictionary.Add(key, item); + } + return dictionary; + } + + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs.meta new file mode 100644 index 0000000..97e097a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Collections/OrderedDictionary.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ca4b738078ed756469d5d97bcca93e6f +timeCreated: 1636570216 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs new file mode 100644 index 0000000..d4f9503 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs @@ -0,0 +1,62 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine +{ + /// The base class for all constraint datas. + public abstract class ConstraintData { + internal readonly string name; + internal int order; + internal bool skinRequired; + + public ConstraintData (string name) { + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + this.name = name; + } + + /// The constraint's name, which is unique across all constraints in the skeleton of the same type. + public string Name { get { return name; } } + + ///The ordinal of this constraint for the order a skeleton's constraints will be applied by + /// . + public int Order { get { return order; } set { order = value; } } + + ///When true, only updates this constraint if the contains + /// this constraint. + /// + public bool SkinRequired { get { return skinRequired; } set { skinRequired = value; } } + + override public string ToString () { + return name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs.meta new file mode 100644 index 0000000..961c6fd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ConstraintData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 55d3827079aca3a4687535c3ede7ec5f +timeCreated: 1636570216 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs new file mode 100644 index 0000000..72c3b70 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs @@ -0,0 +1,64 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// Stores the current pose values for an Event. + public class Event { + internal readonly EventData data; + internal readonly float time; + internal int intValue; + internal float floatValue; + internal string stringValue; + internal float volume; + internal float balance; + + public EventData Data { get { return data; } } + /// The animation time this event was keyed. + public float Time { get { return time; } } + + public int Int { get { return intValue; } set { intValue = value; } } + public float Float { get { return floatValue; } set { floatValue = value; } } + public string String { get { return stringValue; } set { stringValue = value; } } + + public float Volume { get { return volume; } set { volume = value; } } + public float Balance { get { return balance; } set { balance = value; } } + + public Event (float time, EventData data) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + this.time = time; + this.data = data; + } + + override public string ToString () { + return this.data.Name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs.meta new file mode 100644 index 0000000..dbdbc59 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Event.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dec0d9d780605944eb4514125ab6350b +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs new file mode 100644 index 0000000..39094f4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs @@ -0,0 +1,56 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// Stores the setup pose values for an Event. + public class EventData { + internal string name; + + /// The name of the event, which is unique across all events in the skeleton. + public string Name { get { return name; } } + public int Int { get; set; } + public float Float { get; set; } + public string @String { get; set; } + + public string AudioPath { get; set; } + public float Volume { get; set; } + public float Balance { get; set; } + + public EventData (string name) { + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + this.name = name; + } + + override public string ToString () { + return Name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs.meta new file mode 100644 index 0000000..941b359 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/EventData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 37bbfb9fb268a644ba75052961a42b81 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs new file mode 100644 index 0000000..7d0b697 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs @@ -0,0 +1,641 @@ +// +// System.Collections.Generic.List +// +// Authors: +// Ben Maurer (bmaurer@ximian.com) +// Martin Baulig (martin@ximian.com) +// Carlos Alberto Cortez (calberto.cortez@gmail.com) +// David Waite (mass@akuma.org) +// +// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) +// Copyright (C) 2005 David Waite +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Spine { + [DebuggerDisplay("Count={Count}")] + public class ExposedList : IEnumerable { + public T[] Items; + public int Count; + private const int DefaultCapacity = 4; + private static readonly T[] EmptyArray = new T[0]; + private int version; + + public ExposedList () { + Items = EmptyArray; + } + + public ExposedList (IEnumerable collection) { + CheckCollection(collection); + + // initialize to needed size (if determinable) + ICollection c = collection as ICollection; + if (c == null) { + Items = EmptyArray; + AddEnumerable(collection); + } else { + Items = new T[c.Count]; + AddCollection(c); + } + } + + public ExposedList (int capacity) { + if (capacity < 0) + throw new ArgumentOutOfRangeException("capacity"); + Items = new T[capacity]; + } + + internal ExposedList (T[] data, int size) { + Items = data; + Count = size; + } + + public void Add (T item) { + // If we check to see if we need to grow before trying to grow + // we can speed things up by 25% + if (Count == Items.Length) + GrowIfNeeded(1); + Items[Count++] = item; + version++; + } + + public void GrowIfNeeded (int addedCount) { + int minimumSize = Count + addedCount; + if (minimumSize > Items.Length) + Capacity = Math.Max(Math.Max(Capacity * 2, DefaultCapacity), minimumSize); + } + + public ExposedList Resize (int newSize) { + int itemsLength = Items.Length; + var oldItems = Items; + if (newSize > itemsLength) { + Array.Resize(ref Items, newSize); +// var newItems = new T[newSize]; +// Array.Copy(oldItems, newItems, Count); +// Items = newItems; + } else if (newSize < itemsLength) { + // Allow nulling of T reference type to allow GC. + for (int i = newSize; i < itemsLength; i++) + oldItems[i] = default(T); + } + Count = newSize; + return this; + } + + public void EnsureCapacity (int min) { + if (Items.Length < min) { + int newCapacity = Items.Length == 0 ? DefaultCapacity : Items.Length * 2; + //if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; + if (newCapacity < min) newCapacity = min; + Capacity = newCapacity; + } + } + + private void CheckRange (int index, int count) { + if (index < 0) + throw new ArgumentOutOfRangeException("index"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count"); + + if ((uint)index + (uint)count > (uint)Count) + throw new ArgumentException("index and count exceed length of list"); + } + + private void AddCollection (ICollection collection) { + int collectionCount = collection.Count; + if (collectionCount == 0) + return; + + GrowIfNeeded(collectionCount); + collection.CopyTo(Items, Count); + Count += collectionCount; + } + + private void AddEnumerable (IEnumerable enumerable) { + foreach (T t in enumerable) { + Add(t); + } + } + + // Additional overload provided because ExposedList only implements IEnumerable, + // leading to sub-optimal behavior: It grows multiple times as it assumes not + // to know the final size ahead of insertion. + public void AddRange (ExposedList list) { + CheckCollection(list); + + int collectionCount = list.Count; + if (collectionCount == 0) + return; + + GrowIfNeeded(collectionCount); + list.CopyTo(Items, Count); + Count += collectionCount; + + version++; + } + + public void AddRange (IEnumerable collection) { + CheckCollection(collection); + + ICollection c = collection as ICollection; + if (c != null) + AddCollection(c); + else + AddEnumerable(collection); + version++; + } + + public int BinarySearch (T item) { + return Array.BinarySearch(Items, 0, Count, item); + } + + public int BinarySearch (T item, IComparer comparer) { + return Array.BinarySearch(Items, 0, Count, item, comparer); + } + + public int BinarySearch (int index, int count, T item, IComparer comparer) { + CheckRange(index, count); + return Array.BinarySearch(Items, index, count, item, comparer); + } + + public void Clear (bool clearArray = true) { + if (clearArray) + Array.Clear(Items, 0, Items.Length); + + Count = 0; + version++; + } + + public bool Contains (T item) { + return Array.IndexOf(Items, item, 0, Count) != -1; + } + + public ExposedList ConvertAll (Converter converter) { + if (converter == null) + throw new ArgumentNullException("converter"); + ExposedList u = new ExposedList(Count); + for (int i = 0; i < Count; i++) + u.Items[i] = converter(Items[i]); + + u.Count = Count; + return u; + } + + public void CopyTo (T[] array) { + Array.Copy(Items, 0, array, 0, Count); + } + + public void CopyTo (T[] array, int arrayIndex) { + Array.Copy(Items, 0, array, arrayIndex, Count); + } + + public void CopyTo (int index, T[] array, int arrayIndex, int count) { + CheckRange(index, count); + Array.Copy(Items, index, array, arrayIndex, count); + } + + + + public bool Exists (Predicate match) { + CheckMatch(match); + return GetIndex(0, Count, match) != -1; + } + + public T Find (Predicate match) { + CheckMatch(match); + int i = GetIndex(0, Count, match); + return (i != -1) ? Items[i] : default(T); + } + + private static void CheckMatch (Predicate match) { + if (match == null) + throw new ArgumentNullException("match"); + } + + public ExposedList FindAll (Predicate match) { + CheckMatch(match); + return FindAllList(match); + } + + private ExposedList FindAllList (Predicate match) { + ExposedList results = new ExposedList(); + for (int i = 0; i < Count; i++) + if (match(Items[i])) + results.Add(Items[i]); + + return results; + } + + public int FindIndex (Predicate match) { + CheckMatch(match); + return GetIndex(0, Count, match); + } + + public int FindIndex (int startIndex, Predicate match) { + CheckMatch(match); + CheckIndex(startIndex); + return GetIndex(startIndex, Count - startIndex, match); + } + + public int FindIndex (int startIndex, int count, Predicate match) { + CheckMatch(match); + CheckRange(startIndex, count); + return GetIndex(startIndex, count, match); + } + + private int GetIndex (int startIndex, int count, Predicate match) { + int end = startIndex + count; + for (int i = startIndex; i < end; i++) + if (match(Items[i])) + return i; + + return -1; + } + + public T FindLast (Predicate match) { + CheckMatch(match); + int i = GetLastIndex(0, Count, match); + return i == -1 ? default(T) : Items[i]; + } + + public int FindLastIndex (Predicate match) { + CheckMatch(match); + return GetLastIndex(0, Count, match); + } + + public int FindLastIndex (int startIndex, Predicate match) { + CheckMatch(match); + CheckIndex(startIndex); + return GetLastIndex(0, startIndex + 1, match); + } + + public int FindLastIndex (int startIndex, int count, Predicate match) { + CheckMatch(match); + int start = startIndex - count + 1; + CheckRange(start, count); + return GetLastIndex(start, count, match); + } + + private int GetLastIndex (int startIndex, int count, Predicate match) { + // unlike FindLastIndex, takes regular params for search range + for (int i = startIndex + count; i != startIndex; ) + if (match(Items[--i])) + return i; + return -1; + } + + public void ForEach (Action action) { + if (action == null) + throw new ArgumentNullException("action"); + for (int i = 0; i < Count; i++) + action(Items[i]); + } + + public Enumerator GetEnumerator () { + return new Enumerator(this); + } + + public ExposedList GetRange (int index, int count) { + CheckRange(index, count); + T[] tmpArray = new T[count]; + Array.Copy(Items, index, tmpArray, 0, count); + return new ExposedList(tmpArray, count); + } + + public int IndexOf (T item) { + return Array.IndexOf(Items, item, 0, Count); + } + + public int IndexOf (T item, int index) { + CheckIndex(index); + return Array.IndexOf(Items, item, index, Count - index); + } + + public int IndexOf (T item, int index, int count) { + if (index < 0) + throw new ArgumentOutOfRangeException("index"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count"); + + if ((uint)index + (uint)count > (uint)Count) + throw new ArgumentOutOfRangeException("index and count exceed length of list"); + + return Array.IndexOf(Items, item, index, count); + } + + private void Shift (int start, int delta) { + if (delta < 0) + start -= delta; + + if (start < Count) + Array.Copy(Items, start, Items, start + delta, Count - start); + + Count += delta; + + if (delta < 0) + Array.Clear(Items, Count, -delta); + } + + private void CheckIndex (int index) { + if (index < 0 || (uint)index > (uint)Count) + throw new ArgumentOutOfRangeException("index"); + } + + public void Insert (int index, T item) { + CheckIndex(index); + if (Count == Items.Length) + GrowIfNeeded(1); + Shift(index, 1); + Items[index] = item; + version++; + } + + private void CheckCollection (IEnumerable collection) { + if (collection == null) + throw new ArgumentNullException("collection"); + } + + public void InsertRange (int index, IEnumerable collection) { + CheckCollection(collection); + CheckIndex(index); + if (collection == this) { + T[] buffer = new T[Count]; + CopyTo(buffer, 0); + GrowIfNeeded(Count); + Shift(index, buffer.Length); + Array.Copy(buffer, 0, Items, index, buffer.Length); + } else { + ICollection c = collection as ICollection; + if (c != null) + InsertCollection(index, c); + else + InsertEnumeration(index, collection); + } + version++; + } + + private void InsertCollection (int index, ICollection collection) { + int collectionCount = collection.Count; + GrowIfNeeded(collectionCount); + + Shift(index, collectionCount); + collection.CopyTo(Items, index); + } + + private void InsertEnumeration (int index, IEnumerable enumerable) { + foreach (T t in enumerable) + Insert(index++, t); + } + + public int LastIndexOf (T item) { + return Array.LastIndexOf(Items, item, Count - 1, Count); + } + + public int LastIndexOf (T item, int index) { + CheckIndex(index); + return Array.LastIndexOf(Items, item, index, index + 1); + } + + public int LastIndexOf (T item, int index, int count) { + if (index < 0) + throw new ArgumentOutOfRangeException("index", index, "index is negative"); + + if (count < 0) + throw new ArgumentOutOfRangeException("count", count, "count is negative"); + + if (index - count + 1 < 0) + throw new ArgumentOutOfRangeException("count", count, "count is too large"); + + return Array.LastIndexOf(Items, item, index, count); + } + + public bool Remove (T item) { + int loc = IndexOf(item); + if (loc != -1) + RemoveAt(loc); + + return loc != -1; + } + + public int RemoveAll (Predicate match) { + CheckMatch(match); + int i = 0; + int j = 0; + + // Find the first item to remove + for (i = 0; i < Count; i++) + if (match(Items[i])) + break; + + if (i == Count) + return 0; + + version++; + + // Remove any additional items + for (j = i + 1; j < Count; j++) { + if (!match(Items[j])) + Items[i++] = Items[j]; + } + if (j - i > 0) + Array.Clear(Items, i, j - i); + + Count = i; + return (j - i); + } + + public void RemoveAt (int index) { + if (index < 0 || (uint)index >= (uint)Count) + throw new ArgumentOutOfRangeException("index"); + Shift(index, -1); + Array.Clear(Items, Count, 1); + version++; + } + + // Spine Added Method + // Based on Stack.Pop(); https://referencesource.microsoft.com/#mscorlib/system/collections/stack.cs + /// Pops the last item of the list. If the list is empty, Pop throws an InvalidOperationException. + public T Pop () { + if (Count == 0) + throw new InvalidOperationException("List is empty. Nothing to pop."); + + int i = Count - 1; + T item = Items[i]; + Items[i] = default(T); + Count--; + version++; + return item; + } + + public void RemoveRange (int index, int count) { + CheckRange(index, count); + if (count > 0) { + Shift(index, -count); + Array.Clear(Items, Count, count); + version++; + } + } + + public void Reverse () { + Array.Reverse(Items, 0, Count); + version++; + } + + public void Reverse (int index, int count) { + CheckRange(index, count); + Array.Reverse(Items, index, count); + version++; + } + + public void Sort () { + Array.Sort(Items, 0, Count, Comparer.Default); + version++; + } + + public void Sort (IComparer comparer) { + Array.Sort(Items, 0, Count, comparer); + version++; + } + + public void Sort (Comparison comparison) { + Array.Sort(Items, comparison); + version++; + } + + public void Sort (int index, int count, IComparer comparer) { + CheckRange(index, count); + Array.Sort(Items, index, count, comparer); + version++; + } + + public T[] ToArray () { + T[] t = new T[Count]; + Array.Copy(Items, t, Count); + + return t; + } + + public void TrimExcess () { + Capacity = Count; + } + + public bool TrueForAll (Predicate match) { + CheckMatch(match); + + for (int i = 0; i < Count; i++) + if (!match(Items[i])) + return false; + + return true; + } + + public int Capacity { + get { + return Items.Length; + } + set { + if ((uint)value < (uint)Count) + throw new ArgumentOutOfRangeException(); + + Array.Resize(ref Items, value); + } + } + + #region Interface implementations. + + IEnumerator IEnumerable.GetEnumerator () { + return GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator () { + return GetEnumerator(); + } + + #endregion + + public struct Enumerator : IEnumerator, IDisposable { + private ExposedList l; + private int next; + private int ver; + private T current; + + internal Enumerator (ExposedList l) + : this() { + this.l = l; + ver = l.version; + } + + public void Dispose () { + l = null; + } + + private void VerifyState () { + if (l == null) + throw new ObjectDisposedException(GetType().FullName); + if (ver != l.version) + throw new InvalidOperationException( + "Collection was modified; enumeration operation may not execute."); + } + + public bool MoveNext () { + VerifyState(); + + if (next < 0) + return false; + + if (next < l.Count) { + current = l.Items[next++]; + return true; + } + + next = -1; + return false; + } + + public T Current { + get { + return current; + } + } + + void IEnumerator.Reset () { + VerifyState(); + next = 0; + } + + object IEnumerator.Current { + get { + VerifyState(); + if (next <= 0) + throw new InvalidOperationException(); + return current; + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs.meta new file mode 100644 index 0000000..c51394b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/ExposedList.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 89690af94a880744989712505f2957b1 +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs new file mode 100644 index 0000000..aa380ad --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs @@ -0,0 +1,42 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine { + + ///The interface for items updated by . + public interface IUpdatable { + void Update (); + + ///Returns false when this item has not been updated because a skin is required and the active + /// skin does not contain this item. + /// + /// + bool Active { get; } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs.meta new file mode 100644 index 0000000..d1c948f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IUpdatable.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 44a51df5672fe4249b6763960587a017 +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs new file mode 100644 index 0000000..1d88c4a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs @@ -0,0 +1,365 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// + /// + /// Stores the current pose for an IK constraint. An IK constraint adjusts the rotation of 1 or 2 constrained bones so the tip of + /// the last bone is as close to the target bone as possible. + /// + /// See IK constraints in the Spine User Guide. + /// + public class IkConstraint : IUpdatable { + internal IkConstraintData data; + internal ExposedList bones = new ExposedList(); + internal Bone target; + internal int bendDirection; + internal bool compress, stretch; + internal float mix = 1, softness; + + internal bool active; + + public IkConstraint (IkConstraintData data, Skeleton skeleton) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + this.data = data; + mix = data.mix; + softness = data.softness; + bendDirection = data.bendDirection; + compress = data.compress; + stretch = data.stretch; + + bones = new ExposedList(data.bones.Count); + foreach (BoneData boneData in data.bones) + bones.Add(skeleton.FindBone(boneData.name)); + target = skeleton.FindBone(data.target.name); + } + + /// Copy constructor. + public IkConstraint (IkConstraint constraint, Skeleton skeleton) { + if (constraint == null) throw new ArgumentNullException("constraint cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); + data = constraint.data; + bones = new ExposedList(constraint.Bones.Count); + foreach (Bone bone in constraint.Bones) + bones.Add(skeleton.Bones.Items[bone.data.index]); + target = skeleton.Bones.Items[constraint.target.data.index]; + mix = constraint.mix; + softness = constraint.softness; + bendDirection = constraint.bendDirection; + compress = constraint.compress; + stretch = constraint.stretch; + } + + /// Applies the constraint to the constrained bones. + public void Apply () { + Update(); + } + + public void Update () { + Bone target = this.target; + ExposedList bones = this.bones; + switch (bones.Count) { + case 1: + Apply(bones.Items[0], target.worldX, target.worldY, compress, stretch, data.uniform, mix); + break; + case 2: + Apply(bones.Items[0], bones.Items[1], target.worldX, target.worldY, bendDirection, stretch, softness, mix); + break; + } + } + + /// The bones that will be modified by this IK constraint. + public ExposedList Bones { + get { return bones; } + } + + /// The bone that is the IK target. + public Bone Target { + get { return target; } + set { target = value; } + } + + /// A percentage (0-1) that controls the mix between the constrained and unconstrained rotations. + public float Mix { + get { return mix; } + set { mix = value; } + } + + ///For two bone IK, the distance from the maximum reach of the bones that rotation will slow. + public float Softness { + get { return softness; } + set { softness = value; } + } + + /// Controls the bend direction of the IK bones, either 1 or -1. + public int BendDirection { + get { return bendDirection; } + set { bendDirection = value; } + } + + /// + /// When true and only a single bone is being constrained, if the target is too close, the bone is scaled to reach it. + public bool Compress { + get { return compress; } + set { compress = value; } + } + + /// + /// When true, if the target is out of range, the parent bone is scaled to reach it. If more than one bone is being constrained + /// and the parent bone has local nonuniform scale, stretch is not applied. + public bool Stretch { + get { return stretch; } + set { stretch = value; } + } + + public bool Active { + get { return active; } + } + + /// The IK constraint's setup pose data. + public IkConstraintData Data { + get { return data; } + } + + override public string ToString () { + return data.name; + } + + /// Applies 1 bone IK. The target is specified in the world coordinate system. + static public void Apply (Bone bone, float targetX, float targetY, bool compress, bool stretch, bool uniform, + float alpha) { + if (!bone.appliedValid) bone.UpdateAppliedTransform(); + Bone p = bone.parent; + + float pa = p.a, pb = p.b, pc = p.c, pd = p.d; + float rotationIK = -bone.ashearX - bone.arotation; + float tx = 0, ty = 0; + + switch(bone.data.transformMode) { + case TransformMode.OnlyTranslation: + tx = targetX - bone.worldX; + ty = targetY - bone.worldY; + break; + case TransformMode.NoRotationOrReflection: { + float s = Math.Abs(pa * pd - pb * pc) / (pa * pa + pc * pc); + float sa = pa / bone.skeleton.ScaleX; + float sc = pc / bone.skeleton.ScaleY; + pb = -sc * s * bone.skeleton.ScaleX; + pd = sa * s * bone.skeleton.ScaleY; + rotationIK += (float)Math.Atan2(pc, pa) * MathUtils.RadDeg; + goto default; // Fall through. + } + default: { + float x = targetX - p.worldX, y = targetY - p.worldY; + float d = pa * pd - pb * pc; + tx = (x * pd - y * pb) / d - bone.ax; + ty = (y * pa - x * pc) / d - bone.ay; + break; + } + } + + rotationIK += (float)Math.Atan2(ty, tx) * MathUtils.RadDeg; + if (bone.ascaleX < 0) rotationIK += 180; + if (rotationIK > 180) + rotationIK -= 360; + else if (rotationIK < -180) // + rotationIK += 360; + + float sx = bone.ascaleX, sy = bone.ascaleY; + if (compress || stretch) { + switch (bone.data.transformMode) { + case TransformMode.NoScale: + tx = targetX - bone.worldX; + ty = targetY - bone.worldY; + break; + case TransformMode.NoScaleOrReflection: + tx = targetX - bone.worldX; + ty = targetY - bone.worldY; + break; + } + float b = bone.data.length * sx, dd = (float)Math.Sqrt(tx * tx + ty * ty); + if ((compress && dd < b) || (stretch && dd > b) && b > 0.0001f) { + float s = (dd / b - 1) * alpha + 1; + sx *= s; + if (uniform) sy *= s; + } + } + bone.UpdateWorldTransform(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY); + } + + /// Applies 2 bone IK. The target is specified in the world coordinate system. + /// A direct descendant of the parent bone. + static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, bool stretch, float softness, + float alpha) { + if (alpha == 0) { + child.UpdateWorldTransform(); + return; + } + if (!parent.appliedValid) parent.UpdateAppliedTransform(); + if (!child.appliedValid) child.UpdateAppliedTransform(); + float px = parent.ax, py = parent.ay, psx = parent.ascaleX, sx = psx, psy = parent.ascaleY, csx = child.ascaleX; + int os1, os2, s2; + if (psx < 0) { + psx = -psx; + os1 = 180; + s2 = -1; + } else { + os1 = 0; + s2 = 1; + } + if (psy < 0) { + psy = -psy; + s2 = -s2; + } + if (csx < 0) { + csx = -csx; + os2 = 180; + } else + os2 = 0; + float cx = child.ax, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d; + bool u = Math.Abs(psx - psy) <= 0.0001f; + if (!u) { + cy = 0; + cwx = a * cx + parent.worldX; + cwy = c * cx + parent.worldY; + } else { + cy = child.ay; + cwx = a * cx + b * cy + parent.worldX; + cwy = c * cx + d * cy + parent.worldY; + } + Bone pp = parent.parent; + a = pp.a; + b = pp.b; + c = pp.c; + d = pp.d; + float id = 1 / (a * d - b * c), x = cwx - pp.worldX, y = cwy - pp.worldY; + float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py; + float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2; + if (l1 < 0.0001f) { + Apply(parent, targetX, targetY, false, stretch, false, alpha); + child.UpdateWorldTransform(cx, cy, 0, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); + return; + } + x = targetX - pp.worldX; + y = targetY - pp.worldY; + float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; + float dd = tx * tx + ty * ty; + if (softness != 0) { + softness *= psx * (csx + 1) / 2; + float td = (float)Math.Sqrt(dd), sd = td - l1 - l2 * psx + softness; + if (sd > 0) { + float p = Math.Min(1, sd / (softness * 2)) - 1; + p = (sd - softness * (1 - p * p)) / td; + tx -= p * tx; + ty -= p * ty; + dd = tx * tx + ty * ty; + } + } + if (u) { + l2 *= psx; + float cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2); + if (cos < -1) + cos = -1; + else if (cos > 1) { + cos = 1; + if (stretch) sx *= ((float)Math.Sqrt(dd) / (l1 + l2) - 1) * alpha + 1; + } + a2 = (float)Math.Acos(cos) * bendDir; + a = l1 + l2 * cos; + b = l2 * (float)Math.Sin(a2); + a1 = (float)Math.Atan2(ty * a - tx * b, tx * a + ty * b); + } else { + a = psx * l2; + b = psy * l2; + float aa = a * a, bb = b * b, ta = (float)Math.Atan2(ty, tx); + c = bb * l1 * l1 + aa * dd - aa * bb; + float c1 = -2 * bb * l1, c2 = bb - aa; + d = c1 * c1 - 4 * c2 * c; + if (d >= 0) { + float q = (float)Math.Sqrt(d); + if (c1 < 0) q = -q; + q = -(c1 + q) / 2; + float r0 = q / c2, r1 = c / q; + float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1; + if (r * r <= dd) { + y = (float)Math.Sqrt(dd - r * r) * bendDir; + a1 = ta - (float)Math.Atan2(y, r); + a2 = (float)Math.Atan2(y / psy, (r - l1) / psx); + goto break_outer; // break outer; + } + } + float minAngle = MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0; + float maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0; + c = -a * l1 / (aa - bb); + if (c >= -1 && c <= 1) { + c = (float)Math.Acos(c); + x = a * (float)Math.Cos(c) + l1; + y = b * (float)Math.Sin(c); + d = x * x + y * y; + if (d < minDist) { + minAngle = c; + minDist = d; + minX = x; + minY = y; + } + if (d > maxDist) { + maxAngle = c; + maxDist = d; + maxX = x; + maxY = y; + } + } + if (dd <= (minDist + maxDist) / 2) { + a1 = ta - (float)Math.Atan2(minY * bendDir, minX); + a2 = minAngle * bendDir; + } else { + a1 = ta - (float)Math.Atan2(maxY * bendDir, maxX); + a2 = maxAngle * bendDir; + } + } + break_outer: + float os = (float)Math.Atan2(cy, cx) * s2; + float rotation = parent.arotation; + a1 = (a1 - os) * MathUtils.RadDeg + os1 - rotation; + if (a1 > 180) + a1 -= 360; + else if (a1 < -180) a1 += 360; + parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, sx, parent.ascaleY, 0, 0); + rotation = child.arotation; + a2 = ((a2 + os) * MathUtils.RadDeg - child.ashearX) * s2 + os2 - rotation; + if (a2 > 180) + a2 -= 360; + else if (a2 < -180) a2 += 360; + child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs.meta new file mode 100644 index 0000000..bffcd55 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraint.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 916f8e6534860cc40824adfc2916baa7 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs new file mode 100644 index 0000000..bc6a1c7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs @@ -0,0 +1,99 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + /// Stores the setup pose for an IkConstraint. + public class IkConstraintData : ConstraintData { + internal ExposedList bones = new ExposedList(); + internal BoneData target; + internal int bendDirection = 1; + internal bool compress, stretch, uniform; + internal float mix = 1, softness; + + public IkConstraintData (string name) : base(name) { + } + + /// The bones that are constrained by this IK Constraint. + public ExposedList Bones { + get { return bones; } + } + + /// The bone that is the IK target. + public BoneData Target { + get { return target; } + set { target = value; } + } + + /// + /// A percentage (0-1) that controls the mix between the constraint and unconstrained rotations. + public float Mix { + get { return mix; } + set { mix = value; } + } + + ///For two bone IK, the distance from the maximum reach of the bones that rotation will slow. + public float Softness { + get { return softness; } + set { softness = value; } + } + + /// Controls the bend direction of the IK bones, either 1 or -1. + public int BendDirection { + get { return bendDirection; } + set { bendDirection = value; } + } + + /// + /// When true, and only a single bone is being constrained, + /// if the target is too close, the bone is scaled to reach it. + public bool Compress { + get { return compress; } + set { compress = value; } + } + + /// + /// When true, if the target is out of range, the parent bone is scaled on the X axis to reach it. + /// If the bone has local nonuniform scale, stretching is not applied. + public bool Stretch { + get { return stretch; } + set { stretch = value; } + } + + /// + /// When true, only a single bone is being constrained and Compress or Stretch is used, + /// the bone is scaled both on the X and Y axes. + public bool Uniform { + get { return uniform; } + set { uniform = value; } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs.meta new file mode 100644 index 0000000..4825594 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/IkConstraintData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 94ad1e9256073264785f806086a000ba +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs new file mode 100644 index 0000000..aa790f4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs @@ -0,0 +1,531 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.IO; +using System.Text; +using System.Collections; +using System.Globalization; +using System.Collections.Generic; + +namespace Spine { + public static class Json { + public static object Deserialize (TextReader text) { + var parser = new SharpJson.JsonDecoder(); + parser.parseNumbersAsFloat = true; + return parser.Decode(text.ReadToEnd()); + } + } +} + +/** + * Copyright (c) 2016 Adriano Tinoco d'Oliveira Rezende + * + * Based on the JSON parser by Patrick van Bergen + * http://techblog.procurios.nl/k/news/view/14605/14863/how-do-i-write-my-own-parser-(for-json).html + * + * Changes made: + * + * - Optimized parser speed (deserialize roughly near 3x faster than original) + * - Added support to handle lexer/parser error messages with line numbers + * - Added more fine grained control over type conversions during the parsing + * - Refactory API (Separate Lexer code from Parser code and the Encoder from Decoder) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +namespace SharpJson +{ + class Lexer + { + public enum Token { + None, + Null, + True, + False, + Colon, + Comma, + String, + Number, + CurlyOpen, + CurlyClose, + SquaredOpen, + SquaredClose, + }; + + public bool hasError { + get { + return !success; + } + } + + public int lineNumber { + get; + private set; + } + + public bool parseNumbersAsFloat { + get; + set; + } + + char[] json; + int index = 0; + bool success = true; + char[] stringBuffer = new char[4096]; + + public Lexer(string text) + { + Reset(); + + json = text.ToCharArray(); + parseNumbersAsFloat = false; + } + + public void Reset() + { + index = 0; + lineNumber = 1; + success = true; + } + + public string ParseString() + { + int idx = 0; + StringBuilder builder = null; + + SkipWhiteSpaces(); + + // " + char c = json[index++]; + + bool failed = false; + bool complete = false; + + while (!complete && !failed) { + if (index == json.Length) + break; + + c = json[index++]; + if (c == '"') { + complete = true; + break; + } else if (c == '\\') { + if (index == json.Length) + break; + + c = json[index++]; + + switch (c) { + case '"': + stringBuffer[idx++] = '"'; + break; + case '\\': + stringBuffer[idx++] = '\\'; + break; + case '/': + stringBuffer[idx++] = '/'; + break; + case 'b': + stringBuffer[idx++] = '\b'; + break; + case'f': + stringBuffer[idx++] = '\f'; + break; + case 'n': + stringBuffer[idx++] = '\n'; + break; + case 'r': + stringBuffer[idx++] = '\r'; + break; + case 't': + stringBuffer[idx++] = '\t'; + break; + case 'u': + int remainingLength = json.Length - index; + if (remainingLength >= 4) { + var hex = new string(json, index, 4); + + // XXX: handle UTF + stringBuffer[idx++] = (char) Convert.ToInt32(hex, 16); + + // skip 4 chars + index += 4; + } else { + failed = true; + } + break; + } + } else { + stringBuffer[idx++] = c; + } + + if (idx >= stringBuffer.Length) { + if (builder == null) + builder = new StringBuilder(); + + builder.Append(stringBuffer, 0, idx); + idx = 0; + } + } + + if (!complete) { + success = false; + return null; + } + + if (builder != null) + return builder.ToString (); + else + return new string (stringBuffer, 0, idx); + } + + string GetNumberString() + { + SkipWhiteSpaces(); + + int lastIndex = GetLastIndexOfNumber(index); + int charLength = (lastIndex - index) + 1; + + var result = new string (json, index, charLength); + + index = lastIndex + 1; + + return result; + } + + public float ParseFloatNumber() + { + float number; + var str = GetNumberString (); + + if (!float.TryParse (str, NumberStyles.Float, CultureInfo.InvariantCulture, out number)) + return 0; + + return number; + } + + public double ParseDoubleNumber() + { + double number; + var str = GetNumberString (); + + if (!double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out number)) + return 0; + + return number; + } + + int GetLastIndexOfNumber(int index) + { + int lastIndex; + + for (lastIndex = index; lastIndex < json.Length; lastIndex++) { + char ch = json[lastIndex]; + + if ((ch < '0' || ch > '9') && ch != '+' && ch != '-' + && ch != '.' && ch != 'e' && ch != 'E') + break; + } + + return lastIndex - 1; + } + + void SkipWhiteSpaces() + { + for (; index < json.Length; index++) { + char ch = json[index]; + + if (ch == '\n') + lineNumber++; + + if (!char.IsWhiteSpace(json[index])) + break; + } + } + + public Token LookAhead() + { + SkipWhiteSpaces(); + + int savedIndex = index; + return NextToken(json, ref savedIndex); + } + + public Token NextToken() + { + SkipWhiteSpaces(); + return NextToken(json, ref index); + } + + static Token NextToken(char[] json, ref int index) + { + if (index == json.Length) + return Token.None; + + char c = json[index++]; + + switch (c) { + case '{': + return Token.CurlyOpen; + case '}': + return Token.CurlyClose; + case '[': + return Token.SquaredOpen; + case ']': + return Token.SquaredClose; + case ',': + return Token.Comma; + case '"': + return Token.String; + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case '-': + return Token.Number; + case ':': + return Token.Colon; + } + + index--; + + int remainingLength = json.Length - index; + + // false + if (remainingLength >= 5) { + if (json[index] == 'f' && + json[index + 1] == 'a' && + json[index + 2] == 'l' && + json[index + 3] == 's' && + json[index + 4] == 'e') { + index += 5; + return Token.False; + } + } + + // true + if (remainingLength >= 4) { + if (json[index] == 't' && + json[index + 1] == 'r' && + json[index + 2] == 'u' && + json[index + 3] == 'e') { + index += 4; + return Token.True; + } + } + + // null + if (remainingLength >= 4) { + if (json[index] == 'n' && + json[index + 1] == 'u' && + json[index + 2] == 'l' && + json[index + 3] == 'l') { + index += 4; + return Token.Null; + } + } + + return Token.None; + } + } + + public class JsonDecoder + { + public string errorMessage { + get; + private set; + } + + public bool parseNumbersAsFloat { + get; + set; + } + + Lexer lexer; + + public JsonDecoder() + { + errorMessage = null; + parseNumbersAsFloat = false; + } + + public object Decode(string text) + { + errorMessage = null; + + lexer = new Lexer(text); + lexer.parseNumbersAsFloat = parseNumbersAsFloat; + + return ParseValue(); + } + + public static object DecodeText(string text) + { + var builder = new JsonDecoder(); + return builder.Decode(text); + } + + IDictionary ParseObject() + { + var table = new Dictionary(); + + // { + lexer.NextToken(); + + while (true) { + var token = lexer.LookAhead(); + + switch (token) { + case Lexer.Token.None: + TriggerError("Invalid token"); + return null; + case Lexer.Token.Comma: + lexer.NextToken(); + break; + case Lexer.Token.CurlyClose: + lexer.NextToken(); + return table; + default: + // name + string name = EvalLexer(lexer.ParseString()); + + if (errorMessage != null) + return null; + + // : + token = lexer.NextToken(); + + if (token != Lexer.Token.Colon) { + TriggerError("Invalid token; expected ':'"); + return null; + } + + // value + object value = ParseValue(); + + if (errorMessage != null) + return null; + + table[name] = value; + break; + } + } + + //return null; // Unreachable code + } + + IList ParseArray() + { + var array = new List(); + + // [ + lexer.NextToken(); + + while (true) { + var token = lexer.LookAhead(); + + switch (token) { + case Lexer.Token.None: + TriggerError("Invalid token"); + return null; + case Lexer.Token.Comma: + lexer.NextToken(); + break; + case Lexer.Token.SquaredClose: + lexer.NextToken(); + return array; + default: + object value = ParseValue(); + + if (errorMessage != null) + return null; + + array.Add(value); + break; + } + } + + //return null; // Unreachable code + } + + object ParseValue() + { + switch (lexer.LookAhead()) { + case Lexer.Token.String: + return EvalLexer(lexer.ParseString()); + case Lexer.Token.Number: + if (parseNumbersAsFloat) + return EvalLexer(lexer.ParseFloatNumber()); + else + return EvalLexer(lexer.ParseDoubleNumber()); + case Lexer.Token.CurlyOpen: + return ParseObject(); + case Lexer.Token.SquaredOpen: + return ParseArray(); + case Lexer.Token.True: + lexer.NextToken(); + return true; + case Lexer.Token.False: + lexer.NextToken(); + return false; + case Lexer.Token.Null: + lexer.NextToken(); + return null; + case Lexer.Token.None: + break; + } + + TriggerError("Unable to parse value"); + return null; + } + + void TriggerError(string message) + { + errorMessage = string.Format("Error: '{0}' at line {1}", + message, lexer.lineNumber); + } + + T EvalLexer(T value) + { + if (lexer.hasError) + TriggerError("Lexical error ocurred"); + + return value; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs.meta new file mode 100644 index 0000000..ca4d324 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Json.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 371f40ecc08b2eb4cbec49585d41e2c3 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs new file mode 100644 index 0000000..ad10ec2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs @@ -0,0 +1,173 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +//#define USE_FAST_SIN_COS_ATAN2_APPROXIMATIONS + +using System; + +namespace Spine { + public static class MathUtils { + public const float PI = 3.1415927f; + public const float PI2 = PI * 2; + public const float RadDeg = 180f / PI; + public const float DegRad = PI / 180; + + static Random random = new Random(); + + #if USE_FAST_SIN_COS_ATAN2_APPROXIMATIONS + const int SIN_BITS = 14; // 16KB. Adjust for accuracy. + const int SIN_MASK = ~(-1 << SIN_BITS); + const int SIN_COUNT = SIN_MASK + 1; + const float RadFull = PI * 2; + const float DegFull = 360; + const float RadToIndex = SIN_COUNT / RadFull; + const float DegToIndex = SIN_COUNT / DegFull; + static float[] sin = new float[SIN_COUNT]; + + static MathUtils () { + for (int i = 0; i < SIN_COUNT; i++) + sin[i] = (float)Math.Sin((i + 0.5f) / SIN_COUNT * RadFull); + for (int i = 0; i < 360; i += 90) + sin[(int)(i * DegToIndex) & SIN_MASK] = (float)Math.Sin(i * DegRad); + } + + /// Returns the sine of a given angle in radians from a lookup table. + static public float Sin (float radians) { + return sin[(int)(radians * RadToIndex) & SIN_MASK]; + } + + /// Returns the cosine of a given angle in radians from a lookup table. + static public float Cos (float radians) { + return sin[(int)((radians + PI / 2) * RadToIndex) & SIN_MASK]; + } + + /// Returns the sine of a given angle in degrees from a lookup table. + static public float SinDeg (float degrees) { + return sin[(int)(degrees * DegToIndex) & SIN_MASK]; + } + + /// Returns the cosine of a given angle in degrees from a lookup table. + static public float CosDeg (float degrees) { + return sin[(int)((degrees + 90) * DegToIndex) & SIN_MASK]; + } + + /// Returns atan2 in radians, faster but less accurate than Math.Atan2. Average error of 0.00231 radians (0.1323 + /// degrees), largest error of 0.00488 radians (0.2796 degrees). + static public float Atan2 (float y, float x) { + if (x == 0f) { + if (y > 0f) return PI / 2; + if (y == 0f) return 0f; + return -PI / 2; + } + float atan, z = y / x; + if (Math.Abs(z) < 1f) { + atan = z / (1f + 0.28f * z * z); + if (x < 0f) return atan + (y < 0f ? -PI : PI); + return atan; + } + atan = PI / 2 - z / (z * z + 0.28f); + return y < 0f ? atan - PI : atan; + } + #else + /// Returns the sine of a given angle in radians. + static public float Sin (float radians) { + return (float)Math.Sin(radians); + } + + /// Returns the cosine of a given angle in radians. + static public float Cos (float radians) { + return (float)Math.Cos(radians); + } + + /// Returns the sine of a given angle in degrees. + static public float SinDeg (float degrees) { + return (float)Math.Sin(degrees * DegRad); + } + + /// Returns the cosine of a given angle in degrees. + static public float CosDeg (float degrees) { + return (float)Math.Cos(degrees * DegRad); + } + + /// Returns the atan2 using Math.Atan2. + static public float Atan2 (float y, float x) { + return (float)Math.Atan2(y, x); + } + #endif + static public float Clamp (float value, float min, float max) { + if (value < min) return min; + if (value > max) return max; + return value; + } + + static public float RandomTriangle(float min, float max) { + return RandomTriangle(min, max, (min + max) * 0.5f); + } + + static public float RandomTriangle(float min, float max, float mode) { + float u = (float)random.NextDouble(); + float d = max - min; + if (u <= (mode - min) / d) return min + (float)Math.Sqrt(u * d * (mode - min)); + return max - (float)Math.Sqrt((1 - u) * d * (max - mode)); + } + } + + public abstract class IInterpolation { + public static IInterpolation Pow2 = new Pow(2); + public static IInterpolation Pow2Out = new PowOut(2); + + protected abstract float Apply(float a); + + public float Apply(float start, float end, float a) { + return start + (end - start) * Apply(a); + } + } + + public class Pow: IInterpolation { + public float Power { get; set; } + + public Pow(float power) { + Power = power; + } + + protected override float Apply(float a) { + if (a <= 0.5f) return (float)Math.Pow(a * 2, Power) / 2; + return (float)Math.Pow((a - 1) * 2, Power) / (Power % 2 == 0 ? -2 : 2) + 1; + } + } + + public class PowOut : Pow { + public PowOut(float power) : base(power) { + } + + protected override float Apply(float a) { + return (float)Math.Pow(a - 1, Power) * (Power % 2 == 0 ? -1 : 1) + 1; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs.meta new file mode 100644 index 0000000..00c7de3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/MathUtils.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 03b653e54c5403b4191f5003d64c6e18 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs new file mode 100644 index 0000000..c8fef41 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs @@ -0,0 +1,467 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + + /// + /// + /// Stores the current pose for a path constraint. A path constraint adjusts the rotation, translation, and scale of the + /// constrained bones so they follow a {@link PathAttachment}. + /// + /// See Path constraints in the Spine User Guide. + /// + public class PathConstraint : IUpdatable { + const int NONE = -1, BEFORE = -2, AFTER = -3; + const float Epsilon = 0.00001f; + + internal PathConstraintData data; + internal ExposedList bones; + internal Slot target; + internal float position, spacing, rotateMix, translateMix; + + internal bool active; + + internal ExposedList spaces = new ExposedList(), positions = new ExposedList(); + internal ExposedList world = new ExposedList(), curves = new ExposedList(), lengths = new ExposedList(); + internal float[] segments = new float[10]; + + public PathConstraint (PathConstraintData data, Skeleton skeleton) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + this.data = data; + bones = new ExposedList(data.Bones.Count); + foreach (BoneData boneData in data.bones) + bones.Add(skeleton.FindBone(boneData.name)); + target = skeleton.FindSlot(data.target.name); + position = data.position; + spacing = data.spacing; + rotateMix = data.rotateMix; + translateMix = data.translateMix; + } + + /// Copy constructor. + public PathConstraint (PathConstraint constraint, Skeleton skeleton) { + if (constraint == null) throw new ArgumentNullException("constraint cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); + data = constraint.data; + bones = new ExposedList(constraint.Bones.Count); + foreach (Bone bone in constraint.Bones) + bones.Add(skeleton.Bones.Items[bone.data.index]); + target = skeleton.slots.Items[constraint.target.data.index]; + position = constraint.position; + spacing = constraint.spacing; + rotateMix = constraint.rotateMix; + translateMix = constraint.translateMix; + } + + /// Applies the constraint to the constrained bones. + public void Apply () { + Update(); + } + + public void Update () { + PathAttachment attachment = target.Attachment as PathAttachment; + if (attachment == null) return; + + float rotateMix = this.rotateMix, translateMix = this.translateMix; + bool translate = translateMix > 0, rotate = rotateMix > 0; + if (!translate && !rotate) return; + + PathConstraintData data = this.data; + bool percentSpacing = data.spacingMode == SpacingMode.Percent; + RotateMode rotateMode = data.rotateMode; + bool tangents = rotateMode == RotateMode.Tangent, scale = rotateMode == RotateMode.ChainScale; + int boneCount = this.bones.Count, spacesCount = tangents ? boneCount : boneCount + 1; + Bone[] bonesItems = this.bones.Items; + ExposedList spaces = this.spaces.Resize(spacesCount), lengths = null; + float spacing = this.spacing; + if (scale || !percentSpacing) { + if (scale) lengths = this.lengths.Resize(boneCount); + bool lengthSpacing = data.spacingMode == SpacingMode.Length; + for (int i = 0, n = spacesCount - 1; i < n;) { + Bone bone = bonesItems[i]; + float setupLength = bone.data.length; + if (setupLength < PathConstraint.Epsilon) { + if (scale) lengths.Items[i] = 0; + spaces.Items[++i] = 0; + } else if (percentSpacing) { + if (scale) { + float x = setupLength * bone.a, y = setupLength * bone.c; + float length = (float)Math.Sqrt(x * x + y * y); + lengths.Items[i] = length; + } + spaces.Items[++i] = spacing; + } else { + float x = setupLength * bone.a, y = setupLength * bone.c; + float length = (float)Math.Sqrt(x * x + y * y); + if (scale) lengths.Items[i] = length; + spaces.Items[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length / setupLength; + } + } + } else { + for (int i = 1; i < spacesCount; i++) + spaces.Items[i] = spacing; + } + + float[] positions = ComputeWorldPositions(attachment, spacesCount, tangents, + data.positionMode == PositionMode.Percent, percentSpacing); + float boneX = positions[0], boneY = positions[1], offsetRotation = data.offsetRotation; + bool tip; + if (offsetRotation == 0) { + tip = rotateMode == RotateMode.Chain; + } else { + tip = false; + Bone p = target.bone; + offsetRotation *= p.a * p.d - p.b * p.c > 0 ? MathUtils.DegRad : -MathUtils.DegRad; + } + for (int i = 0, p = 3; i < boneCount; i++, p += 3) { + Bone bone = bonesItems[i]; + bone.worldX += (boneX - bone.worldX) * translateMix; + bone.worldY += (boneY - bone.worldY) * translateMix; + float x = positions[p], y = positions[p + 1], dx = x - boneX, dy = y - boneY; + if (scale) { + float length = lengths.Items[i]; + if (length >= PathConstraint.Epsilon) { + float s = ((float)Math.Sqrt(dx * dx + dy * dy) / length - 1) * rotateMix + 1; + bone.a *= s; + bone.c *= s; + } + } + boneX = x; + boneY = y; + if (rotate) { + float a = bone.a, b = bone.b, c = bone.c, d = bone.d, r, cos, sin; + if (tangents) + r = positions[p - 1]; + else if (spaces.Items[i + 1] < PathConstraint.Epsilon) + r = positions[p + 2]; + else + r = MathUtils.Atan2(dy, dx); + r -= MathUtils.Atan2(c, a); + if (tip) { + cos = MathUtils.Cos(r); + sin = MathUtils.Sin(r); + float length = bone.data.length; + boneX += (length * (cos * a - sin * c) - dx) * rotateMix; + boneY += (length * (sin * a + cos * c) - dy) * rotateMix; + } else + r += offsetRotation; + if (r > MathUtils.PI) + r -= MathUtils.PI2; + else if (r < -MathUtils.PI) // + r += MathUtils.PI2; + r *= rotateMix; + cos = MathUtils.Cos(r); + sin = MathUtils.Sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + } + bone.appliedValid = false; + } + } + + float[] ComputeWorldPositions (PathAttachment path, int spacesCount, bool tangents, bool percentPosition, + bool percentSpacing) { + + Slot target = this.target; + float position = this.position; + float[] spacesItems = this.spaces.Items, output = this.positions.Resize(spacesCount * 3 + 2).Items, world; + bool closed = path.Closed; + int verticesLength = path.WorldVerticesLength, curveCount = verticesLength / 6, prevCurve = NONE; + float pathLength = 0; + + if (!path.ConstantSpeed) { + float[] lengths = path.Lengths; + curveCount -= closed ? 1 : 2; + pathLength = lengths[curveCount]; + if (percentPosition) position *= pathLength; + if (percentSpacing) { + for (int i = 1; i < spacesCount; i++) + spacesItems[i] *= pathLength; + } + world = this.world.Resize(8).Items; + for (int i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { + float space = spacesItems[i]; + position += space; + float p = position; + + if (closed) { + p %= pathLength; + if (p < 0) p += pathLength; + curve = 0; + } else if (p < 0) { + if (prevCurve != BEFORE) { + prevCurve = BEFORE; + path.ComputeWorldVertices(target, 2, 4, world, 0, 2); + } + AddBeforePosition(p, world, 0, output, o); + continue; + } else if (p > pathLength) { + if (prevCurve != AFTER) { + prevCurve = AFTER; + path.ComputeWorldVertices(target, verticesLength - 6, 4, world, 0, 2); + } + AddAfterPosition(p - pathLength, world, 0, output, o); + continue; + } + + // Determine curve containing position. + for (;; curve++) { + float length = lengths[curve]; + if (p > length) continue; + if (curve == 0) + p /= length; + else { + float prev = lengths[curve - 1]; + p = (p - prev) / (length - prev); + } + break; + } + if (curve != prevCurve) { + prevCurve = curve; + if (closed && curve == curveCount) { + path.ComputeWorldVertices(target, verticesLength - 4, 4, world, 0, 2); + path.ComputeWorldVertices(target, 0, 4, world, 4, 2); + } else + path.ComputeWorldVertices(target, curve * 6 + 2, 8, world, 0, 2); + } + AddCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], output, o, + tangents || (i > 0 && space < PathConstraint.Epsilon)); + } + return output; + } + + // World vertices. + if (closed) { + verticesLength += 2; + world = this.world.Resize(verticesLength).Items; + path.ComputeWorldVertices(target, 2, verticesLength - 4, world, 0, 2); + path.ComputeWorldVertices(target, 0, 2, world, verticesLength - 4, 2); + world[verticesLength - 2] = world[0]; + world[verticesLength - 1] = world[1]; + } else { + curveCount--; + verticesLength -= 4; + world = this.world.Resize(verticesLength).Items; + path.ComputeWorldVertices(target, 2, verticesLength, world, 0, 2); + } + + // Curve lengths. + float[] curves = this.curves.Resize(curveCount).Items; + pathLength = 0; + float x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; + float tmpx, tmpy, dddfx, dddfy, ddfx, ddfy, dfx, dfy; + for (int i = 0, w = 2; i < curveCount; i++, w += 6) { + cx1 = world[w]; + cy1 = world[w + 1]; + cx2 = world[w + 2]; + cy2 = world[w + 3]; + x2 = world[w + 4]; + y2 = world[w + 5]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.1875f; + tmpy = (y1 - cy1 * 2 + cy2) * 0.1875f; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375f; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375f; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.75f + tmpx + dddfx * 0.16666667f; + dfy = (cy1 - y1) * 0.75f + tmpy + dddfy * 0.16666667f; + pathLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + pathLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + pathLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + pathLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + curves[i] = pathLength; + x1 = x2; + y1 = y2; + } + if (percentPosition) + position *= pathLength; + else + position *= pathLength / path.lengths[curveCount - 1]; + + if (percentSpacing) { + for (int i = 1; i < spacesCount; i++) + spacesItems[i] *= pathLength; + } + + float[] segments = this.segments; + float curveLength = 0; + for (int i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { + float space = spacesItems[i]; + position += space; + float p = position; + + if (closed) { + p %= pathLength; + if (p < 0) p += pathLength; + curve = 0; + } else if (p < 0) { + AddBeforePosition(p, world, 0, output, o); + continue; + } else if (p > pathLength) { + AddAfterPosition(p - pathLength, world, verticesLength - 4, output, o); + continue; + } + + // Determine curve containing position. + for (;; curve++) { + float length = curves[curve]; + if (p > length) continue; + if (curve == 0) + p /= length; + else { + float prev = curves[curve - 1]; + p = (p - prev) / (length - prev); + } + break; + } + + // Curve segment lengths. + if (curve != prevCurve) { + prevCurve = curve; + int ii = curve * 6; + x1 = world[ii]; + y1 = world[ii + 1]; + cx1 = world[ii + 2]; + cy1 = world[ii + 3]; + cx2 = world[ii + 4]; + cy2 = world[ii + 5]; + x2 = world[ii + 6]; + y2 = world[ii + 7]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.03f; + tmpy = (y1 - cy1 * 2 + cy2) * 0.03f; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006f; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006f; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.3f + tmpx + dddfx * 0.16666667f; + dfy = (cy1 - y1) * 0.3f + tmpy + dddfy * 0.16666667f; + curveLength = (float)Math.Sqrt(dfx * dfx + dfy * dfy); + segments[0] = curveLength; + for (ii = 1; ii < 8; ii++) { + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + curveLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + segments[ii] = curveLength; + } + dfx += ddfx; + dfy += ddfy; + curveLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + segments[8] = curveLength; + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + curveLength += (float)Math.Sqrt(dfx * dfx + dfy * dfy); + segments[9] = curveLength; + segment = 0; + } + + // Weight by segment length. + p *= curveLength; + for (;; segment++) { + float length = segments[segment]; + if (p > length) continue; + if (segment == 0) + p /= length; + else { + float prev = segments[segment - 1]; + p = segment + (p - prev) / (length - prev); + } + break; + } + AddCurvePosition(p * 0.1f, x1, y1, cx1, cy1, cx2, cy2, x2, y2, output, o, tangents || (i > 0 && space < PathConstraint.Epsilon)); + } + return output; + } + + static void AddBeforePosition (float p, float[] temp, int i, float[] output, int o) { + float x1 = temp[i], y1 = temp[i + 1], dx = temp[i + 2] - x1, dy = temp[i + 3] - y1, r = MathUtils.Atan2(dy, dx); + output[o] = x1 + p * MathUtils.Cos(r); + output[o + 1] = y1 + p * MathUtils.Sin(r); + output[o + 2] = r; + } + + static void AddAfterPosition (float p, float[] temp, int i, float[] output, int o) { + float x1 = temp[i + 2], y1 = temp[i + 3], dx = x1 - temp[i], dy = y1 - temp[i + 1], r = MathUtils.Atan2(dy, dx); + output[o] = x1 + p * MathUtils.Cos(r); + output[o + 1] = y1 + p * MathUtils.Sin(r); + output[o + 2] = r; + } + + static void AddCurvePosition (float p, float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2, + float[] output, int o, bool tangents) { + if (p < PathConstraint.Epsilon || float.IsNaN(p)) { + output[o] = x1; + output[o + 1] = y1; + output[o + 2] = (float)Math.Atan2(cy1 - y1, cx1 - x1); + return; + } + float tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; + float ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p; + float x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; + output[o] = x; + output[o + 1] = y; + if (tangents) { + if (p < 0.001f) + output[o + 2] = (float)Math.Atan2(cy1 - y1, cx1 - x1); + else + output[o + 2] = (float)Math.Atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)); + } + } + + /// The position along the path. + public float Position { get { return position; } set { position = value; } } + /// The spacing between bones. + public float Spacing { get { return spacing; } set { spacing = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained rotations. + public float RotateMix { get { return rotateMix; } set { rotateMix = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained translations. + public float TranslateMix { get { return translateMix; } set { translateMix = value; } } + /// The bones that will be modified by this path constraint. + public ExposedList Bones { get { return bones; } } + /// The slot whose path attachment will be used to constrained the bones. + public Slot Target { get { return target; } set { target = value; } } + public bool Active { get { return active; } } + /// The path constraint's setup pose data. + public PathConstraintData Data { get { return data; } } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs.meta new file mode 100644 index 0000000..3ee8122 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraint.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 731d05fbc2874c74984813ce4c5bb8df +timeCreated: 1467213650 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs new file mode 100644 index 0000000..fa6e71f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs @@ -0,0 +1,68 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class PathConstraintData : ConstraintData { + internal ExposedList bones = new ExposedList(); + internal SlotData target; + internal PositionMode positionMode; + internal SpacingMode spacingMode; + internal RotateMode rotateMode; + internal float offsetRotation; + internal float position, spacing, rotateMix, translateMix; + + public PathConstraintData (string name) : base(name) { + } + + public ExposedList Bones { get { return bones; } } + public SlotData Target { get { return target; } set { target = value; } } + public PositionMode PositionMode { get { return positionMode; } set { positionMode = value; } } + public SpacingMode SpacingMode { get { return spacingMode; } set { spacingMode = value; } } + public RotateMode RotateMode { get { return rotateMode; } set { rotateMode = value; } } + public float OffsetRotation { get { return offsetRotation; } set { offsetRotation = value; } } + public float Position { get { return position; } set { position = value; } } + public float Spacing { get { return spacing; } set { spacing = value; } } + public float RotateMix { get { return rotateMix; } set { rotateMix = value; } } + public float TranslateMix { get { return translateMix; } set { translateMix = value; } } + } + + public enum PositionMode { + Fixed, Percent + } + + public enum SpacingMode { + Length, Fixed, Percent + } + + public enum RotateMode { + Tangent, Chain, ChainScale + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs.meta new file mode 100644 index 0000000..6506276 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/PathConstraintData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9d836858269be96428428fb6764dfc3a +timeCreated: 1467213651 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs new file mode 100644 index 0000000..1bd5017 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs @@ -0,0 +1,635 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; + +namespace Spine { + public class Skeleton { + internal SkeletonData data; + internal ExposedList bones; + internal ExposedList slots; + internal ExposedList drawOrder; + internal ExposedList ikConstraints; + internal ExposedList transformConstraints; + internal ExposedList pathConstraints; + internal ExposedList updateCache = new ExposedList(); + internal ExposedList updateCacheReset = new ExposedList(); + internal Skin skin; + internal float r = 1, g = 1, b = 1, a = 1; + internal float time; + private float scaleX = 1, scaleY = 1; + internal float x, y; + + public SkeletonData Data { get { return data; } } + public ExposedList Bones { get { return bones; } } + public ExposedList UpdateCacheList { get { return updateCache; } } + public ExposedList Slots { get { return slots; } } + public ExposedList DrawOrder { get { return drawOrder; } } + public ExposedList IkConstraints { get { return ikConstraints; } } + public ExposedList PathConstraints { get { return pathConstraints; } } + public ExposedList TransformConstraints { get { return transformConstraints; } } + public Skin Skin { get { return skin; } set { SetSkin(value); } } + public float R { get { return r; } set { r = value; } } + public float G { get { return g; } set { g = value; } } + public float B { get { return b; } set { b = value; } } + public float A { get { return a; } set { a = value; } } + public float Time { get { return time; } set { time = value; } } + public float X { get { return x; } set { x = value; } } + public float Y { get { return y; } set { y = value; } } + public float ScaleX { get { return scaleX; } set { scaleX = value; } } + public float ScaleY { get { return scaleY * (Bone.yDown ? -1 : 1); } set { scaleY = value; } } + + [Obsolete("Use ScaleX instead. FlipX is when ScaleX is negative.")] + public bool FlipX { get { return scaleX < 0; } set { scaleX = value ? -1f : 1f; } } + + [Obsolete("Use ScaleY instead. FlipY is when ScaleY is negative.")] + public bool FlipY { get { return scaleY < 0; } set { scaleY = value ? -1f : 1f; } } + + public Bone RootBone { + get { return bones.Count == 0 ? null : bones.Items[0]; } + } + + public Skeleton (SkeletonData data) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + this.data = data; + + bones = new ExposedList(data.bones.Count); + foreach (BoneData boneData in data.bones) { + Bone bone; + if (boneData.parent == null) { + bone = new Bone(boneData, this, null); + } else { + Bone parent = bones.Items[boneData.parent.index]; + bone = new Bone(boneData, this, parent); + parent.children.Add(bone); + } + bones.Add(bone); + } + + slots = new ExposedList(data.slots.Count); + drawOrder = new ExposedList(data.slots.Count); + foreach (SlotData slotData in data.slots) { + Bone bone = bones.Items[slotData.boneData.index]; + Slot slot = new Slot(slotData, bone); + slots.Add(slot); + drawOrder.Add(slot); + } + + ikConstraints = new ExposedList(data.ikConstraints.Count); + foreach (IkConstraintData ikConstraintData in data.ikConstraints) + ikConstraints.Add(new IkConstraint(ikConstraintData, this)); + + transformConstraints = new ExposedList(data.transformConstraints.Count); + foreach (TransformConstraintData transformConstraintData in data.transformConstraints) + transformConstraints.Add(new TransformConstraint(transformConstraintData, this)); + + pathConstraints = new ExposedList (data.pathConstraints.Count); + foreach (PathConstraintData pathConstraintData in data.pathConstraints) + pathConstraints.Add(new PathConstraint(pathConstraintData, this)); + + UpdateCache(); + UpdateWorldTransform(); + } + + /// Caches information about bones and constraints. Must be called if the is modified or if bones, constraints, or + /// constraints, or weighted path attachments are added or removed. + public void UpdateCache () { + var updateCache = this.updateCache; + updateCache.Clear(); + this.updateCacheReset.Clear(); + + int boneCount = this.bones.Items.Length; + var bones = this.bones; + for (int i = 0; i < boneCount; i++) { + Bone bone = bones.Items[i]; + bone.sorted = bone.data.skinRequired; + bone.active = !bone.sorted; + } + if (skin != null) { + Object[] skinBones = skin.bones.Items; + for (int i = 0, n = skin.bones.Count; i < n; i++) { + Bone bone = (Bone)bones.Items[((BoneData)skinBones[i]).index]; + do { + bone.sorted = false; + bone.active = true; + bone = bone.parent; + } while (bone != null); + } + } + + int ikCount = this.ikConstraints.Count, transformCount = this.transformConstraints.Count, pathCount = this.pathConstraints.Count; + var ikConstraints = this.ikConstraints; + var transformConstraints = this.transformConstraints; + var pathConstraints = this.pathConstraints; + int constraintCount = ikCount + transformCount + pathCount; + //outer: + for (int i = 0; i < constraintCount; i++) { + for (int ii = 0; ii < ikCount; ii++) { + IkConstraint constraint = ikConstraints.Items[ii]; + if (constraint.data.order == i) { + SortIkConstraint(constraint); + goto continue_outer; //continue outer; + } + } + for (int ii = 0; ii < transformCount; ii++) { + TransformConstraint constraint = transformConstraints.Items[ii]; + if (constraint.data.order == i) { + SortTransformConstraint(constraint); + goto continue_outer; //continue outer; + } + } + for (int ii = 0; ii < pathCount; ii++) { + PathConstraint constraint = pathConstraints.Items[ii]; + if (constraint.data.order == i) { + SortPathConstraint(constraint); + goto continue_outer; //continue outer; + } + } + continue_outer: {} + } + + for (int i = 0; i < boneCount; i++) + SortBone(bones.Items[i]); + } + + private void SortIkConstraint (IkConstraint constraint) { + constraint.active = constraint.target.active + && (!constraint.data.skinRequired || (skin != null && skin.constraints.Contains(constraint.data))); + if (!constraint.active) return; + + Bone target = constraint.target; + SortBone(target); + + var constrained = constraint.bones; + Bone parent = constrained.Items[0]; + SortBone(parent); + + if (constrained.Count > 1) { + Bone child = constrained.Items[constrained.Count - 1]; + if (!updateCache.Contains(child)) + updateCacheReset.Add(child); + } + + updateCache.Add(constraint); + + SortReset(parent.children); + constrained.Items[constrained.Count - 1].sorted = true; + } + + private void SortPathConstraint (PathConstraint constraint) { + constraint.active = constraint.target.bone.active + && (!constraint.data.skinRequired || (skin != null && skin.constraints.Contains(constraint.data))); + if (!constraint.active) return; + + Slot slot = constraint.target; + int slotIndex = slot.data.index; + Bone slotBone = slot.bone; + if (skin != null) SortPathConstraintAttachment(skin, slotIndex, slotBone); + if (data.defaultSkin != null && data.defaultSkin != skin) + SortPathConstraintAttachment(data.defaultSkin, slotIndex, slotBone); + + Attachment attachment = slot.attachment; + if (attachment is PathAttachment) SortPathConstraintAttachment(attachment, slotBone); + + var constrained = constraint.bones; + int boneCount = constrained.Count; + for (int i = 0; i < boneCount; i++) + SortBone(constrained.Items[i]); + + updateCache.Add(constraint); + + for (int i = 0; i < boneCount; i++) + SortReset(constrained.Items[i].children); + for (int i = 0; i < boneCount; i++) + constrained.Items[i].sorted = true; + } + + private void SortTransformConstraint (TransformConstraint constraint) { + constraint.active = constraint.target.active + && (!constraint.data.skinRequired || (skin != null && skin.constraints.Contains(constraint.data))); + if (!constraint.active) return; + + SortBone(constraint.target); + + var constrained = constraint.bones; + int boneCount = constrained.Count; + if (constraint.data.local) { + for (int i = 0; i < boneCount; i++) { + Bone child = constrained.Items[i]; + SortBone(child.parent); + if (!updateCache.Contains(child)) updateCacheReset.Add(child); + } + } else { + for (int i = 0; i < boneCount; i++) + SortBone(constrained.Items[i]); + } + + updateCache.Add(constraint); + + for (int i = 0; i < boneCount; i++) + SortReset(constrained.Items[i].children); + for (int i = 0; i < boneCount; i++) + constrained.Items[i].sorted = true; + } + + private void SortPathConstraintAttachment (Skin skin, int slotIndex, Bone slotBone) { + foreach (var entryObj in skin.Attachments.Keys) { + var entry = (Skin.SkinEntry)entryObj; + if (entry.SlotIndex == slotIndex) SortPathConstraintAttachment(entry.Attachment, slotBone); + } + } + + private void SortPathConstraintAttachment (Attachment attachment, Bone slotBone) { + if (!(attachment is PathAttachment)) return; + int[] pathBones = ((PathAttachment)attachment).bones; + if (pathBones == null) + SortBone(slotBone); + else { + var bones = this.bones; + for (int i = 0, n = pathBones.Length; i < n;) { + int nn = pathBones[i++]; + nn += i; + while (i < nn) + SortBone(bones.Items[pathBones[i++]]); + } + } + } + + private void SortBone (Bone bone) { + if (bone.sorted) return; + Bone parent = bone.parent; + if (parent != null) SortBone(parent); + bone.sorted = true; + updateCache.Add(bone); + } + + private static void SortReset (ExposedList bones) { + var bonesItems = bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) { + Bone bone = bonesItems[i]; + if (!bone.active) continue; + if (bone.sorted) SortReset(bone.children); + bone.sorted = false; + } + } + + /// Updates the world transform for each bone and applies constraints. + public void UpdateWorldTransform () { + var updateCacheReset = this.updateCacheReset; + var updateCacheResetItems = updateCacheReset.Items; + for (int i = 0, n = updateCacheReset.Count; i < n; i++) { + Bone bone = updateCacheResetItems[i]; + bone.ax = bone.x; + bone.ay = bone.y; + bone.arotation = bone.rotation; + bone.ascaleX = bone.scaleX; + bone.ascaleY = bone.scaleY; + bone.ashearX = bone.shearX; + bone.ashearY = bone.shearY; + bone.appliedValid = true; + } + var updateItems = this.updateCache.Items; + for (int i = 0, n = updateCache.Count; i < n; i++) + updateItems[i].Update(); + } + + /// + /// Temporarily sets the root bone as a child of the specified bone, then updates the world transform for each bone and applies + /// all constraints. + /// + public void UpdateWorldTransform (Bone parent) { + // This partial update avoids computing the world transform for constrained bones when 1) the bone is not updated + // before the constraint, 2) the constraint only needs to access the applied local transform, and 3) the constraint calls + // updateWorldTransform. + var updateCacheReset = this.updateCacheReset; + var updateCacheResetItems = updateCacheReset.Items; + for (int i = 0, n = updateCacheReset.Count; i < n; i++) { + Bone bone = updateCacheResetItems[i]; + bone.ax = bone.x; + bone.ay = bone.y; + bone.arotation = bone.rotation; + bone.ascaleX = bone.scaleX; + bone.ascaleY = bone.scaleY; + bone.ashearX = bone.shearX; + bone.ashearY = bone.shearY; + bone.appliedValid = true; + } + + // Apply the parent bone transform to the root bone. The root bone always inherits scale, rotation and reflection. + Bone rootBone = this.RootBone; + float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; + rootBone.worldX = pa * x + pb * y + parent.worldX; + rootBone.worldY = pc * x + pd * y + parent.worldY; + + float rotationY = rootBone.rotation + 90 + rootBone.shearY; + float la = MathUtils.CosDeg(rootBone.rotation + rootBone.shearX) * rootBone.scaleX; + float lb = MathUtils.CosDeg(rotationY) * rootBone.scaleY; + float lc = MathUtils.SinDeg(rootBone.rotation + rootBone.shearX) * rootBone.scaleX; + float ld = MathUtils.SinDeg(rotationY) * rootBone.scaleY; + rootBone.a = (pa * la + pb * lc) * scaleX; + rootBone.b = (pa * lb + pb * ld) * scaleX; + rootBone.c = (pc * la + pd * lc) * scaleY; + rootBone.d = (pc * lb + pd * ld) * scaleY; + + // Update everything except root bone. + var updateCache = this.updateCache; + var updateCacheItems = updateCache.Items; + for (int i = 0, n = updateCache.Count; i < n; i++) { + var updatable = updateCacheItems[i]; + if (updatable != rootBone) + updatable.Update(); + } + } + + /// Sets the bones, constraints, and slots to their setup pose values. + public void SetToSetupPose () { + SetBonesToSetupPose(); + SetSlotsToSetupPose(); + } + + /// Sets the bones and constraints to their setup pose values. + public void SetBonesToSetupPose () { + var bonesItems = this.bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) + bonesItems[i].SetToSetupPose(); + + var ikConstraintsItems = this.ikConstraints.Items; + for (int i = 0, n = ikConstraints.Count; i < n; i++) { + IkConstraint constraint = ikConstraintsItems[i]; + constraint.mix = constraint.data.mix; + constraint.softness = constraint.data.softness; + constraint.bendDirection = constraint.data.bendDirection; + constraint.compress = constraint.data.compress; + constraint.stretch = constraint.data.stretch; + } + + var transformConstraintsItems = this.transformConstraints.Items; + for (int i = 0, n = transformConstraints.Count; i < n; i++) { + TransformConstraint constraint = transformConstraintsItems[i]; + TransformConstraintData constraintData = constraint.data; + constraint.rotateMix = constraintData.rotateMix; + constraint.translateMix = constraintData.translateMix; + constraint.scaleMix = constraintData.scaleMix; + constraint.shearMix = constraintData.shearMix; + } + + var pathConstraintItems = this.pathConstraints.Items; + for (int i = 0, n = pathConstraints.Count; i < n; i++) { + PathConstraint constraint = pathConstraintItems[i]; + PathConstraintData constraintData = constraint.data; + constraint.position = constraintData.position; + constraint.spacing = constraintData.spacing; + constraint.rotateMix = constraintData.rotateMix; + constraint.translateMix = constraintData.translateMix; + } + } + + public void SetSlotsToSetupPose () { + var slots = this.slots; + var slotsItems = slots.Items; + drawOrder.Clear(); + for (int i = 0, n = slots.Count; i < n; i++) + drawOrder.Add(slotsItems[i]); + + for (int i = 0, n = slots.Count; i < n; i++) + slotsItems[i].SetToSetupPose(); + } + + /// May be null. + public Bone FindBone (string boneName) { + if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null."); + var bones = this.bones; + var bonesItems = bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) { + Bone bone = bonesItems[i]; + if (bone.data.name == boneName) return bone; + } + return null; + } + + /// -1 if the bone was not found. + public int FindBoneIndex (string boneName) { + if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null."); + var bones = this.bones; + var bonesItems = bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) + if (bonesItems[i].data.name == boneName) return i; + return -1; + } + + /// May be null. + public Slot FindSlot (string slotName) { + if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null."); + var slots = this.slots; + var slotsItems = slots.Items; + for (int i = 0, n = slots.Count; i < n; i++) { + Slot slot = slotsItems[i]; + if (slot.data.name == slotName) return slot; + } + return null; + } + + /// -1 if the bone was not found. + public int FindSlotIndex (string slotName) { + if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null."); + var slots = this.slots; + var slotsItems = slots.Items; + for (int i = 0, n = slots.Count; i < n; i++) + if (slotsItems[i].data.name.Equals(slotName)) return i; + return -1; + } + + /// Sets a skin by name (see SetSkin). + public void SetSkin (string skinName) { + Skin foundSkin = data.FindSkin(skinName); + if (foundSkin == null) throw new ArgumentException("Skin not found: " + skinName, "skinName"); + SetSkin(foundSkin); + } + + /// + /// Sets the skin used to look up attachments before looking in the . If the + /// skin is changed, is called. + /// + /// Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. + /// If there was no old skin, each slot's setup mode attachment is attached from the new skin. + /// + /// After changing the skin, the visible attachments can be reset to those attached in the setup pose by calling + /// . + /// Also, often is called before the next time the + /// skeleton is rendered to allow any attachment keys in the current animation(s) to hide or show attachments from the new skin. + /// + /// May be null. + public void SetSkin (Skin newSkin) { + if (newSkin == skin) return; + if (newSkin != null) { + if (skin != null) + newSkin.AttachAll(this, skin); + else { + ExposedList slots = this.slots; + for (int i = 0, n = slots.Count; i < n; i++) { + Slot slot = slots.Items[i]; + string name = slot.data.attachmentName; + if (name != null) { + Attachment attachment = newSkin.GetAttachment(i, name); + if (attachment != null) slot.Attachment = attachment; + } + } + } + } + skin = newSkin; + UpdateCache(); + } + + /// Finds an attachment by looking in the {@link #skin} and {@link SkeletonData#defaultSkin} using the slot name and attachment name. + /// May be null. + public Attachment GetAttachment (string slotName, string attachmentName) { + return GetAttachment(data.FindSlotIndex(slotName), attachmentName); + } + + /// Finds an attachment by looking in the skin and skeletonData.defaultSkin using the slot index and attachment name.First the skin is checked and if the attachment was not found, the default skin is checked. + /// May be null. + public Attachment GetAttachment (int slotIndex, string attachmentName) { + if (attachmentName == null) throw new ArgumentNullException("attachmentName", "attachmentName cannot be null."); + if (skin != null) { + Attachment attachment = skin.GetAttachment(slotIndex, attachmentName); + if (attachment != null) return attachment; + } + return data.defaultSkin != null ? data.defaultSkin.GetAttachment(slotIndex, attachmentName) : null; + } + + /// A convenience method to set an attachment by finding the slot with FindSlot, finding the attachment with GetAttachment, then setting the slot's slot.Attachment. + /// May be null to clear the slot's attachment. + public void SetAttachment (string slotName, string attachmentName) { + if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null."); + ExposedList slots = this.slots; + for (int i = 0, n = slots.Count; i < n; i++) { + Slot slot = slots.Items[i]; + if (slot.data.name == slotName) { + Attachment attachment = null; + if (attachmentName != null) { + attachment = GetAttachment(i, attachmentName); + if (attachment == null) throw new Exception("Attachment not found: " + attachmentName + ", for slot: " + slotName); + } + slot.Attachment = attachment; + return; + } + } + throw new Exception("Slot not found: " + slotName); + } + + /// May be null. + public IkConstraint FindIkConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList ikConstraints = this.ikConstraints; + for (int i = 0, n = ikConstraints.Count; i < n; i++) { + IkConstraint ikConstraint = ikConstraints.Items[i]; + if (ikConstraint.data.name == constraintName) return ikConstraint; + } + return null; + } + + /// May be null. + public TransformConstraint FindTransformConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList transformConstraints = this.transformConstraints; + for (int i = 0, n = transformConstraints.Count; i < n; i++) { + TransformConstraint transformConstraint = transformConstraints.Items[i]; + if (transformConstraint.data.Name == constraintName) return transformConstraint; + } + return null; + } + + /// May be null. + public PathConstraint FindPathConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList pathConstraints = this.pathConstraints; + for (int i = 0, n = pathConstraints.Count; i < n; i++) { + PathConstraint constraint = pathConstraints.Items[i]; + if (constraint.data.Name.Equals(constraintName)) return constraint; + } + return null; + } + + public void Update (float delta) { + time += delta; + } + + /// Returns the axis aligned bounding box (AABB) of the region and mesh attachments for the current pose. + /// The horizontal distance between the skeleton origin and the left side of the AABB. + /// The vertical distance between the skeleton origin and the bottom side of the AABB. + /// The width of the AABB + /// The height of the AABB. + /// Reference to hold a float[]. May be a null reference. This method will assign it a new float[] with the appropriate size as needed. + public void GetBounds (out float x, out float y, out float width, out float height, ref float[] vertexBuffer) { + float[] temp = vertexBuffer; + temp = temp ?? new float[8]; + var drawOrderItems = this.drawOrder.Items; + float minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + for (int i = 0, n = drawOrderItems.Length; i < n; i++) { + Slot slot = drawOrderItems[i]; + if (!slot.bone.active) continue; + int verticesLength = 0; + float[] vertices = null; + Attachment attachment = slot.attachment; + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) { + verticesLength = 8; + vertices = temp; + if (vertices.Length < 8) vertices = temp = new float[8]; + regionAttachment.ComputeWorldVertices(slot.bone, temp, 0); + } else { + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + MeshAttachment mesh = meshAttachment; + verticesLength = mesh.WorldVerticesLength; + vertices = temp; + if (vertices.Length < verticesLength) vertices = temp = new float[verticesLength]; + mesh.ComputeWorldVertices(slot, 0, verticesLength, temp, 0); + } + } + + if (vertices != null) { + for (int ii = 0; ii < verticesLength; ii += 2) { + float vx = vertices[ii], vy = vertices[ii + 1]; + minX = Math.Min(minX, vx); + minY = Math.Min(minY, vy); + maxX = Math.Max(maxX, vx); + maxY = Math.Max(maxY, vy); + } + } + } + x = minX; + y = minY; + width = maxX - minX; + height = maxY - minY; + vertexBuffer = temp; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs.meta new file mode 100644 index 0000000..619d2cc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skeleton.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 12ac3c1c7546be24fb9625d3c850619d +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs new file mode 100644 index 0000000..810c22b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs @@ -0,0 +1,997 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1) +#define IS_UNITY +#endif + +using System; +using System.IO; +using System.Collections.Generic; + +#if WINDOWS_STOREAPP +using System.Threading.Tasks; +using Windows.Storage; +#endif + +namespace Spine { + public class SkeletonBinary { + public const int BONE_ROTATE = 0; + public const int BONE_TRANSLATE = 1; + public const int BONE_SCALE = 2; + public const int BONE_SHEAR = 3; + + public const int SLOT_ATTACHMENT = 0; + public const int SLOT_COLOR = 1; + public const int SLOT_TWO_COLOR = 2; + + public const int PATH_POSITION = 0; + public const int PATH_SPACING = 1; + public const int PATH_MIX = 2; + + public const int CURVE_LINEAR = 0; + public const int CURVE_STEPPED = 1; + public const int CURVE_BEZIER = 2; + + public float Scale { get; set; } + + private AttachmentLoader attachmentLoader; + private List linkedMeshes = new List(); + + public SkeletonBinary (params Atlas[] atlasArray) + : this(new AtlasAttachmentLoader(atlasArray)) { + } + + public SkeletonBinary (AttachmentLoader attachmentLoader) { + if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader"); + this.attachmentLoader = attachmentLoader; + Scale = 1; + } + + #if !ISUNITY && WINDOWS_STOREAPP + private async Task ReadFile(string path) { + var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; + using (var input = new BufferedStream(await folder.GetFileAsync(path).AsTask().ConfigureAwait(false))) { + SkeletonData skeletonData = ReadSkeletonData(input); + skeletonData.Name = Path.GetFileNameWithoutExtension(path); + return skeletonData; + } + } + + public SkeletonData ReadSkeletonData (String path) { + return this.ReadFile(path).Result; + } + #else + public SkeletonData ReadSkeletonData (String path) { + #if WINDOWS_PHONE + using (var input = new BufferedStream(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { + #else + using (var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { + #endif + SkeletonData skeletonData = ReadSkeletonData(input); + skeletonData.name = Path.GetFileNameWithoutExtension(path); + return skeletonData; + } + } + #endif // WINDOWS_STOREAPP + + public static readonly TransformMode[] TransformModeValues = { + TransformMode.Normal, + TransformMode.OnlyTranslation, + TransformMode.NoRotationOrReflection, + TransformMode.NoScale, + TransformMode.NoScaleOrReflection + }; + + /// Returns the version string of binary skeleton data. + public static string GetVersionString (Stream file) { + if (file == null) throw new ArgumentNullException("file"); + + SkeletonInput input = new SkeletonInput(file); + return input.GetVersionString(); + } + + public SkeletonData ReadSkeletonData (Stream file) { + if (file == null) throw new ArgumentNullException("file"); + float scale = Scale; + + var skeletonData = new SkeletonData(); + SkeletonInput input = new SkeletonInput(file); + + skeletonData.hash = input.ReadString(); + if (skeletonData.hash.Length == 0) skeletonData.hash = null; + skeletonData.version = input.ReadString(); + if (skeletonData.version.Length == 0) skeletonData.version = null; + if ("3.8.75" == skeletonData.version) + throw new Exception("Unsupported skeleton data, please export with a newer version of Spine."); + skeletonData.x = input.ReadFloat(); + skeletonData.y = input.ReadFloat(); + skeletonData.width = input.ReadFloat(); + skeletonData.height = input.ReadFloat(); + + bool nonessential = input.ReadBoolean(); + + if (nonessential) { + skeletonData.fps = input.ReadFloat(); + + skeletonData.imagesPath = input.ReadString(); + if (string.IsNullOrEmpty(skeletonData.imagesPath)) skeletonData.imagesPath = null; + + skeletonData.audioPath = input.ReadString(); + if (string.IsNullOrEmpty(skeletonData.audioPath)) skeletonData.audioPath = null; + } + + int n; + Object[] o; + + // Strings. + input.strings = new ExposedList(n = input.ReadInt(true)); + o = input.strings.Resize(n).Items; + for (int i = 0; i < n; i++) + o[i] = input.ReadString(); + + // Bones. + o = skeletonData.bones.Resize(n = input.ReadInt(true)).Items; + for (int i = 0; i < n; i++) { + String name = input.ReadString(); + BoneData parent = i == 0 ? null : skeletonData.bones.Items[input.ReadInt(true)]; + BoneData data = new BoneData(i, name, parent); + data.rotation = input.ReadFloat(); + data.x = input.ReadFloat() * scale; + data.y = input.ReadFloat() * scale; + data.scaleX = input.ReadFloat(); + data.scaleY = input.ReadFloat(); + data.shearX = input.ReadFloat(); + data.shearY = input.ReadFloat(); + data.length = input.ReadFloat() * scale; + data.transformMode = TransformModeValues[input.ReadInt(true)]; + data.skinRequired = input.ReadBoolean(); + if (nonessential) input.ReadInt(); // Skip bone color. + o[i] = data; + } + + // Slots. + o = skeletonData.slots.Resize(n = input.ReadInt(true)).Items; + for (int i = 0; i < n; i++) { + String slotName = input.ReadString(); + BoneData boneData = skeletonData.bones.Items[input.ReadInt(true)]; + SlotData slotData = new SlotData(i, slotName, boneData); + int color = input.ReadInt(); + slotData.r = ((color & 0xff000000) >> 24) / 255f; + slotData.g = ((color & 0x00ff0000) >> 16) / 255f; + slotData.b = ((color & 0x0000ff00) >> 8) / 255f; + slotData.a = ((color & 0x000000ff)) / 255f; + + int darkColor = input.ReadInt(); // 0x00rrggbb + if (darkColor != -1) { + slotData.hasSecondColor = true; + slotData.r2 = ((darkColor & 0x00ff0000) >> 16) / 255f; + slotData.g2 = ((darkColor & 0x0000ff00) >> 8) / 255f; + slotData.b2 = ((darkColor & 0x000000ff)) / 255f; + } + + slotData.attachmentName = input.ReadStringRef(); + slotData.blendMode = (BlendMode)input.ReadInt(true); + o[i] = slotData; + } + + // IK constraints. + o = skeletonData.ikConstraints.Resize(n = input.ReadInt(true)).Items; + for (int i = 0, nn; i < n; i++) { + IkConstraintData data = new IkConstraintData(input.ReadString()); + data.order = input.ReadInt(true); + data.skinRequired = input.ReadBoolean(); + Object[] bones = data.bones.Resize(nn = input.ReadInt(true)).Items; + for (int ii = 0; ii < nn; ii++) + bones[ii] = skeletonData.bones.Items[input.ReadInt(true)]; + data.target = skeletonData.bones.Items[input.ReadInt(true)]; + data.mix = input.ReadFloat(); + data.softness = input.ReadFloat() * scale; + data.bendDirection = input.ReadSByte(); + data.compress = input.ReadBoolean(); + data.stretch = input.ReadBoolean(); + data.uniform = input.ReadBoolean(); + o[i] = data; + } + + // Transform constraints. + o = skeletonData.transformConstraints.Resize(n = input.ReadInt(true)).Items; + for (int i = 0, nn; i < n; i++) { + TransformConstraintData data = new TransformConstraintData(input.ReadString()); + data.order = input.ReadInt(true); + data.skinRequired = input.ReadBoolean(); + Object[] bones = data.bones.Resize(nn = input.ReadInt(true)).Items; + for (int ii = 0; ii < nn; ii++) + bones[ii] = skeletonData.bones.Items[input.ReadInt(true)]; + data.target = skeletonData.bones.Items[input.ReadInt(true)]; + data.local = input.ReadBoolean(); + data.relative = input.ReadBoolean(); + data.offsetRotation = input.ReadFloat(); + data.offsetX = input.ReadFloat() * scale; + data.offsetY = input.ReadFloat() * scale; + data.offsetScaleX = input.ReadFloat(); + data.offsetScaleY = input.ReadFloat(); + data.offsetShearY = input.ReadFloat(); + data.rotateMix = input.ReadFloat(); + data.translateMix = input.ReadFloat(); + data.scaleMix = input.ReadFloat(); + data.shearMix = input.ReadFloat(); + o[i] = data; + } + + // Path constraints + o = skeletonData.pathConstraints.Resize(n = input.ReadInt(true)).Items; + for (int i = 0, nn; i < n; i++) { + PathConstraintData data = new PathConstraintData(input.ReadString()); + data.order = input.ReadInt(true); + data.skinRequired = input.ReadBoolean(); + Object[] bones = data.bones.Resize(nn = input.ReadInt(true)).Items; + for (int ii = 0; ii < nn; ii++) + bones[ii] = skeletonData.bones.Items[input.ReadInt(true)]; + data.target = skeletonData.slots.Items[input.ReadInt(true)]; + data.positionMode = (PositionMode)Enum.GetValues(typeof(PositionMode)).GetValue(input.ReadInt(true)); + data.spacingMode = (SpacingMode)Enum.GetValues(typeof(SpacingMode)).GetValue(input.ReadInt(true)); + data.rotateMode = (RotateMode)Enum.GetValues(typeof(RotateMode)).GetValue(input.ReadInt(true)); + data.offsetRotation = input.ReadFloat(); + data.position = input.ReadFloat(); + if (data.positionMode == PositionMode.Fixed) data.position *= scale; + data.spacing = input.ReadFloat(); + if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale; + data.rotateMix = input.ReadFloat(); + data.translateMix = input.ReadFloat(); + o[i] = data; + } + + // Default skin. + Skin defaultSkin = ReadSkin(input, skeletonData, true, nonessential); + if (defaultSkin != null) { + skeletonData.defaultSkin = defaultSkin; + skeletonData.skins.Add(defaultSkin); + } + + // Skins. + { + int i = skeletonData.skins.Count; + o = skeletonData.skins.Resize(n = i + input.ReadInt(true)).Items; + for (; i < n; i++) + o[i] = ReadSkin(input, skeletonData, false, nonessential); + } + + // Linked meshes. + n = linkedMeshes.Count; + for (int i = 0; i < n; i++) { + SkeletonJson.LinkedMesh linkedMesh = linkedMeshes[i]; + Skin skin = linkedMesh.skin == null ? skeletonData.DefaultSkin : skeletonData.FindSkin(linkedMesh.skin); + if (skin == null) throw new Exception("Skin not found: " + linkedMesh.skin); + Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent); + if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent); + linkedMesh.mesh.DeformAttachment = linkedMesh.inheritDeform ? (VertexAttachment)parent : linkedMesh.mesh; + linkedMesh.mesh.ParentMesh = (MeshAttachment)parent; + linkedMesh.mesh.UpdateUVs(); + } + linkedMeshes.Clear(); + + // Events. + o = skeletonData.events.Resize(n = input.ReadInt(true)).Items; + for (int i = 0; i < n; i++) { + EventData data = new EventData(input.ReadStringRef()); + data.Int = input.ReadInt(false); + data.Float = input.ReadFloat(); + data.String = input.ReadString(); + data.AudioPath = input.ReadString(); + if (data.AudioPath != null) { + data.Volume = input.ReadFloat(); + data.Balance = input.ReadFloat(); + } + o[i] = data; + } + + // Animations. + o = skeletonData.animations.Resize(n = input.ReadInt(true)).Items; + for (int i = 0; i < n; i++) + o[i] = ReadAnimation(input.ReadString(), input, skeletonData); + + return skeletonData; + } + + + /// May be null. + private Skin ReadSkin (SkeletonInput input, SkeletonData skeletonData, bool defaultSkin, bool nonessential) { + + Skin skin; + int slotCount; + + if (defaultSkin) { + slotCount = input.ReadInt(true); + if (slotCount == 0) return null; + skin = new Skin("default"); + } else { + skin = new Skin(input.ReadStringRef()); + Object[] bones = skin.bones.Resize(input.ReadInt(true)).Items; + for (int i = 0, n = skin.bones.Count; i < n; i++) + bones[i] = skeletonData.bones.Items[input.ReadInt(true)]; + + for (int i = 0, n = input.ReadInt(true); i < n; i++) + skin.constraints.Add(skeletonData.ikConstraints.Items[input.ReadInt(true)]); + for (int i = 0, n = input.ReadInt(true); i < n; i++) + skin.constraints.Add(skeletonData.transformConstraints.Items[input.ReadInt(true)]); + for (int i = 0, n = input.ReadInt(true); i < n; i++) + skin.constraints.Add(skeletonData.pathConstraints.Items[input.ReadInt(true)]); + skin.constraints.TrimExcess(); + slotCount = input.ReadInt(true); + } + for (int i = 0; i < slotCount; i++) { + int slotIndex = input.ReadInt(true); + for (int ii = 0, nn = input.ReadInt(true); ii < nn; ii++) { + String name = input.ReadStringRef(); + Attachment attachment = ReadAttachment(input, skeletonData, skin, slotIndex, name, nonessential); + if (attachment != null) skin.SetAttachment(slotIndex, name, attachment); + } + } + return skin; + } + + private Attachment ReadAttachment (SkeletonInput input, SkeletonData skeletonData, Skin skin, int slotIndex, + String attachmentName, bool nonessential) { + + float scale = Scale; + + String name = input.ReadStringRef(); + if (name == null) name = attachmentName; + + AttachmentType type = (AttachmentType)input.ReadByte(); + switch (type) { + case AttachmentType.Region: { + String path = input.ReadStringRef(); + float rotation = input.ReadFloat(); + float x = input.ReadFloat(); + float y = input.ReadFloat(); + float scaleX = input.ReadFloat(); + float scaleY = input.ReadFloat(); + float width = input.ReadFloat(); + float height = input.ReadFloat(); + int color = input.ReadInt(); + + if (path == null) path = name; + RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path); + if (region == null) return null; + region.Path = path; + region.x = x * scale; + region.y = y * scale; + region.scaleX = scaleX; + region.scaleY = scaleY; + region.rotation = rotation; + region.width = width * scale; + region.height = height * scale; + region.r = ((color & 0xff000000) >> 24) / 255f; + region.g = ((color & 0x00ff0000) >> 16) / 255f; + region.b = ((color & 0x0000ff00) >> 8) / 255f; + region.a = ((color & 0x000000ff)) / 255f; + region.UpdateOffset(); + return region; + } + case AttachmentType.Boundingbox: { + int vertexCount = input.ReadInt(true); + Vertices vertices = ReadVertices(input, vertexCount); + if (nonessential) input.ReadInt(); //int color = nonessential ? input.ReadInt() : 0; // Avoid unused local warning. + + BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name); + if (box == null) return null; + box.worldVerticesLength = vertexCount << 1; + box.vertices = vertices.vertices; + box.bones = vertices.bones; + // skipped porting: if (nonessential) Color.rgba8888ToColor(box.getColor(), color); + return box; + } + case AttachmentType.Mesh: { + String path = input.ReadStringRef(); + int color = input.ReadInt(); + int vertexCount = input.ReadInt(true); + float[] uvs = ReadFloatArray(input, vertexCount << 1, 1); + int[] triangles = ReadShortArray(input); + Vertices vertices = ReadVertices(input, vertexCount); + int hullLength = input.ReadInt(true); + int[] edges = null; + float width = 0, height = 0; + if (nonessential) { + edges = ReadShortArray(input); + width = input.ReadFloat(); + height = input.ReadFloat(); + } + + if (path == null) path = name; + MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); + if (mesh == null) return null; + mesh.Path = path; + mesh.r = ((color & 0xff000000) >> 24) / 255f; + mesh.g = ((color & 0x00ff0000) >> 16) / 255f; + mesh.b = ((color & 0x0000ff00) >> 8) / 255f; + mesh.a = ((color & 0x000000ff)) / 255f; + mesh.bones = vertices.bones; + mesh.vertices = vertices.vertices; + mesh.WorldVerticesLength = vertexCount << 1; + mesh.triangles = triangles; + mesh.regionUVs = uvs; + mesh.UpdateUVs(); + mesh.HullLength = hullLength << 1; + if (nonessential) { + mesh.Edges = edges; + mesh.Width = width * scale; + mesh.Height = height * scale; + } + return mesh; + } + case AttachmentType.Linkedmesh: { + String path = input.ReadStringRef(); + int color = input.ReadInt(); + String skinName = input.ReadStringRef(); + String parent = input.ReadStringRef(); + bool inheritDeform = input.ReadBoolean(); + float width = 0, height = 0; + if (nonessential) { + width = input.ReadFloat(); + height = input.ReadFloat(); + } + + if (path == null) path = name; + MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); + if (mesh == null) return null; + mesh.Path = path; + mesh.r = ((color & 0xff000000) >> 24) / 255f; + mesh.g = ((color & 0x00ff0000) >> 16) / 255f; + mesh.b = ((color & 0x0000ff00) >> 8) / 255f; + mesh.a = ((color & 0x000000ff)) / 255f; + if (nonessential) { + mesh.Width = width * scale; + mesh.Height = height * scale; + } + linkedMeshes.Add(new SkeletonJson.LinkedMesh(mesh, skinName, slotIndex, parent, inheritDeform)); + return mesh; + } + case AttachmentType.Path: { + bool closed = input.ReadBoolean(); + bool constantSpeed = input.ReadBoolean(); + int vertexCount = input.ReadInt(true); + Vertices vertices = ReadVertices(input, vertexCount); + float[] lengths = new float[vertexCount / 3]; + for (int i = 0, n = lengths.Length; i < n; i++) + lengths[i] = input.ReadFloat() * scale; + if (nonessential) input.ReadInt(); //int color = nonessential ? input.ReadInt() : 0; + + PathAttachment path = attachmentLoader.NewPathAttachment(skin, name); + if (path == null) return null; + path.closed = closed; + path.constantSpeed = constantSpeed; + path.worldVerticesLength = vertexCount << 1; + path.vertices = vertices.vertices; + path.bones = vertices.bones; + path.lengths = lengths; + // skipped porting: if (nonessential) Color.rgba8888ToColor(path.getColor(), color); + return path; + } + case AttachmentType.Point: { + float rotation = input.ReadFloat(); + float x = input.ReadFloat(); + float y = input.ReadFloat(); + if (nonessential) input.ReadInt(); //int color = nonessential ? input.ReadInt() : 0; + + PointAttachment point = attachmentLoader.NewPointAttachment(skin, name); + if (point == null) return null; + point.x = x * scale; + point.y = y * scale; + point.rotation = rotation; + // skipped porting: if (nonessential) point.color = color; + return point; + } + case AttachmentType.Clipping: { + int endSlotIndex = input.ReadInt(true); + int vertexCount = input.ReadInt(true); + Vertices vertices = ReadVertices(input, vertexCount); + if (nonessential) input.ReadInt(); + + ClippingAttachment clip = attachmentLoader.NewClippingAttachment(skin, name); + if (clip == null) return null; + clip.EndSlot = skeletonData.slots.Items[endSlotIndex]; + clip.worldVerticesLength = vertexCount << 1; + clip.vertices = vertices.vertices; + clip.bones = vertices.bones; + // skipped porting: if (nonessential) Color.rgba8888ToColor(clip.getColor(), color); + return clip; + } + } + return null; + } + + private Vertices ReadVertices (SkeletonInput input, int vertexCount) { + float scale = Scale; + int verticesLength = vertexCount << 1; + Vertices vertices = new Vertices(); + if(!input.ReadBoolean()) { + vertices.vertices = ReadFloatArray(input, verticesLength, scale); + return vertices; + } + var weights = new ExposedList(verticesLength * 3 * 3); + var bonesArray = new ExposedList(verticesLength * 3); + for (int i = 0; i < vertexCount; i++) { + int boneCount = input.ReadInt(true); + bonesArray.Add(boneCount); + for (int ii = 0; ii < boneCount; ii++) { + bonesArray.Add(input.ReadInt(true)); + weights.Add(input.ReadFloat() * scale); + weights.Add(input.ReadFloat() * scale); + weights.Add(input.ReadFloat()); + } + } + + vertices.vertices = weights.ToArray(); + vertices.bones = bonesArray.ToArray(); + return vertices; + } + + private float[] ReadFloatArray (SkeletonInput input, int n, float scale) { + float[] array = new float[n]; + if (scale == 1) { + for (int i = 0; i < n; i++) + array[i] = input.ReadFloat(); + } else { + for (int i = 0; i < n; i++) + array[i] = input.ReadFloat() * scale; + } + return array; + } + + private int[] ReadShortArray (SkeletonInput input) { + int n = input.ReadInt(true); + int[] array = new int[n]; + for (int i = 0; i < n; i++) + array[i] = (input.ReadByte() << 8) | input.ReadByte(); + return array; + } + + private Animation ReadAnimation (String name, SkeletonInput input, SkeletonData skeletonData) { + var timelines = new ExposedList(32); + float scale = Scale; + float duration = 0; + + // Slot timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + int slotIndex = input.ReadInt(true); + for (int ii = 0, nn = input.ReadInt(true); ii < nn; ii++) { + int timelineType = input.ReadByte(); + int frameCount = input.ReadInt(true); + switch (timelineType) { + case SLOT_ATTACHMENT: { + AttachmentTimeline timeline = new AttachmentTimeline(frameCount); + timeline.slotIndex = slotIndex; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadStringRef()); + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[frameCount - 1]); + break; + } + case SLOT_COLOR: { + ColorTimeline timeline = new ColorTimeline(frameCount); + timeline.slotIndex = slotIndex; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + float time = input.ReadFloat(); + int color = input.ReadInt(); + float r = ((color & 0xff000000) >> 24) / 255f; + float g = ((color & 0x00ff0000) >> 16) / 255f; + float b = ((color & 0x0000ff00) >> 8) / 255f; + float a = ((color & 0x000000ff)) / 255f; + timeline.SetFrame(frameIndex, time, r, g, b, a); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * ColorTimeline.ENTRIES]); + break; + } + case SLOT_TWO_COLOR: { + TwoColorTimeline timeline = new TwoColorTimeline(frameCount); + timeline.slotIndex = slotIndex; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + float time = input.ReadFloat(); + int color = input.ReadInt(); + float r = ((color & 0xff000000) >> 24) / 255f; + float g = ((color & 0x00ff0000) >> 16) / 255f; + float b = ((color & 0x0000ff00) >> 8) / 255f; + float a = ((color & 0x000000ff)) / 255f; + int color2 = input.ReadInt(); // 0x00rrggbb + float r2 = ((color2 & 0x00ff0000) >> 16) / 255f; + float g2 = ((color2 & 0x0000ff00) >> 8) / 255f; + float b2 = ((color2 & 0x000000ff)) / 255f; + + timeline.SetFrame(frameIndex, time, r, g, b, a, r2, g2, b2); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TwoColorTimeline.ENTRIES]); + break; + } + } + } + } + + // Bone timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + int boneIndex = input.ReadInt(true); + for (int ii = 0, nn = input.ReadInt(true); ii < nn; ii++) { + int timelineType = input.ReadByte(); + int frameCount = input.ReadInt(true); + switch (timelineType) { + case BONE_ROTATE: { + RotateTimeline timeline = new RotateTimeline(frameCount); + timeline.boneIndex = boneIndex; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat()); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * RotateTimeline.ENTRIES]); + break; + } + case BONE_TRANSLATE: + case BONE_SCALE: + case BONE_SHEAR: { + TranslateTimeline timeline; + float timelineScale = 1; + if (timelineType == BONE_SCALE) + timeline = new ScaleTimeline(frameCount); + else if (timelineType == BONE_SHEAR) + timeline = new ShearTimeline(frameCount); + else { + timeline = new TranslateTimeline(frameCount); + timelineScale = scale; + } + timeline.boneIndex = boneIndex; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat() * timelineScale, + input.ReadFloat() * timelineScale); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TranslateTimeline.ENTRIES]); + break; + } + } + } + } + + // IK constraint timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + int index = input.ReadInt(true); + int frameCount = input.ReadInt(true); + IkConstraintTimeline timeline = new IkConstraintTimeline(frameCount) { + ikConstraintIndex = index + }; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat(), input.ReadFloat() * scale, input.ReadSByte(), input.ReadBoolean(), + input.ReadBoolean()); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * IkConstraintTimeline.ENTRIES]); + } + + // Transform constraint timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + int index = input.ReadInt(true); + int frameCount = input.ReadInt(true); + TransformConstraintTimeline timeline = new TransformConstraintTimeline(frameCount); + timeline.transformConstraintIndex = index; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat(), input.ReadFloat(), input.ReadFloat(), + input.ReadFloat()); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TransformConstraintTimeline.ENTRIES]); + } + + // Path constraint timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + int index = input.ReadInt(true); + PathConstraintData data = skeletonData.pathConstraints.Items[index]; + for (int ii = 0, nn = input.ReadInt(true); ii < nn; ii++) { + int timelineType = input.ReadSByte(); + int frameCount = input.ReadInt(true); + switch(timelineType) { + case PATH_POSITION: + case PATH_SPACING: { + PathConstraintPositionTimeline timeline; + float timelineScale = 1; + if (timelineType == PATH_SPACING) { + timeline = new PathConstraintSpacingTimeline(frameCount); + if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) timelineScale = scale; + } else { + timeline = new PathConstraintPositionTimeline(frameCount); + if (data.positionMode == PositionMode.Fixed) timelineScale = scale; + } + timeline.pathConstraintIndex = index; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat() * timelineScale); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintPositionTimeline.ENTRIES]); + break; + } + case PATH_MIX: { + PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(frameCount); + timeline.pathConstraintIndex = index; + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + timeline.SetFrame(frameIndex, input.ReadFloat(), input.ReadFloat(), input.ReadFloat()); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintMixTimeline.ENTRIES]); + break; + } + } + } + } + + // Deform timelines. + for (int i = 0, n = input.ReadInt(true); i < n; i++) { + Skin skin = skeletonData.skins.Items[input.ReadInt(true)]; + for (int ii = 0, nn = input.ReadInt(true); ii < nn; ii++) { + int slotIndex = input.ReadInt(true); + for (int iii = 0, nnn = input.ReadInt(true); iii < nnn; iii++) { + VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, input.ReadStringRef()); + bool weighted = attachment.bones != null; + float[] vertices = attachment.vertices; + int deformLength = weighted ? vertices.Length / 3 * 2 : vertices.Length; + + int frameCount = input.ReadInt(true); + DeformTimeline timeline = new DeformTimeline(frameCount); + timeline.slotIndex = slotIndex; + timeline.attachment = attachment; + + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { + float time = input.ReadFloat(); + float[] deform; + int end = input.ReadInt(true); + if (end == 0) + deform = weighted ? new float[deformLength] : vertices; + else { + deform = new float[deformLength]; + int start = input.ReadInt(true); + end += start; + if (scale == 1) { + for (int v = start; v < end; v++) + deform[v] = input.ReadFloat(); + } else { + for (int v = start; v < end; v++) + deform[v] = input.ReadFloat() * scale; + } + if (!weighted) { + for (int v = 0, vn = deform.Length; v < vn; v++) + deform[v] += vertices[v]; + } + } + + timeline.SetFrame(frameIndex, time, deform); + if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[frameCount - 1]); + } + } + } + + // Draw order timeline. + int drawOrderCount = input.ReadInt(true); + if (drawOrderCount > 0) { + DrawOrderTimeline timeline = new DrawOrderTimeline(drawOrderCount); + int slotCount = skeletonData.slots.Count; + for (int i = 0; i < drawOrderCount; i++) { + float time = input.ReadFloat(); + int offsetCount = input.ReadInt(true); + int[] drawOrder = new int[slotCount]; + for (int ii = slotCount - 1; ii >= 0; ii--) + drawOrder[ii] = -1; + int[] unchanged = new int[slotCount - offsetCount]; + int originalIndex = 0, unchangedIndex = 0; + for (int ii = 0; ii < offsetCount; ii++) { + int slotIndex = input.ReadInt(true); + // Collect unchanged items. + while (originalIndex != slotIndex) + unchanged[unchangedIndex++] = originalIndex++; + // Set changed items. + drawOrder[originalIndex + input.ReadInt(true)] = originalIndex++; + } + // Collect remaining unchanged items. + while (originalIndex < slotCount) + unchanged[unchangedIndex++] = originalIndex++; + // Fill in unchanged items. + for (int ii = slotCount - 1; ii >= 0; ii--) + if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex]; + timeline.SetFrame(i, time, drawOrder); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[drawOrderCount - 1]); + } + + // Event timeline. + int eventCount = input.ReadInt(true); + if (eventCount > 0) { + EventTimeline timeline = new EventTimeline(eventCount); + for (int i = 0; i < eventCount; i++) { + float time = input.ReadFloat(); + EventData eventData = skeletonData.events.Items[input.ReadInt(true)]; + Event e = new Event(time, eventData) { + Int = input.ReadInt(false), + Float = input.ReadFloat(), + String = input.ReadBoolean() ? input.ReadString() : eventData.String + }; + if (e.data.AudioPath != null) { + e.volume = input.ReadFloat(); + e.balance = input.ReadFloat(); + } + timeline.SetFrame(i, e); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[eventCount - 1]); + } + + timelines.TrimExcess(); + return new Animation(name, timelines, duration); + } + + private void ReadCurve (SkeletonInput input, int frameIndex, CurveTimeline timeline) { + switch (input.ReadByte()) { + case CURVE_STEPPED: + timeline.SetStepped(frameIndex); + break; + case CURVE_BEZIER: + timeline.SetCurve(frameIndex, input.ReadFloat(), input.ReadFloat(), input.ReadFloat(), input.ReadFloat()); + break; + } + } + + internal class Vertices + { + public int[] bones; + public float[] vertices; + } + + internal class SkeletonInput { + private byte[] chars = new byte[32]; + private byte[] bytesBigEndian = new byte[4]; + internal ExposedList strings; + Stream input; + + public SkeletonInput (Stream input) { + this.input = input; + } + + public byte ReadByte () { + return (byte)input.ReadByte(); + } + + public sbyte ReadSByte () { + int value = input.ReadByte(); + if (value == -1) throw new EndOfStreamException(); + return (sbyte)value; + } + + public bool ReadBoolean () { + return input.ReadByte() != 0; + } + + public float ReadFloat () { + input.Read(bytesBigEndian, 0, 4); + chars[3] = bytesBigEndian[0]; + chars[2] = bytesBigEndian[1]; + chars[1] = bytesBigEndian[2]; + chars[0] = bytesBigEndian[3]; + return BitConverter.ToSingle(chars, 0); + } + + public int ReadInt () { + input.Read(bytesBigEndian, 0, 4); + return (bytesBigEndian[0] << 24) + + (bytesBigEndian[1] << 16) + + (bytesBigEndian[2] << 8) + + bytesBigEndian[3]; + } + + public int ReadInt (bool optimizePositive) { + int b = input.ReadByte(); + int result = b & 0x7F; + if ((b & 0x80) != 0) { + b = input.ReadByte(); + result |= (b & 0x7F) << 7; + if ((b & 0x80) != 0) { + b = input.ReadByte(); + result |= (b & 0x7F) << 14; + if ((b & 0x80) != 0) { + b = input.ReadByte(); + result |= (b & 0x7F) << 21; + if ((b & 0x80) != 0) result |= (input.ReadByte() & 0x7F) << 28; + } + } + } + return optimizePositive ? result : ((result >> 1) ^ -(result & 1)); + } + + public string ReadString () { + int byteCount = ReadInt(true); + switch (byteCount) { + case 0: + return null; + case 1: + return ""; + } + byteCount--; + byte[] buffer = this.chars; + if (buffer.Length < byteCount) buffer = new byte[byteCount]; + ReadFully(buffer, 0, byteCount); + return System.Text.Encoding.UTF8.GetString(buffer, 0, byteCount); + } + + ///May be null. + public String ReadStringRef () { + int index = ReadInt(true); + return index == 0 ? null : strings.Items[index - 1]; + } + + public void ReadFully (byte[] buffer, int offset, int length) { + while (length > 0) { + int count = input.Read(buffer, offset, length); + if (count <= 0) throw new EndOfStreamException(); + offset += count; + length -= count; + } + } + + /// Returns the version string of binary skeleton data. + public string GetVersionString () { + try { + // Hash. + int byteCount = ReadInt(true); + if (byteCount > 1) input.Position += byteCount - 1; + + // Version. + byteCount = ReadInt(true); + if (byteCount > 1) { + byteCount--; + var buffer = new byte[byteCount]; + ReadFully(buffer, 0, byteCount); + return System.Text.Encoding.UTF8.GetString(buffer, 0, byteCount); + } + + throw new ArgumentException("Stream does not contain a valid binary Skeleton Data.", "input"); + } catch (Exception e) { + throw new ArgumentException("Stream does not contain a valid binary Skeleton Data.\n" + e, "input"); + } + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs.meta new file mode 100644 index 0000000..fd3aabc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBinary.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 40d8a8f15082f3844a5c9c8c3ef2047f +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs new file mode 100644 index 0000000..fe24736 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs @@ -0,0 +1,234 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + + /// + /// Collects each BoundingBoxAttachment that is visible and computes the world vertices for its polygon. + /// The polygon vertices are provided along with convenience methods for doing hit detection. + /// + public class SkeletonBounds { + private ExposedList polygonPool = new ExposedList(); + private float minX, minY, maxX, maxY; + + public ExposedList BoundingBoxes { get; private set; } + public ExposedList Polygons { get; private set; } + public float MinX { get { return minX; } set { minX = value; } } + public float MinY { get { return minY; } set { minY = value; } } + public float MaxX { get { return maxX; } set { maxX = value; } } + public float MaxY { get { return maxY; } set { maxY = value; } } + public float Width { get { return maxX - minX; } } + public float Height { get { return maxY - minY; } } + + public SkeletonBounds () { + BoundingBoxes = new ExposedList(); + Polygons = new ExposedList(); + } + + /// + /// Clears any previous polygons, finds all visible bounding box attachments, + /// and computes the world vertices for each bounding box's polygon. + /// The skeleton. + /// + /// If true, the axis aligned bounding box containing all the polygons is computed. + /// If false, the SkeletonBounds AABB methods will always return true. + /// + public void Update (Skeleton skeleton, bool updateAabb) { + ExposedList boundingBoxes = BoundingBoxes; + ExposedList polygons = Polygons; + ExposedList slots = skeleton.slots; + int slotCount = slots.Count; + + boundingBoxes.Clear(); + for (int i = 0, n = polygons.Count; i < n; i++) + polygonPool.Add(polygons.Items[i]); + polygons.Clear(); + + for (int i = 0; i < slotCount; i++) { + Slot slot = slots.Items[i]; + if (!slot.bone.active) continue; + BoundingBoxAttachment boundingBox = slot.attachment as BoundingBoxAttachment; + if (boundingBox == null) continue; + boundingBoxes.Add(boundingBox); + + Polygon polygon = null; + int poolCount = polygonPool.Count; + if (poolCount > 0) { + polygon = polygonPool.Items[poolCount - 1]; + polygonPool.RemoveAt(poolCount - 1); + } else + polygon = new Polygon(); + polygons.Add(polygon); + + int count = boundingBox.worldVerticesLength; + polygon.Count = count; + if (polygon.Vertices.Length < count) polygon.Vertices = new float[count]; + boundingBox.ComputeWorldVertices(slot, polygon.Vertices); + } + + if (updateAabb) { + AabbCompute(); + } else { + minX = int.MinValue; + minY = int.MinValue; + maxX = int.MaxValue; + maxY = int.MaxValue; + } + } + + private void AabbCompute () { + float minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + ExposedList polygons = Polygons; + for (int i = 0, n = polygons.Count; i < n; i++) { + Polygon polygon = polygons.Items[i]; + float[] vertices = polygon.Vertices; + for (int ii = 0, nn = polygon.Count; ii < nn; ii += 2) { + float x = vertices[ii]; + float y = vertices[ii + 1]; + minX = Math.Min(minX, x); + minY = Math.Min(minY, y); + maxX = Math.Max(maxX, x); + maxY = Math.Max(maxY, y); + } + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + } + + + /// Returns true if the axis aligned bounding box contains the point. + public bool AabbContainsPoint (float x, float y) { + return x >= minX && x <= maxX && y >= minY && y <= maxY; + } + + /// Returns true if the axis aligned bounding box intersects the line segment. + public bool AabbIntersectsSegment (float x1, float y1, float x2, float y2) { + float minX = this.minX; + float minY = this.minY; + float maxX = this.maxX; + float maxY = this.maxY; + if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) + return false; + float m = (y2 - y1) / (x2 - x1); + float y = m * (minX - x1) + y1; + if (y > minY && y < maxY) return true; + y = m * (maxX - x1) + y1; + if (y > minY && y < maxY) return true; + float x = (minY - y1) / m + x1; + if (x > minX && x < maxX) return true; + x = (maxY - y1) / m + x1; + if (x > minX && x < maxX) return true; + return false; + } + + /// Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. + public bool AabbIntersectsSkeleton (SkeletonBounds bounds) { + return minX < bounds.maxX && maxX > bounds.minX && minY < bounds.maxY && maxY > bounds.minY; + } + + /// Returns true if the polygon contains the point. + public bool ContainsPoint (Polygon polygon, float x, float y) { + float[] vertices = polygon.Vertices; + int nn = polygon.Count; + + int prevIndex = nn - 2; + bool inside = false; + for (int ii = 0; ii < nn; ii += 2) { + float vertexY = vertices[ii + 1]; + float prevY = vertices[prevIndex + 1]; + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + float vertexX = vertices[ii]; + if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) inside = !inside; + } + prevIndex = ii; + } + return inside; + } + + /// Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more + /// efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. + public BoundingBoxAttachment ContainsPoint (float x, float y) { + ExposedList polygons = Polygons; + for (int i = 0, n = polygons.Count; i < n; i++) + if (ContainsPoint(polygons.Items[i], x, y)) return BoundingBoxes.Items[i]; + return null; + } + + /// Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually + /// more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. + public BoundingBoxAttachment IntersectsSegment (float x1, float y1, float x2, float y2) { + ExposedList polygons = Polygons; + for (int i = 0, n = polygons.Count; i < n; i++) + if (IntersectsSegment(polygons.Items[i], x1, y1, x2, y2)) return BoundingBoxes.Items[i]; + return null; + } + + /// Returns true if the polygon contains the line segment. + public bool IntersectsSegment (Polygon polygon, float x1, float y1, float x2, float y2) { + float[] vertices = polygon.Vertices; + int nn = polygon.Count; + + float width12 = x1 - x2, height12 = y1 - y2; + float det1 = x1 * y2 - y1 * x2; + float x3 = vertices[nn - 2], y3 = vertices[nn - 1]; + for (int ii = 0; ii < nn; ii += 2) { + float x4 = vertices[ii], y4 = vertices[ii + 1]; + float det2 = x3 * y4 - y3 * x4; + float width34 = x3 - x4, height34 = y3 - y4; + float det3 = width12 * height34 - height12 * width34; + float x = (det1 * width34 - width12 * det2) / det3; + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + float y = (det1 * height34 - height12 * det2) / det3; + if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; + } + x3 = x4; + y3 = y4; + } + return false; + } + + public Polygon GetPolygon (BoundingBoxAttachment attachment) { + int index = BoundingBoxes.IndexOf(attachment); + return index == -1 ? null : Polygons.Items[index]; + } + } + + public class Polygon { + public float[] Vertices { get; set; } + public int Count { get; set; } + + public Polygon () { + Vertices = new float[16]; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs.meta new file mode 100644 index 0000000..db6a2d1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonBounds.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 087b328a58c93b149bb977eee3a17258 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs new file mode 100644 index 0000000..40b6036 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs @@ -0,0 +1,296 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class SkeletonClipping { + internal readonly Triangulator triangulator = new Triangulator(); + internal readonly ExposedList clippingPolygon = new ExposedList(); + internal readonly ExposedList clipOutput = new ExposedList(128); + internal readonly ExposedList clippedVertices = new ExposedList(128); + internal readonly ExposedList clippedTriangles = new ExposedList(128); + internal readonly ExposedList clippedUVs = new ExposedList(128); + internal readonly ExposedList scratch = new ExposedList(); + + internal ClippingAttachment clipAttachment; + internal ExposedList> clippingPolygons; + + public ExposedList ClippedVertices { get { return clippedVertices; } } + public ExposedList ClippedTriangles { get { return clippedTriangles; } } + public ExposedList ClippedUVs { get { return clippedUVs; } } + + public bool IsClipping { get { return clipAttachment != null; } } + + public int ClipStart (Slot slot, ClippingAttachment clip) { + if (clipAttachment != null) return 0; + clipAttachment = clip; + + int n = clip.worldVerticesLength; + float[] vertices = clippingPolygon.Resize(n).Items; + clip.ComputeWorldVertices(slot, 0, n, vertices, 0, 2); + MakeClockwise(clippingPolygon); + clippingPolygons = triangulator.Decompose(clippingPolygon, triangulator.Triangulate(clippingPolygon)); + foreach (var polygon in clippingPolygons) { + MakeClockwise(polygon); + polygon.Add(polygon.Items[0]); + polygon.Add(polygon.Items[1]); + } + return clippingPolygons.Count; + } + + public void ClipEnd (Slot slot) { + if (clipAttachment != null && clipAttachment.endSlot == slot.data) ClipEnd(); + } + + public void ClipEnd () { + if (clipAttachment == null) return; + clipAttachment = null; + clippingPolygons = null; + clippedVertices.Clear(); + clippedTriangles.Clear(); + clippingPolygon.Clear(); + } + + public void ClipTriangles (float[] vertices, int verticesLength, int[] triangles, int trianglesLength, float[] uvs) { + ExposedList clipOutput = this.clipOutput, clippedVertices = this.clippedVertices; + var clippedTriangles = this.clippedTriangles; + var polygons = clippingPolygons.Items; + int polygonsCount = clippingPolygons.Count; + + int index = 0; + clippedVertices.Clear(); + clippedUVs.Clear(); + clippedTriangles.Clear(); + //outer: + for (int i = 0; i < trianglesLength; i += 3) { + int vertexOffset = triangles[i] << 1; + float x1 = vertices[vertexOffset], y1 = vertices[vertexOffset + 1]; + float u1 = uvs[vertexOffset], v1 = uvs[vertexOffset + 1]; + + vertexOffset = triangles[i + 1] << 1; + float x2 = vertices[vertexOffset], y2 = vertices[vertexOffset + 1]; + float u2 = uvs[vertexOffset], v2 = uvs[vertexOffset + 1]; + + vertexOffset = triangles[i + 2] << 1; + float x3 = vertices[vertexOffset], y3 = vertices[vertexOffset + 1]; + float u3 = uvs[vertexOffset], v3 = uvs[vertexOffset + 1]; + + for (int p = 0; p < polygonsCount; p++) { + int s = clippedVertices.Count; + if (Clip(x1, y1, x2, y2, x3, y3, polygons[p], clipOutput)) { + int clipOutputLength = clipOutput.Count; + if (clipOutputLength == 0) continue; + float d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1; + float d = 1 / (d0 * d2 + d1 * (y1 - y3)); + + int clipOutputCount = clipOutputLength >> 1; + float[] clipOutputItems = clipOutput.Items; + float[] clippedVerticesItems = clippedVertices.Resize(s + clipOutputCount * 2).Items; + float[] clippedUVsItems = clippedUVs.Resize(s + clipOutputCount * 2).Items; + for (int ii = 0; ii < clipOutputLength; ii += 2) { + float x = clipOutputItems[ii], y = clipOutputItems[ii + 1]; + clippedVerticesItems[s] = x; + clippedVerticesItems[s + 1] = y; + float c0 = x - x3, c1 = y - y3; + float a = (d0 * c0 + d1 * c1) * d; + float b = (d4 * c0 + d2 * c1) * d; + float c = 1 - a - b; + clippedUVsItems[s] = u1 * a + u2 * b + u3 * c; + clippedUVsItems[s + 1] = v1 * a + v2 * b + v3 * c; + s += 2; + } + + s = clippedTriangles.Count; + int[] clippedTrianglesItems = clippedTriangles.Resize(s + 3 * (clipOutputCount - 2)).Items; + clipOutputCount--; + for (int ii = 1; ii < clipOutputCount; ii++) { + clippedTrianglesItems[s] = index; + clippedTrianglesItems[s + 1] = index + ii; + clippedTrianglesItems[s + 2] = index + ii + 1; + s += 3; + } + index += clipOutputCount + 1; + } + else { + float[] clippedVerticesItems = clippedVertices.Resize(s + 3 * 2).Items; + float[] clippedUVsItems = clippedUVs.Resize(s + 3 * 2).Items; + clippedVerticesItems[s] = x1; + clippedVerticesItems[s + 1] = y1; + clippedVerticesItems[s + 2] = x2; + clippedVerticesItems[s + 3] = y2; + clippedVerticesItems[s + 4] = x3; + clippedVerticesItems[s + 5] = y3; + + clippedUVsItems[s] = u1; + clippedUVsItems[s + 1] = v1; + clippedUVsItems[s + 2] = u2; + clippedUVsItems[s + 3] = v2; + clippedUVsItems[s + 4] = u3; + clippedUVsItems[s + 5] = v3; + + s = clippedTriangles.Count; + int[] clippedTrianglesItems = clippedTriangles.Resize(s + 3).Items; + clippedTrianglesItems[s] = index; + clippedTrianglesItems[s + 1] = index + 1; + clippedTrianglesItems[s + 2] = index + 2; + index += 3; + break; //continue outer; + } + } + } + + } + + /** Clips the input triangle against the convex, clockwise clipping area. If the triangle lies entirely within the clipping + * area, false is returned. The clipping area must duplicate the first vertex at the end of the vertices list. */ + internal bool Clip (float x1, float y1, float x2, float y2, float x3, float y3, ExposedList clippingArea, ExposedList output) { + var originalOutput = output; + var clipped = false; + + // Avoid copy at the end. + ExposedList input = null; + if (clippingArea.Count % 4 >= 2) { + input = output; + output = scratch; + } else { + input = scratch; + } + + input.Clear(); + input.Add(x1); + input.Add(y1); + input.Add(x2); + input.Add(y2); + input.Add(x3); + input.Add(y3); + input.Add(x1); + input.Add(y1); + output.Clear(); + + float[] clippingVertices = clippingArea.Items; + int clippingVerticesLast = clippingArea.Count - 4; + for (int i = 0; ; i += 2) { + float edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1]; + float edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3]; + float deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2; + + float[] inputVertices = input.Items; + int inputVerticesLength = input.Count - 2, outputStart = output.Count; + for (int ii = 0; ii < inputVerticesLength; ii += 2) { + float inputX = inputVertices[ii], inputY = inputVertices[ii + 1]; + float inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3]; + bool side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0; + if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) { + if (side2) { // v1 inside, v2 inside + output.Add(inputX2); + output.Add(inputY2); + continue; + } + // v1 inside, v2 outside + float c0 = inputY2 - inputY, c2 = inputX2 - inputX; + float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); + if (Math.Abs(s) > 0.000001f) { + float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; + output.Add(edgeX + (edgeX2 - edgeX) * ua); + output.Add(edgeY + (edgeY2 - edgeY) * ua); + } else { + output.Add(edgeX); + output.Add(edgeY); + } + } + else if (side2) { // v1 outside, v2 inside + float c0 = inputY2 - inputY, c2 = inputX2 - inputX; + float s = c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY); + if (Math.Abs(s) > 0.000001f) { + float ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / s; + output.Add(edgeX + (edgeX2 - edgeX) * ua); + output.Add(edgeY + (edgeY2 - edgeY) * ua); + } else { + output.Add(edgeX); + output.Add(edgeY); + } + output.Add(inputX2); + output.Add(inputY2); + } + clipped = true; + } + + if (outputStart == output.Count) { // All edges outside. + originalOutput.Clear(); + return true; + } + + output.Add(output.Items[0]); + output.Add(output.Items[1]); + + if (i == clippingVerticesLast) break; + var temp = output; + output = input; + output.Clear(); + input = temp; + } + + if (originalOutput != output) { + originalOutput.Clear(); + for (int i = 0, n = output.Count - 2; i < n; i++) { + originalOutput.Add(output.Items[i]); + } + } else { + originalOutput.Resize(originalOutput.Count - 2); + } + + return clipped; + } + + public static void MakeClockwise (ExposedList polygon) { + float[] vertices = polygon.Items; + int verticeslength = polygon.Count; + + float area = vertices[verticeslength - 2] * vertices[1] - vertices[0] * vertices[verticeslength - 1], p1x, p1y, p2x, p2y; + for (int i = 0, n = verticeslength - 3; i < n; i += 2) { + p1x = vertices[i]; + p1y = vertices[i + 1]; + p2x = vertices[i + 2]; + p2y = vertices[i + 3]; + area += p1x * p2y - p2x * p1y; + } + if (area < 0) return; + + for (int i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) { + float x = vertices[i], y = vertices[i + 1]; + int other = lastX - i; + vertices[i] = vertices[other]; + vertices[i + 1] = vertices[other + 1]; + vertices[other] = x; + vertices[other + 1] = y; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs.meta new file mode 100644 index 0000000..73ecd0d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonClipping.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7db809d277afd0e4a8e8c6b703002ee0 +timeCreated: 1492744746 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs new file mode 100644 index 0000000..05ec272 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs @@ -0,0 +1,230 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + + /// Stores the setup pose and all of the stateless data for a skeleton. + public class SkeletonData { + internal string name; + internal ExposedList bones = new ExposedList(); // Ordered parents first + internal ExposedList slots = new ExposedList(); // Setup pose draw order. + internal ExposedList skins = new ExposedList(); + internal Skin defaultSkin; + internal ExposedList events = new ExposedList(); + internal ExposedList animations = new ExposedList(); + internal ExposedList ikConstraints = new ExposedList(); + internal ExposedList transformConstraints = new ExposedList(); + internal ExposedList pathConstraints = new ExposedList(); + internal float x , y, width, height; + internal string version, hash; + + // Nonessential. + internal float fps; + internal string imagesPath, audioPath; + + public string Name { get { return name; } set { name = value; } } + + /// The skeleton's bones, sorted parent first. The root bone is always the first bone. + public ExposedList Bones { get { return bones; } } + + public ExposedList Slots { get { return slots; } } + + /// All skins, including the default skin. + public ExposedList Skins { get { return skins; } set { skins = value; } } + + /// + /// The skeleton's default skin. + /// By default this skin contains all attachments that were not in a skin in Spine. + /// + /// May be null. + public Skin DefaultSkin { get { return defaultSkin; } set { defaultSkin = value; } } + + public ExposedList Events { get { return events; } set { events = value; } } + public ExposedList Animations { get { return animations; } set { animations = value; } } + public ExposedList IkConstraints { get { return ikConstraints; } set { ikConstraints = value; } } + public ExposedList TransformConstraints { get { return transformConstraints; } set { transformConstraints = value; } } + public ExposedList PathConstraints { get { return pathConstraints; } set { pathConstraints = value; } } + + public float X { get { return x; } set { x = value; } } + public float Y { get { return y; } set { y = value; } } + public float Width { get { return width; } set { width = value; } } + public float Height { get { return height; } set { height = value; } } + /// The Spine version used to export this data, or null. + public string Version { get { return version; } set { version = value; } } + public string Hash { get { return hash; } set { hash = value; } } + + /// The path to the images directory as defined in Spine. Available only when nonessential data was exported. May be null + public string ImagesPath { get { return imagesPath; } set { imagesPath = value; } } + + /// The path to the audio directory defined in Spine. Available only when nonessential data was exported. May be null. + public string AudioPath { get { return audioPath; } set { audioPath = value; } } + + /// + /// The dopesheet FPS in Spine. Available only when nonessential data was exported. + public float Fps { get { return fps; } set { fps = value; } } + + // --- Bones. + + /// + /// Finds a bone by comparing each bone's name. + /// It is more efficient to cache the results of this method than to call it multiple times. + /// May be null. + public BoneData FindBone (string boneName) { + if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null."); + var bones = this.bones; + var bonesItems = bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) { + BoneData bone = bonesItems[i]; + if (bone.name == boneName) return bone; + } + return null; + } + + /// -1 if the bone was not found. + public int FindBoneIndex (string boneName) { + if (boneName == null) throw new ArgumentNullException("boneName", "boneName cannot be null."); + var bones = this.bones; + var bonesItems = bones.Items; + for (int i = 0, n = bones.Count; i < n; i++) + if (bonesItems[i].name == boneName) return i; + return -1; + } + + // --- Slots. + + /// May be null. + public SlotData FindSlot (string slotName) { + if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null."); + ExposedList slots = this.slots; + for (int i = 0, n = slots.Count; i < n; i++) { + SlotData slot = slots.Items[i]; + if (slot.name == slotName) return slot; + } + return null; + } + + /// -1 if the slot was not found. + public int FindSlotIndex (string slotName) { + if (slotName == null) throw new ArgumentNullException("slotName", "slotName cannot be null."); + ExposedList slots = this.slots; + for (int i = 0, n = slots.Count; i < n; i++) + if (slots.Items[i].name == slotName) return i; + return -1; + } + + // --- Skins. + + /// May be null. + public Skin FindSkin (string skinName) { + if (skinName == null) throw new ArgumentNullException("skinName", "skinName cannot be null."); + foreach (Skin skin in skins) + if (skin.name == skinName) return skin; + return null; + } + + // --- Events. + + /// May be null. + public EventData FindEvent (string eventDataName) { + if (eventDataName == null) throw new ArgumentNullException("eventDataName", "eventDataName cannot be null."); + foreach (EventData eventData in events) + if (eventData.name == eventDataName) return eventData; + return null; + } + + // --- Animations. + + /// May be null. + public Animation FindAnimation (string animationName) { + if (animationName == null) throw new ArgumentNullException("animationName", "animationName cannot be null."); + ExposedList animations = this.animations; + for (int i = 0, n = animations.Count; i < n; i++) { + Animation animation = animations.Items[i]; + if (animation.name == animationName) return animation; + } + return null; + } + + // --- IK constraints. + + /// May be null. + public IkConstraintData FindIkConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList ikConstraints = this.ikConstraints; + for (int i = 0, n = ikConstraints.Count; i < n; i++) { + IkConstraintData ikConstraint = ikConstraints.Items[i]; + if (ikConstraint.name == constraintName) return ikConstraint; + } + return null; + } + + // --- Transform constraints. + + /// May be null. + public TransformConstraintData FindTransformConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList transformConstraints = this.transformConstraints; + for (int i = 0, n = transformConstraints.Count; i < n; i++) { + TransformConstraintData transformConstraint = transformConstraints.Items[i]; + if (transformConstraint.name == constraintName) return transformConstraint; + } + return null; + } + + // --- Path constraints. + + /// May be null. + public PathConstraintData FindPathConstraint (string constraintName) { + if (constraintName == null) throw new ArgumentNullException("constraintName", "constraintName cannot be null."); + ExposedList pathConstraints = this.pathConstraints; + for (int i = 0, n = pathConstraints.Count; i < n; i++) { + PathConstraintData constraint = pathConstraints.Items[i]; + if (constraint.name.Equals(constraintName)) return constraint; + } + return null; + } + + /// -1 if the path constraint was not found. + public int FindPathConstraintIndex (string pathConstraintName) { + if (pathConstraintName == null) throw new ArgumentNullException("pathConstraintName", "pathConstraintName cannot be null."); + ExposedList pathConstraints = this.pathConstraints; + for (int i = 0, n = pathConstraints.Count; i < n; i++) + if (pathConstraints.Items[i].name.Equals(pathConstraintName)) return i; + return -1; + } + + // --- + + override public string ToString () { + return name ?? base.ToString(); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs.meta new file mode 100644 index 0000000..579186e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2b813f63abbb6d94a80a5c050590a0be +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs new file mode 100644 index 0000000..de7f236 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs @@ -0,0 +1,918 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1) +#define IS_UNITY +#endif + +using System; +using System.IO; +using System.Collections.Generic; + +#if WINDOWS_STOREAPP +using System.Threading.Tasks; +using Windows.Storage; +#endif + +namespace Spine { + public class SkeletonJson { + public float Scale { get; set; } + + private AttachmentLoader attachmentLoader; + private List linkedMeshes = new List(); + + public SkeletonJson (params Atlas[] atlasArray) + : this(new AtlasAttachmentLoader(atlasArray)) { + } + + public SkeletonJson (AttachmentLoader attachmentLoader) { + if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader", "attachmentLoader cannot be null."); + this.attachmentLoader = attachmentLoader; + Scale = 1; + } + + #if !IS_UNITY && WINDOWS_STOREAPP + private async Task ReadFile(string path) { + var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; + var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false); + using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) { + SkeletonData skeletonData = ReadSkeletonData(reader); + skeletonData.Name = Path.GetFileNameWithoutExtension(path); + return skeletonData; + } + } + + public SkeletonData ReadSkeletonData (string path) { + return this.ReadFile(path).Result; + } + #else + public SkeletonData ReadSkeletonData (string path) { + #if WINDOWS_PHONE + using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { + #else + using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))) { + #endif + SkeletonData skeletonData = ReadSkeletonData(reader); + skeletonData.name = Path.GetFileNameWithoutExtension(path); + return skeletonData; + } + } + #endif + + public SkeletonData ReadSkeletonData (TextReader reader) { + if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null."); + + float scale = this.Scale; + var skeletonData = new SkeletonData(); + + var root = Json.Deserialize(reader) as Dictionary; + if (root == null) throw new Exception("Invalid JSON."); + + // Skeleton. + if (root.ContainsKey("skeleton")) { + var skeletonMap = (Dictionary)root["skeleton"]; + skeletonData.hash = (string)skeletonMap["hash"]; + skeletonData.version = (string)skeletonMap["spine"]; + if ("3.8.75" == skeletonData.version) + throw new Exception("Unsupported skeleton data, please export with a newer version of Spine."); + skeletonData.x = GetFloat(skeletonMap, "x", 0); + skeletonData.y = GetFloat(skeletonMap, "y", 0); + skeletonData.width = GetFloat(skeletonMap, "width", 0); + skeletonData.height = GetFloat(skeletonMap, "height", 0); + skeletonData.fps = GetFloat(skeletonMap, "fps", 30); + skeletonData.imagesPath = GetString(skeletonMap, "images", null); + skeletonData.audioPath = GetString(skeletonMap, "audio", null); + } + + // Bones. + if (root.ContainsKey("bones")) { + foreach (Dictionary boneMap in (List)root["bones"]) { + BoneData parent = null; + if (boneMap.ContainsKey("parent")) { + parent = skeletonData.FindBone((string)boneMap["parent"]); + if (parent == null) + throw new Exception("Parent bone not found: " + boneMap["parent"]); + } + var data = new BoneData(skeletonData.Bones.Count, (string)boneMap["name"], parent); + data.length = GetFloat(boneMap, "length", 0) * scale; + data.x = GetFloat(boneMap, "x", 0) * scale; + data.y = GetFloat(boneMap, "y", 0) * scale; + data.rotation = GetFloat(boneMap, "rotation", 0); + data.scaleX = GetFloat(boneMap, "scaleX", 1); + data.scaleY = GetFloat(boneMap, "scaleY", 1); + data.shearX = GetFloat(boneMap, "shearX", 0); + data.shearY = GetFloat(boneMap, "shearY", 0); + + string tm = GetString(boneMap, "transform", TransformMode.Normal.ToString()); + data.transformMode = (TransformMode)Enum.Parse(typeof(TransformMode), tm, true); + data.skinRequired = GetBoolean(boneMap, "skin", false); + + skeletonData.bones.Add(data); + } + } + + // Slots. + if (root.ContainsKey("slots")) { + foreach (Dictionary slotMap in (List)root["slots"]) { + var slotName = (string)slotMap["name"]; + var boneName = (string)slotMap["bone"]; + BoneData boneData = skeletonData.FindBone(boneName); + if (boneData == null) throw new Exception("Slot bone not found: " + boneName); + var data = new SlotData(skeletonData.Slots.Count, slotName, boneData); + + if (slotMap.ContainsKey("color")) { + string color = (string)slotMap["color"]; + data.r = ToColor(color, 0); + data.g = ToColor(color, 1); + data.b = ToColor(color, 2); + data.a = ToColor(color, 3); + } + + if (slotMap.ContainsKey("dark")) { + var color2 = (string)slotMap["dark"]; + data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB" + data.g2 = ToColor(color2, 1, 6); + data.b2 = ToColor(color2, 2, 6); + data.hasSecondColor = true; + } + + data.attachmentName = GetString(slotMap, "attachment", null); + if (slotMap.ContainsKey("blend")) + data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (string)slotMap["blend"], true); + else + data.blendMode = BlendMode.Normal; + skeletonData.slots.Add(data); + } + } + + // IK constraints. + if (root.ContainsKey("ik")) { + foreach (Dictionary constraintMap in (List)root["ik"]) { + IkConstraintData data = new IkConstraintData((string)constraintMap["name"]); + data.order = GetInt(constraintMap, "order", 0); + data.skinRequired = GetBoolean(constraintMap,"skin", false); + + if (constraintMap.ContainsKey("bones")) { + foreach (string boneName in (List)constraintMap["bones"]) { + BoneData bone = skeletonData.FindBone(boneName); + if (bone == null) throw new Exception("IK bone not found: " + boneName); + data.bones.Add(bone); + } + } + + string targetName = (string)constraintMap["target"]; + data.target = skeletonData.FindBone(targetName); + if (data.target == null) throw new Exception("IK target bone not found: " + targetName); + data.mix = GetFloat(constraintMap, "mix", 1); + data.softness = GetFloat(constraintMap, "softness", 0) * scale; + data.bendDirection = GetBoolean(constraintMap, "bendPositive", true) ? 1 : -1; + data.compress = GetBoolean(constraintMap, "compress", false); + data.stretch = GetBoolean(constraintMap, "stretch", false); + data.uniform = GetBoolean(constraintMap, "uniform", false); + + skeletonData.ikConstraints.Add(data); + } + } + + // Transform constraints. + if (root.ContainsKey("transform")) { + foreach (Dictionary constraintMap in (List)root["transform"]) { + TransformConstraintData data = new TransformConstraintData((string)constraintMap["name"]); + data.order = GetInt(constraintMap, "order", 0); + data.skinRequired = GetBoolean(constraintMap,"skin", false); + + if (constraintMap.ContainsKey("bones")) { + foreach (string boneName in (List)constraintMap["bones"]) { + BoneData bone = skeletonData.FindBone(boneName); + if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName); + data.bones.Add(bone); + } + } + + string targetName = (string)constraintMap["target"]; + data.target = skeletonData.FindBone(targetName); + if (data.target == null) throw new Exception("Transform constraint target bone not found: " + targetName); + + data.local = GetBoolean(constraintMap, "local", false); + data.relative = GetBoolean(constraintMap, "relative", false); + + data.offsetRotation = GetFloat(constraintMap, "rotation", 0); + data.offsetX = GetFloat(constraintMap, "x", 0) * scale; + data.offsetY = GetFloat(constraintMap, "y", 0) * scale; + data.offsetScaleX = GetFloat(constraintMap, "scaleX", 0); + data.offsetScaleY = GetFloat(constraintMap, "scaleY", 0); + data.offsetShearY = GetFloat(constraintMap, "shearY", 0); + + data.rotateMix = GetFloat(constraintMap, "rotateMix", 1); + data.translateMix = GetFloat(constraintMap, "translateMix", 1); + data.scaleMix = GetFloat(constraintMap, "scaleMix", 1); + data.shearMix = GetFloat(constraintMap, "shearMix", 1); + + skeletonData.transformConstraints.Add(data); + } + } + + // Path constraints. + if(root.ContainsKey("path")) { + foreach (Dictionary constraintMap in (List)root["path"]) { + PathConstraintData data = new PathConstraintData((string)constraintMap["name"]); + data.order = GetInt(constraintMap, "order", 0); + data.skinRequired = GetBoolean(constraintMap,"skin", false); + + if (constraintMap.ContainsKey("bones")) { + foreach (string boneName in (List)constraintMap["bones"]) { + BoneData bone = skeletonData.FindBone(boneName); + if (bone == null) throw new Exception("Path bone not found: " + boneName); + data.bones.Add(bone); + } + } + + string targetName = (string)constraintMap["target"]; + data.target = skeletonData.FindSlot(targetName); + if (data.target == null) throw new Exception("Path target slot not found: " + targetName); + + data.positionMode = (PositionMode)Enum.Parse(typeof(PositionMode), GetString(constraintMap, "positionMode", "percent"), true); + data.spacingMode = (SpacingMode)Enum.Parse(typeof(SpacingMode), GetString(constraintMap, "spacingMode", "length"), true); + data.rotateMode = (RotateMode)Enum.Parse(typeof(RotateMode), GetString(constraintMap, "rotateMode", "tangent"), true); + data.offsetRotation = GetFloat(constraintMap, "rotation", 0); + data.position = GetFloat(constraintMap, "position", 0); + if (data.positionMode == PositionMode.Fixed) data.position *= scale; + data.spacing = GetFloat(constraintMap, "spacing", 0); + if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale; + data.rotateMix = GetFloat(constraintMap, "rotateMix", 1); + data.translateMix = GetFloat(constraintMap, "translateMix", 1); + + skeletonData.pathConstraints.Add(data); + } + } + + // Skins. + if (root.ContainsKey("skins")) { + foreach (Dictionary skinMap in (List)root["skins"]) { + Skin skin = new Skin((string)skinMap["name"]); + if (skinMap.ContainsKey("bones")) { + foreach (string entryName in (List)skinMap["bones"]) { + BoneData bone = skeletonData.FindBone(entryName); + if (bone == null) throw new Exception("Skin bone not found: " + entryName); + skin.bones.Add(bone); + } + } + if (skinMap.ContainsKey("ik")) { + foreach (string entryName in (List)skinMap["ik"]) { + IkConstraintData constraint = skeletonData.FindIkConstraint(entryName); + if (constraint == null) throw new Exception("Skin IK constraint not found: " + entryName); + skin.constraints.Add(constraint); + } + } + if (skinMap.ContainsKey("transform")) { + foreach (string entryName in (List)skinMap["transform"]) { + TransformConstraintData constraint = skeletonData.FindTransformConstraint(entryName); + if (constraint == null) throw new Exception("Skin transform constraint not found: " + entryName); + skin.constraints.Add(constraint); + } + } + if (skinMap.ContainsKey("path")) { + foreach (string entryName in (List)skinMap["path"]) { + PathConstraintData constraint = skeletonData.FindPathConstraint(entryName); + if (constraint == null) throw new Exception("Skin path constraint not found: " + entryName); + skin.constraints.Add(constraint); + } + } + if (skinMap.ContainsKey("attachments")) { + foreach (KeyValuePair slotEntry in (Dictionary)skinMap["attachments"]) { + int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key); + foreach (KeyValuePair entry in ((Dictionary)slotEntry.Value)) { + try { + Attachment attachment = ReadAttachment((Dictionary)entry.Value, skin, slotIndex, entry.Key, skeletonData); + if (attachment != null) skin.SetAttachment(slotIndex, entry.Key, attachment); + } catch (Exception e) { + throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e); + } + } + } + } + skeletonData.skins.Add(skin); + if (skin.name == "default") skeletonData.defaultSkin = skin; + } + } + + // Linked meshes. + for (int i = 0, n = linkedMeshes.Count; i < n; i++) { + LinkedMesh linkedMesh = linkedMeshes[i]; + Skin skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.FindSkin(linkedMesh.skin); + if (skin == null) throw new Exception("Slot not found: " + linkedMesh.skin); + Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent); + if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent); + linkedMesh.mesh.DeformAttachment = linkedMesh.inheritDeform ? (VertexAttachment)parent : linkedMesh.mesh; + linkedMesh.mesh.ParentMesh = (MeshAttachment)parent; + linkedMesh.mesh.UpdateUVs(); + } + linkedMeshes.Clear(); + + // Events. + if (root.ContainsKey("events")) { + foreach (KeyValuePair entry in (Dictionary)root["events"]) { + var entryMap = (Dictionary)entry.Value; + var data = new EventData(entry.Key); + data.Int = GetInt(entryMap, "int", 0); + data.Float = GetFloat(entryMap, "float", 0); + data.String = GetString(entryMap, "string", string.Empty); + data.AudioPath = GetString(entryMap, "audio", null); + if (data.AudioPath != null) { + data.Volume = GetFloat(entryMap, "volume", 1); + data.Balance = GetFloat(entryMap, "balance", 0); + } + skeletonData.events.Add(data); + } + } + + // Animations. + if (root.ContainsKey("animations")) { + foreach (KeyValuePair entry in (Dictionary)root["animations"]) { + try { + ReadAnimation((Dictionary)entry.Value, entry.Key, skeletonData); + } catch (Exception e) { + throw new Exception("Error reading animation: " + entry.Key, e); + } + } + } + + skeletonData.bones.TrimExcess(); + skeletonData.slots.TrimExcess(); + skeletonData.skins.TrimExcess(); + skeletonData.events.TrimExcess(); + skeletonData.animations.TrimExcess(); + skeletonData.ikConstraints.TrimExcess(); + return skeletonData; + } + + private Attachment ReadAttachment (Dictionary map, Skin skin, int slotIndex, string name, SkeletonData skeletonData) { + float scale = this.Scale; + name = GetString(map, "name", name); + + var typeName = GetString(map, "type", "region"); + var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true); + + string path = GetString(map, "path", name); + + switch (type) { + case AttachmentType.Region: + RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path); + if (region == null) return null; + region.Path = path; + region.x = GetFloat(map, "x", 0) * scale; + region.y = GetFloat(map, "y", 0) * scale; + region.scaleX = GetFloat(map, "scaleX", 1); + region.scaleY = GetFloat(map, "scaleY", 1); + region.rotation = GetFloat(map, "rotation", 0); + region.width = GetFloat(map, "width", 32) * scale; + region.height = GetFloat(map, "height", 32) * scale; + + if (map.ContainsKey("color")) { + var color = (string)map["color"]; + region.r = ToColor(color, 0); + region.g = ToColor(color, 1); + region.b = ToColor(color, 2); + region.a = ToColor(color, 3); + } + + region.UpdateOffset(); + return region; + case AttachmentType.Boundingbox: + BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name); + if (box == null) return null; + ReadVertices(map, box, GetInt(map, "vertexCount", 0) << 1); + return box; + case AttachmentType.Mesh: + case AttachmentType.Linkedmesh: { + MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); + if (mesh == null) return null; + mesh.Path = path; + + if (map.ContainsKey("color")) { + var color = (string)map["color"]; + mesh.r = ToColor(color, 0); + mesh.g = ToColor(color, 1); + mesh.b = ToColor(color, 2); + mesh.a = ToColor(color, 3); + } + + mesh.Width = GetFloat(map, "width", 0) * scale; + mesh.Height = GetFloat(map, "height", 0) * scale; + + string parent = GetString(map, "parent", null); + if (parent != null) { + linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent, GetBoolean(map, "deform", true))); + return mesh; + } + + float[] uvs = GetFloatArray(map, "uvs", 1); + ReadVertices(map, mesh, uvs.Length); + mesh.triangles = GetIntArray(map, "triangles"); + mesh.regionUVs = uvs; + mesh.UpdateUVs(); + + if (map.ContainsKey("hull")) mesh.HullLength = GetInt(map, "hull", 0) * 2; + if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges"); + return mesh; + } + case AttachmentType.Path: { + PathAttachment pathAttachment = attachmentLoader.NewPathAttachment(skin, name); + if (pathAttachment == null) return null; + pathAttachment.closed = GetBoolean(map, "closed", false); + pathAttachment.constantSpeed = GetBoolean(map, "constantSpeed", true); + + int vertexCount = GetInt(map, "vertexCount", 0); + ReadVertices(map, pathAttachment, vertexCount << 1); + + // potential BOZO see Java impl + pathAttachment.lengths = GetFloatArray(map, "lengths", scale); + return pathAttachment; + } + case AttachmentType.Point: { + PointAttachment point = attachmentLoader.NewPointAttachment(skin, name); + if (point == null) return null; + point.x = GetFloat(map, "x", 0) * scale; + point.y = GetFloat(map, "y", 0) * scale; + point.rotation = GetFloat(map, "rotation", 0); + + //string color = GetString(map, "color", null); + //if (color != null) point.color = color; + return point; + } + case AttachmentType.Clipping: { + ClippingAttachment clip = attachmentLoader.NewClippingAttachment(skin, name); + if (clip == null) return null; + + string end = GetString(map, "end", null); + if (end != null) { + SlotData slot = skeletonData.FindSlot(end); + if (slot == null) throw new Exception("Clipping end slot not found: " + end); + clip.EndSlot = slot; + } + + ReadVertices(map, clip, GetInt(map, "vertexCount", 0) << 1); + + //string color = GetString(map, "color", null); + // if (color != null) clip.color = color; + return clip; + } + } + return null; + } + + private void ReadVertices (Dictionary map, VertexAttachment attachment, int verticesLength) { + attachment.WorldVerticesLength = verticesLength; + float[] vertices = GetFloatArray(map, "vertices", 1); + float scale = Scale; + if (verticesLength == vertices.Length) { + if (scale != 1) { + for (int i = 0; i < vertices.Length; i++) { + vertices[i] *= scale; + } + } + attachment.vertices = vertices; + return; + } + ExposedList weights = new ExposedList(verticesLength * 3 * 3); + ExposedList bones = new ExposedList(verticesLength * 3); + for (int i = 0, n = vertices.Length; i < n;) { + int boneCount = (int)vertices[i++]; + bones.Add(boneCount); + for (int nn = i + boneCount * 4; i < nn; i += 4) { + bones.Add((int)vertices[i]); + weights.Add(vertices[i + 1] * this.Scale); + weights.Add(vertices[i + 2] * this.Scale); + weights.Add(vertices[i + 3]); + } + } + attachment.bones = bones.ToArray(); + attachment.vertices = weights.ToArray(); + } + + private void ReadAnimation (Dictionary map, string name, SkeletonData skeletonData) { + var scale = this.Scale; + var timelines = new ExposedList(); + float duration = 0; + + // Slot timelines. + if (map.ContainsKey("slots")) { + foreach (KeyValuePair entry in (Dictionary)map["slots"]) { + string slotName = entry.Key; + int slotIndex = skeletonData.FindSlotIndex(slotName); + var timelineMap = (Dictionary)entry.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { + var values = (List)timelineEntry.Value; + var timelineName = (string)timelineEntry.Key; + if (timelineName == "attachment") { + var timeline = new AttachmentTimeline(values.Count); + timeline.slotIndex = slotIndex; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + float time = GetFloat(valueMap, "time", 0); + timeline.SetFrame(frameIndex++, time, (string)valueMap["name"]); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); + + } else if (timelineName == "color") { + var timeline = new ColorTimeline(values.Count); + timeline.slotIndex = slotIndex; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + float time = GetFloat(valueMap, "time", 0); + string c = (string)valueMap["color"]; + timeline.SetFrame(frameIndex, time, ToColor(c, 0), ToColor(c, 1), ToColor(c, 2), ToColor(c, 3)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * ColorTimeline.ENTRIES]); + + } else if (timelineName == "twoColor") { + var timeline = new TwoColorTimeline(values.Count); + timeline.slotIndex = slotIndex; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + float time = GetFloat(valueMap, "time", 0); + string light = (string)valueMap["light"]; + string dark = (string)valueMap["dark"]; + timeline.SetFrame(frameIndex, time, ToColor(light, 0), ToColor(light, 1), ToColor(light, 2), ToColor(light, 3), + ToColor(dark, 0, 6), ToColor(dark, 1, 6), ToColor(dark, 2, 6)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TwoColorTimeline.ENTRIES]); + + } else + throw new Exception("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); + } + } + } + + // Bone timelines. + if (map.ContainsKey("bones")) { + foreach (KeyValuePair entry in (Dictionary)map["bones"]) { + string boneName = entry.Key; + int boneIndex = skeletonData.FindBoneIndex(boneName); + if (boneIndex == -1) throw new Exception("Bone not found: " + boneName); + var timelineMap = (Dictionary)entry.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { + var values = (List)timelineEntry.Value; + var timelineName = (string)timelineEntry.Key; + if (timelineName == "rotate") { + var timeline = new RotateTimeline(values.Count); + timeline.boneIndex = boneIndex; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "angle", 0)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * RotateTimeline.ENTRIES]); + + } else if (timelineName == "translate" || timelineName == "scale" || timelineName == "shear") { + TranslateTimeline timeline; + float timelineScale = 1, defaultValue = 0; + if (timelineName == "scale") { + timeline = new ScaleTimeline(values.Count); + defaultValue = 1; + } + else if (timelineName == "shear") + timeline = new ShearTimeline(values.Count); + else { + timeline = new TranslateTimeline(values.Count); + timelineScale = scale; + } + timeline.boneIndex = boneIndex; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + float time = GetFloat(valueMap, "time", 0); + float x = GetFloat(valueMap, "x", defaultValue); + float y = GetFloat(valueMap, "y", defaultValue); + timeline.SetFrame(frameIndex, time, x * timelineScale, y * timelineScale); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TranslateTimeline.ENTRIES]); + + } else + throw new Exception("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); + } + } + } + + // IK constraint timelines. + if (map.ContainsKey("ik")) { + foreach (KeyValuePair constraintMap in (Dictionary)map["ik"]) { + IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key); + var values = (List)constraintMap.Value; + var timeline = new IkConstraintTimeline(values.Count); + timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint); + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "mix", 1), + GetFloat(valueMap, "softness", 0) * scale, GetBoolean(valueMap, "bendPositive", true) ? 1 : -1, + GetBoolean(valueMap, "compress", false), GetBoolean(valueMap, "stretch", false)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * IkConstraintTimeline.ENTRIES]); + } + } + + // Transform constraint timelines. + if (map.ContainsKey("transform")) { + foreach (KeyValuePair constraintMap in (Dictionary)map["transform"]) { + TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key); + var values = (List)constraintMap.Value; + var timeline = new TransformConstraintTimeline(values.Count); + timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint); + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "rotateMix", 1), + GetFloat(valueMap, "translateMix", 1), GetFloat(valueMap, "scaleMix", 1), GetFloat(valueMap, "shearMix", 1)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TransformConstraintTimeline.ENTRIES]); + } + } + + // Path constraint timelines. + if (map.ContainsKey("path")) { + foreach (KeyValuePair constraintMap in (Dictionary)map["path"]) { + int index = skeletonData.FindPathConstraintIndex(constraintMap.Key); + if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key); + PathConstraintData data = skeletonData.pathConstraints.Items[index]; + var timelineMap = (Dictionary)constraintMap.Value; + foreach (KeyValuePair timelineEntry in timelineMap) { + var values = (List)timelineEntry.Value; + var timelineName = (string)timelineEntry.Key; + if (timelineName == "position" || timelineName == "spacing") { + PathConstraintPositionTimeline timeline; + float timelineScale = 1; + if (timelineName == "spacing") { + timeline = new PathConstraintSpacingTimeline(values.Count); + if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) timelineScale = scale; + } + else { + timeline = new PathConstraintPositionTimeline(values.Count); + if (data.positionMode == PositionMode.Fixed) timelineScale = scale; + } + timeline.pathConstraintIndex = index; + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, timelineName, 0) * timelineScale); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintPositionTimeline.ENTRIES]); + } + else if (timelineName == "mix") { + PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count); + timeline.pathConstraintIndex = index; + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), GetFloat(valueMap, "rotateMix", 1), + GetFloat(valueMap, "translateMix", 1)); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintMixTimeline.ENTRIES]); + } + } + } + } + + // Deform timelines. + if (map.ContainsKey("deform")) { + foreach (KeyValuePair deformMap in (Dictionary)map["deform"]) { + Skin skin = skeletonData.FindSkin(deformMap.Key); + foreach (KeyValuePair slotMap in (Dictionary)deformMap.Value) { + int slotIndex = skeletonData.FindSlotIndex(slotMap.Key); + if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key); + foreach (KeyValuePair timelineMap in (Dictionary)slotMap.Value) { + var values = (List)timelineMap.Value; + VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key); + if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key); + bool weighted = attachment.bones != null; + float[] vertices = attachment.vertices; + int deformLength = weighted ? vertices.Length / 3 * 2 : vertices.Length; + + var timeline = new DeformTimeline(values.Count); + timeline.slotIndex = slotIndex; + timeline.attachment = attachment; + + int frameIndex = 0; + foreach (Dictionary valueMap in values) { + float[] deform; + if (!valueMap.ContainsKey("vertices")) { + deform = weighted ? new float[deformLength] : vertices; + } else { + deform = new float[deformLength]; + int start = GetInt(valueMap, "offset", 0); + float[] verticesValue = GetFloatArray(valueMap, "vertices", 1); + Array.Copy(verticesValue, 0, deform, start, verticesValue.Length); + if (scale != 1) { + for (int i = start, n = i + verticesValue.Length; i < n; i++) + deform[i] *= scale; + } + + if (!weighted) { + for (int i = 0; i < deformLength; i++) + deform[i] += vertices[i]; + } + } + + timeline.SetFrame(frameIndex, GetFloat(valueMap, "time", 0), deform); + ReadCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); + } + } + } + } + + // Draw order timeline. + if (map.ContainsKey("drawOrder") || map.ContainsKey("draworder")) { + var values = (List)map[map.ContainsKey("drawOrder") ? "drawOrder" : "draworder"]; + var timeline = new DrawOrderTimeline(values.Count); + int slotCount = skeletonData.slots.Count; + int frameIndex = 0; + foreach (Dictionary drawOrderMap in values) { + int[] drawOrder = null; + if (drawOrderMap.ContainsKey("offsets")) { + drawOrder = new int[slotCount]; + for (int i = slotCount - 1; i >= 0; i--) + drawOrder[i] = -1; + var offsets = (List)drawOrderMap["offsets"]; + int[] unchanged = new int[slotCount - offsets.Count]; + int originalIndex = 0, unchangedIndex = 0; + foreach (Dictionary offsetMap in offsets) { + int slotIndex = skeletonData.FindSlotIndex((string)offsetMap["slot"]); + if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]); + // Collect unchanged items. + while (originalIndex != slotIndex) + unchanged[unchangedIndex++] = originalIndex++; + // Set changed items. + int index = originalIndex + (int)(float)offsetMap["offset"]; + drawOrder[index] = originalIndex++; + } + // Collect remaining unchanged items. + while (originalIndex < slotCount) + unchanged[unchangedIndex++] = originalIndex++; + // Fill in unchanged items. + for (int i = slotCount - 1; i >= 0; i--) + if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex]; + } + timeline.SetFrame(frameIndex++, GetFloat(drawOrderMap, "time", 0), drawOrder); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); + } + + // Event timeline. + if (map.ContainsKey("events")) { + var eventsMap = (List)map["events"]; + var timeline = new EventTimeline(eventsMap.Count); + int frameIndex = 0; + foreach (Dictionary eventMap in eventsMap) { + EventData eventData = skeletonData.FindEvent((string)eventMap["name"]); + if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]); + var e = new Event(GetFloat(eventMap, "time", 0), eventData) { + intValue = GetInt(eventMap, "int", eventData.Int), + floatValue = GetFloat(eventMap, "float", eventData.Float), + stringValue = GetString(eventMap, "string", eventData.String) + }; + if (e.data.AudioPath != null) { + e.volume = GetFloat(eventMap, "volume", eventData.Volume); + e.balance = GetFloat(eventMap, "balance", eventData.Balance); + } + timeline.SetFrame(frameIndex++, e); + } + timelines.Add(timeline); + duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]); + } + + timelines.TrimExcess(); + skeletonData.animations.Add(new Animation(name, timelines, duration)); + } + + static void ReadCurve (Dictionary valueMap, CurveTimeline timeline, int frameIndex) { + if (!valueMap.ContainsKey("curve")) + return; + Object curveObject = valueMap["curve"]; + if (curveObject is string) + timeline.SetStepped(frameIndex); + else + timeline.SetCurve(frameIndex, (float)curveObject, GetFloat(valueMap, "c2", 0), GetFloat(valueMap, "c3", 1), GetFloat(valueMap, "c4", 1)); + } + + internal class LinkedMesh { + internal string parent, skin; + internal int slotIndex; + internal MeshAttachment mesh; + internal bool inheritDeform; + + public LinkedMesh (MeshAttachment mesh, string skin, int slotIndex, string parent, bool inheritDeform) { + this.mesh = mesh; + this.skin = skin; + this.slotIndex = slotIndex; + this.parent = parent; + this.inheritDeform = inheritDeform; + } + } + + static float[] GetFloatArray(Dictionary map, string name, float scale) { + var list = (List)map[name]; + var values = new float[list.Count]; + if (scale == 1) { + for (int i = 0, n = list.Count; i < n; i++) + values[i] = (float)list[i]; + } else { + for (int i = 0, n = list.Count; i < n; i++) + values[i] = (float)list[i] * scale; + } + return values; + } + + static int[] GetIntArray(Dictionary map, string name) { + var list = (List)map[name]; + var values = new int[list.Count]; + for (int i = 0, n = list.Count; i < n; i++) + values[i] = (int)(float)list[i]; + return values; + } + + static float GetFloat(Dictionary map, string name, float defaultValue) { + if (!map.ContainsKey(name)) + return defaultValue; + return (float)map[name]; + } + + static int GetInt(Dictionary map, string name, int defaultValue) { + if (!map.ContainsKey(name)) + return defaultValue; + return (int)(float)map[name]; + } + + static bool GetBoolean(Dictionary map, string name, bool defaultValue) { + if (!map.ContainsKey(name)) + return defaultValue; + return (bool)map[name]; + } + + static string GetString(Dictionary map, string name, string defaultValue) { + if (!map.ContainsKey(name)) + return defaultValue; + return (string)map[name]; + } + + static float ToColor(string hexString, int colorIndex, int expectedLength = 8) { + if (hexString.Length != expectedLength) + throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString"); + return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs.meta new file mode 100644 index 0000000..9188b23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SkeletonJson.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c4ab7992894bdb44a480981b1953f76 +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs new file mode 100644 index 0000000..de26ad1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs @@ -0,0 +1,193 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections; +using System.Collections.Generic; +using Spine.Collections; + +namespace Spine { + /// Stores attachments by slot index and attachment name. + /// See SkeletonData , Skeleton , and + /// Runtime skins in the Spine Runtimes Guide. + /// + public class Skin { + internal string name; + private OrderedDictionary attachments = new OrderedDictionary(SkinEntryComparer.Instance); + internal readonly ExposedList bones = new ExposedList(); + internal readonly ExposedList constraints = new ExposedList(); + + public string Name { get { return name; } } + public OrderedDictionary Attachments { get { return attachments; } } + public ExposedList Bones { get { return bones; } } + public ExposedList Constraints { get { return constraints; } } + + public Skin (string name) { + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + this.name = name; + } + + /// Adds an attachment to the skin for the specified slot index and name. + /// If the name already exists for the slot, the previous value is replaced. + public void SetAttachment (int slotIndex, string name, Attachment attachment) { + if (attachment == null) throw new ArgumentNullException("attachment", "attachment cannot be null."); + if (slotIndex < 0) throw new ArgumentNullException("slotIndex", "slotIndex must be >= 0."); + attachments[new SkinEntry(slotIndex, name, attachment)] = attachment; + } + + ///Adds all attachments, bones, and constraints from the specified skin to this skin. + public void AddSkin (Skin skin) { + foreach (BoneData data in skin.bones) + if (!bones.Contains(data)) bones.Add(data); + + foreach (ConstraintData data in skin.constraints) + if (!constraints.Contains(data)) constraints.Add(data); + + foreach (SkinEntry entry in skin.attachments.Keys) + SetAttachment(entry.SlotIndex, entry.Name, entry.Attachment); + } + + ///Adds all attachments from the specified skin to this skin. Attachments are deep copied. + public void CopySkin (Skin skin) { + foreach (BoneData data in skin.bones) + if (!bones.Contains(data)) bones.Add(data); + + foreach (ConstraintData data in skin.constraints) + if (!constraints.Contains(data)) constraints.Add(data); + + foreach (SkinEntry entry in skin.attachments.Keys) { + if (entry.Attachment is MeshAttachment) + SetAttachment(entry.SlotIndex, entry.Name, + entry.Attachment != null ? ((MeshAttachment)entry.Attachment).NewLinkedMesh() : null); + else + SetAttachment(entry.SlotIndex, entry.Name, entry.Attachment != null ? entry.Attachment.Copy() : null); + } + } + + /// Returns the attachment for the specified slot index and name, or null. + /// May be null. + public Attachment GetAttachment (int slotIndex, string name) { + var lookup = new SkinEntry(slotIndex, name, null); + Attachment attachment = null; + bool containsKey = attachments.TryGetValue(lookup, out attachment); + return containsKey ? attachment : null; + } + + /// Removes the attachment in the skin for the specified slot index and name, if any. + public void RemoveAttachment (int slotIndex, string name) { + if (slotIndex < 0) throw new ArgumentOutOfRangeException("slotIndex", "slotIndex must be >= 0"); + var lookup = new SkinEntry(slotIndex, name, null); + attachments.Remove(lookup); + } + + ///Returns all attachments contained in this skin. + public ICollection GetAttachments () { + return this.attachments.Keys; + } + + /// Returns all attachments in this skin for the specified slot index. + /// The target slotIndex. To find the slot index, use or + public void GetAttachments (int slotIndex, List attachments) { + foreach (SkinEntry entry in this.attachments.Keys) + if (entry.SlotIndex == slotIndex) attachments.Add(entry); + } + + ///Clears all attachments, bones, and constraints. + public void Clear () { + attachments.Clear(); + bones.Clear(); + constraints.Clear(); + } + + override public string ToString () { + return name; + } + + /// Attach all attachments from this skin if the corresponding attachment from the old skin is currently attached. + internal void AttachAll (Skeleton skeleton, Skin oldSkin) { + foreach (SkinEntry entry in oldSkin.attachments.Keys) { + int slotIndex = entry.SlotIndex; + Slot slot = skeleton.slots.Items[slotIndex]; + if (slot.Attachment == entry.Attachment) { + Attachment attachment = GetAttachment(slotIndex, entry.Name); + if (attachment != null) slot.Attachment = attachment; + } + } + } + + /// Stores an entry in the skin consisting of the slot index, name, and attachment. + public struct SkinEntry { + private readonly int slotIndex; + private readonly string name; + private readonly Attachment attachment; + internal readonly int hashCode; + + public SkinEntry (int slotIndex, string name, Attachment attachment) { + this.slotIndex = slotIndex; + this.name = name; + this.attachment = attachment; + this.hashCode = this.name.GetHashCode() + this.slotIndex * 37; + } + + public int SlotIndex { + get { + return slotIndex; + } + } + + /// The name the attachment is associated with, equivalent to the skin placeholder name in the Spine editor. + public String Name { + get { + return name; + } + } + + public Attachment Attachment { + get { + return attachment; + } + } + } + + // Avoids boxing in the dictionary and is necessary to omit entry.attachment in the comparison. + class SkinEntryComparer : IEqualityComparer { + internal static readonly SkinEntryComparer Instance = new SkinEntryComparer(); + + bool IEqualityComparer.Equals (SkinEntry e1, SkinEntry e2) { + if (e1.SlotIndex != e2.SlotIndex) return false; + if (!string.Equals(e1.Name, e2.Name, StringComparison.Ordinal)) return false; + return true; + } + + int IEqualityComparer.GetHashCode (SkinEntry e) { + return e.Name.GetHashCode() + e.SlotIndex * 37; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs.meta new file mode 100644 index 0000000..1e9f87e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Skin.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7df8caa3a771f464e803316a6b18c909 +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs new file mode 100644 index 0000000..c7e45a8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs @@ -0,0 +1,196 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + + /// + /// Stores a slot's current pose. Slots organize attachments for {@link Skeleton#drawOrder} purposes and provide a place to store + /// state for an attachment.State cannot be stored in an attachment itself because attachments are stateless and may be shared + /// across multiple skeletons. + /// + public class Slot { + internal SlotData data; + internal Bone bone; + internal float r, g, b, a; + internal float r2, g2, b2; + internal bool hasSecondColor; + internal Attachment attachment; + internal float attachmentTime; + internal ExposedList deform = new ExposedList(); + internal int attachmentState; + + public Slot (SlotData data, Bone bone) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + if (bone == null) throw new ArgumentNullException("bone", "bone cannot be null."); + this.data = data; + this.bone = bone; + + // darkColor = data.darkColor == null ? null : new Color(); + if (data.hasSecondColor) { + r2 = g2 = b2 = 0; + } + + SetToSetupPose(); + } + + /// Copy constructor. + public Slot(Slot slot, Bone bone) { + if (slot == null) throw new ArgumentNullException("slot", "slot cannot be null."); + if (bone == null) throw new ArgumentNullException("bone", "bone cannot be null."); + data = slot.data; + this.bone = bone; + r = slot.r; + g = slot.g; + b = slot.b; + a = slot.a; + + // darkColor = slot.darkColor == null ? null : new Color(slot.darkColor); + if (slot.hasSecondColor) { + r2 = slot.r2; + g2 = slot.g2; + b2 = slot.b2; + } else { + r2 = g2 = b2 = 0; + } + hasSecondColor = slot.hasSecondColor; + + attachment = slot.attachment; + attachmentTime = slot.attachmentTime; + deform.AddRange(slot.deform); + } + + /// The slot's setup pose data. + public SlotData Data { get { return data; } } + /// The bone this slot belongs to. + public Bone Bone { get { return bone; } } + /// The skeleton this slot belongs to. + public Skeleton Skeleton { get { return bone.skeleton; } } + /// The color used to tint the slot's attachment. If is set, this is used as the light color for two + /// color tinting. + public float R { get { return r; } set { r = value; } } + /// The color used to tint the slot's attachment. If is set, this is used as the light color for two + /// color tinting. + public float G { get { return g; } set { g = value; } } + /// The color used to tint the slot's attachment. If is set, this is used as the light color for two + /// color tinting. + public float B { get { return b; } set { b = value; } } + /// The color used to tint the slot's attachment. If is set, this is used as the light color for two + /// color tinting. + public float A { get { return a; } set { a = value; } } + + public void ClampColor() { + r = MathUtils.Clamp(r, 0, 1); + g = MathUtils.Clamp(g, 0, 1); + b = MathUtils.Clamp(b, 0, 1); + a = MathUtils.Clamp(a, 0, 1); + } + + /// The dark color used to tint the slot's attachment for two color tinting, ignored if two color tinting is not used. + /// + public float R2 { get { return r2; } set { r2 = value; } } + /// The dark color used to tint the slot's attachment for two color tinting, ignored if two color tinting is not used. + /// + public float G2 { get { return g2; } set { g2 = value; } } + /// The dark color used to tint the slot's attachment for two color tinting, ignored if two color tinting is not used. + /// + public float B2 { get { return b2; } set { b2 = value; } } + /// Whether R2 G2 B2 are used to tint the slot's attachment for two color tinting. False if two color tinting is not used. + public bool HasSecondColor { get { return data.hasSecondColor; } set { data.hasSecondColor = value; } } + + public void ClampSecondColor () { + r2 = MathUtils.Clamp(r2, 0, 1); + g2 = MathUtils.Clamp(g2, 0, 1); + b2 = MathUtils.Clamp(b2, 0, 1); + } + + public Attachment Attachment { + /// The current attachment for the slot, or null if the slot has no attachment. + get { return attachment; } + /// + /// Sets the slot's attachment and, if the attachment changed, resets and clears + /// . + /// May be null. + set { + if (attachment == value) return; + attachment = value; + attachmentTime = bone.skeleton.time; + deform.Clear(false); + } + } + + /// The time that has elapsed since the last time the attachment was set or cleared. Relies on Skeleton + /// + public float AttachmentTime { + get { return bone.skeleton.time - attachmentTime; } + set { attachmentTime = bone.skeleton.time - value; } + } + + /// Vertices to deform the slot's attachment. For an unweighted mesh, the entries are local positions for each vertex. For a + /// weighted mesh, the entries are an offset for each vertex which will be added to the mesh's local vertex positions. + /// + /// See and . + public ExposedList Deform { + get { + return deform; + } + set { + if (deform == null) throw new ArgumentNullException("deform", "deform cannot be null."); + deform = value; + } + } + + /// Sets this slot to the setup pose. + public void SetToSetupPose () { + r = data.r; + g = data.g; + b = data.b; + a = data.a; + + // if (darkColor != null) darkColor.set(data.darkColor); + if (HasSecondColor) { + r2 = data.r2; + g2 = data.g2; + b2 = data.b2; + } + + if (data.attachmentName == null) + Attachment = null; + else { + attachment = null; + Attachment = bone.skeleton.GetAttachment(data.index, data.attachmentName); + } + } + + override public string ToString () { + return data.name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs.meta new file mode 100644 index 0000000..4bc86f4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Slot.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6974c4b5c87687140a2417201ea43066 +timeCreated: 1456265154 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs new file mode 100644 index 0000000..a51b294 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs @@ -0,0 +1,77 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class SlotData { + internal int index; + internal string name; + internal BoneData boneData; + internal float r = 1, g = 1, b = 1, a = 1; + internal float r2 = 0, g2 = 0, b2 = 0; + internal bool hasSecondColor = false; + internal string attachmentName; + internal BlendMode blendMode; + + /// The index of the slot in . + public int Index { get { return index; } } + /// The name of the slot, which is unique across all slots in the skeleton. + public string Name { get { return name; } } + /// The bone this slot belongs to. + public BoneData BoneData { get { return boneData; } } + public float R { get { return r; } set { r = value; } } + public float G { get { return g; } set { g = value; } } + public float B { get { return b; } set { b = value; } } + public float A { get { return a; } set { a = value; } } + + public float R2 { get { return r2; } set { r2 = value; } } + public float G2 { get { return g2; } set { g2 = value; } } + public float B2 { get { return b2; } set { b2 = value; } } + public bool HasSecondColor { get { return hasSecondColor; } set { hasSecondColor = value; } } + + /// The name of the attachment that is visible for this slot in the setup pose, or null if no attachment is visible. + public String AttachmentName { get { return attachmentName; } set { attachmentName = value; } } + /// The blend mode for drawing the slot's attachment. + public BlendMode BlendMode { get { return blendMode; } set { blendMode = value; } } + + public SlotData (int index, String name, BoneData boneData) { + if (index < 0) throw new ArgumentException ("index must be >= 0.", "index"); + if (name == null) throw new ArgumentNullException("name", "name cannot be null."); + if (boneData == null) throw new ArgumentNullException("boneData", "boneData cannot be null."); + this.index = index; + this.name = name; + this.boneData = boneData; + } + + override public string ToString () { + return name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs.meta new file mode 100644 index 0000000..d203ba7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/SlotData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f28cb47bc1e8b434c85e6f69b2c9e15e +timeCreated: 1456265156 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs new file mode 100644 index 0000000..2576102 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs @@ -0,0 +1,313 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + /// + /// + /// Stores the current pose for a transform constraint. A transform constraint adjusts the world transform of the constrained + /// bones to match that of the target bone. + /// + /// See Transform constraints in the Spine User Guide. + /// + public class TransformConstraint : IUpdatable { + internal TransformConstraintData data; + internal ExposedList bones; + internal Bone target; + internal float rotateMix, translateMix, scaleMix, shearMix; + + internal bool active; + + public TransformConstraint (TransformConstraintData data, Skeleton skeleton) { + if (data == null) throw new ArgumentNullException("data", "data cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); + this.data = data; + rotateMix = data.rotateMix; + translateMix = data.translateMix; + scaleMix = data.scaleMix; + shearMix = data.shearMix; + + bones = new ExposedList(); + foreach (BoneData boneData in data.bones) + bones.Add (skeleton.FindBone(boneData.name)); + + target = skeleton.FindBone(data.target.name); + } + + /// Copy constructor. + public TransformConstraint (TransformConstraint constraint, Skeleton skeleton) { + if (constraint == null) throw new ArgumentNullException("constraint cannot be null."); + if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); + data = constraint.data; + bones = new ExposedList(constraint.Bones.Count); + foreach (Bone bone in constraint.Bones) + bones.Add(skeleton.Bones.Items[bone.data.index]); + target = skeleton.Bones.Items[constraint.target.data.index]; + rotateMix = constraint.rotateMix; + translateMix = constraint.translateMix; + scaleMix = constraint.scaleMix; + shearMix = constraint.shearMix; + } + + /// Applies the constraint to the constrained bones. + public void Apply () { + Update(); + } + + public void Update () { + if (data.local) { + if (data.relative) + ApplyRelativeLocal(); + else + ApplyAbsoluteLocal(); + } else { + if (data.relative) + ApplyRelativeWorld(); + else + ApplyAbsoluteWorld(); + } + } + + void ApplyAbsoluteWorld () { + float rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + Bone target = this.target; + float ta = target.a, tb = target.b, tc = target.c, td = target.d; + float degRadReflect = ta * td - tb * tc > 0 ? MathUtils.DegRad : -MathUtils.DegRad; + float offsetRotation = data.offsetRotation * degRadReflect, offsetShearY = data.offsetShearY * degRadReflect; + var bones = this.bones; + for (int i = 0, n = bones.Count; i < n; i++) { + Bone bone = bones.Items[i]; + bool modified = false; + + if (rotateMix != 0) { + float a = bone.a, b = bone.b, c = bone.c, d = bone.d; + float r = MathUtils.Atan2(tc, ta) - MathUtils.Atan2(c, a) + offsetRotation; + if (r > MathUtils.PI) + r -= MathUtils.PI2; + else if (r < -MathUtils.PI) r += MathUtils.PI2; + r *= rotateMix; + float cos = MathUtils.Cos(r), sin = MathUtils.Sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + modified = true; + } + + if (translateMix != 0) { + float tx, ty; //Vector2 temp = this.temp; + target.LocalToWorld(data.offsetX, data.offsetY, out tx, out ty); //target.localToWorld(temp.set(data.offsetX, data.offsetY)); + bone.worldX += (tx - bone.worldX) * translateMix; + bone.worldY += (ty - bone.worldY) * translateMix; + modified = true; + } + + if (scaleMix > 0) { + float s = (float)Math.Sqrt(bone.a * bone.a + bone.c * bone.c); + if (s != 0) s = (s + ((float)Math.Sqrt(ta * ta + tc * tc) - s + data.offsetScaleX) * scaleMix) / s; + bone.a *= s; + bone.c *= s; + s = (float)Math.Sqrt(bone.b * bone.b + bone.d * bone.d); + if (s != 0) s = (s + ((float)Math.Sqrt(tb * tb + td * td) - s + data.offsetScaleY) * scaleMix) / s; + bone.b *= s; + bone.d *= s; + modified = true; + } + + if (shearMix > 0) { + float b = bone.b, d = bone.d; + float by = MathUtils.Atan2(d, b); + float r = MathUtils.Atan2(td, tb) - MathUtils.Atan2(tc, ta) - (by - MathUtils.Atan2(bone.c, bone.a)); + if (r > MathUtils.PI) + r -= MathUtils.PI2; + else if (r < -MathUtils.PI) r += MathUtils.PI2; + r = by + (r + offsetShearY) * shearMix; + float s = (float)Math.Sqrt(b * b + d * d); + bone.b = MathUtils.Cos(r) * s; + bone.d = MathUtils.Sin(r) * s; + modified = true; + } + + if (modified) bone.appliedValid = false; + } + } + + void ApplyRelativeWorld () { + float rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + Bone target = this.target; + float ta = target.a, tb = target.b, tc = target.c, td = target.d; + float degRadReflect = ta * td - tb * tc > 0 ? MathUtils.DegRad : -MathUtils.DegRad; + float offsetRotation = data.offsetRotation * degRadReflect, offsetShearY = data.offsetShearY * degRadReflect; + var bones = this.bones; + for (int i = 0, n = bones.Count; i < n; i++) { + Bone bone = bones.Items[i]; + bool modified = false; + + if (rotateMix != 0) { + float a = bone.a, b = bone.b, c = bone.c, d = bone.d; + float r = MathUtils.Atan2(tc, ta) + offsetRotation; + if (r > MathUtils.PI) + r -= MathUtils.PI2; + else if (r < -MathUtils.PI) r += MathUtils.PI2; + r *= rotateMix; + float cos = MathUtils.Cos(r), sin = MathUtils.Sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + modified = true; + } + + if (translateMix != 0) { + float tx, ty; //Vector2 temp = this.temp; + target.LocalToWorld(data.offsetX, data.offsetY, out tx, out ty); //target.localToWorld(temp.set(data.offsetX, data.offsetY)); + bone.worldX += tx * translateMix; + bone.worldY += ty * translateMix; + modified = true; + } + + if (scaleMix > 0) { + float s = ((float)Math.Sqrt(ta * ta + tc * tc) - 1 + data.offsetScaleX) * scaleMix + 1; + bone.a *= s; + bone.c *= s; + s = ((float)Math.Sqrt(tb * tb + td * td) - 1 + data.offsetScaleY) * scaleMix + 1; + bone.b *= s; + bone.d *= s; + modified = true; + } + + if (shearMix > 0) { + float r = MathUtils.Atan2(td, tb) - MathUtils.Atan2(tc, ta); + if (r > MathUtils.PI) + r -= MathUtils.PI2; + else if (r < -MathUtils.PI) r += MathUtils.PI2; + float b = bone.b, d = bone.d; + r = MathUtils.Atan2(d, b) + (r - MathUtils.PI / 2 + offsetShearY) * shearMix; + float s = (float)Math.Sqrt(b * b + d * d); + bone.b = MathUtils.Cos(r) * s; + bone.d = MathUtils.Sin(r) * s; + modified = true; + } + + if (modified) bone.appliedValid = false; + } + } + + void ApplyAbsoluteLocal () { + float rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + Bone target = this.target; + if (!target.appliedValid) target.UpdateAppliedTransform(); + var bonesItems = this.bones.Items; + for (int i = 0, n = this.bones.Count; i < n; i++) { + Bone bone = bonesItems[i]; + if (!bone.appliedValid) bone.UpdateAppliedTransform(); + + float rotation = bone.arotation; + if (rotateMix != 0) { + float r = target.arotation - rotation + data.offsetRotation; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + rotation += r * rotateMix; + } + + float x = bone.ax, y = bone.ay; + if (translateMix != 0) { + x += (target.ax - x + data.offsetX) * translateMix; + y += (target.ay - y + data.offsetY) * translateMix; + } + + float scaleX = bone.ascaleX, scaleY = bone.ascaleY; + if (scaleMix != 0) { + if (scaleX != 0) scaleX = (scaleX + (target.ascaleX - scaleX + data.offsetScaleX) * scaleMix) / scaleX; + if (scaleY != 0) scaleY = (scaleY + (target.ascaleY - scaleY + data.offsetScaleY) * scaleMix) / scaleY; + } + + float shearY = bone.ashearY; + if (shearMix != 0) { + float r = target.ashearY - shearY + data.offsetShearY; + r -= (16384 - (int)(16384.499999999996 - r / 360)) * 360; + shearY += r * shearMix; + } + + bone.UpdateWorldTransform(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); + } + } + + void ApplyRelativeLocal () { + float rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + Bone target = this.target; + if (!target.appliedValid) target.UpdateAppliedTransform(); + var bonesItems = this.bones.Items; + for (int i = 0, n = this.bones.Count; i < n; i++) { + Bone bone = bonesItems[i]; + if (!bone.appliedValid) bone.UpdateAppliedTransform(); + + float rotation = bone.arotation; + if (rotateMix != 0) rotation += (target.arotation + data.offsetRotation) * rotateMix; + + float x = bone.ax, y = bone.ay; + if (translateMix != 0) { + x += (target.ax + data.offsetX) * translateMix; + y += (target.ay + data.offsetY) * translateMix; + } + + float scaleX = bone.ascaleX, scaleY = bone.ascaleY; + if (scaleMix != 0) { + scaleX *= ((target.ascaleX - 1 + data.offsetScaleX) * scaleMix) + 1; + scaleY *= ((target.ascaleY - 1 + data.offsetScaleY) * scaleMix) + 1; + } + + float shearY = bone.ashearY; + if (shearMix != 0) shearY += (target.ashearY + data.offsetShearY) * shearMix; + + bone.UpdateWorldTransform(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); + } + } + + /// The bones that will be modified by this transform constraint. + public ExposedList Bones { get { return bones; } } + /// The target bone whose world transform will be copied to the constrained bones. + public Bone Target { get { return target; } set { target = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained rotations. + public float RotateMix { get { return rotateMix; } set { rotateMix = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained translations. + public float TranslateMix { get { return translateMix; } set { translateMix = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained scales. + public float ScaleMix { get { return scaleMix; } set { scaleMix = value; } } + /// A percentage (0-1) that controls the mix between the constrained and unconstrained scales. + public float ShearMix { get { return shearMix; } set { shearMix = value; } } + public bool Active { get { return active; } } + /// The transform constraint's setup pose data. + public TransformConstraintData Data { get { return data; } } + + override public string ToString () { + return data.name; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs.meta new file mode 100644 index 0000000..b3e7ada --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraint.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2e30316a9733f8a4b8b6c362c06dfa11 +timeCreated: 1456265153 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs new file mode 100644 index 0000000..f3da4d6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs @@ -0,0 +1,60 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class TransformConstraintData : ConstraintData { + internal ExposedList bones = new ExposedList(); + internal BoneData target; + internal float rotateMix, translateMix, scaleMix, shearMix; + internal float offsetRotation, offsetX, offsetY, offsetScaleX, offsetScaleY, offsetShearY; + internal bool relative, local; + + public ExposedList Bones { get { return bones; } } + public BoneData Target { get { return target; } set { target = value; } } + public float RotateMix { get { return rotateMix; } set { rotateMix = value; } } + public float TranslateMix { get { return translateMix; } set { translateMix = value; } } + public float ScaleMix { get { return scaleMix; } set { scaleMix = value; } } + public float ShearMix { get { return shearMix; } set { shearMix = value; } } + + public float OffsetRotation { get { return offsetRotation; } set { offsetRotation = value; } } + public float OffsetX { get { return offsetX; } set { offsetX = value; } } + public float OffsetY { get { return offsetY; } set { offsetY = value; } } + public float OffsetScaleX { get { return offsetScaleX; } set { offsetScaleX = value; } } + public float OffsetScaleY { get { return offsetScaleY; } set { offsetScaleY = value; } } + public float OffsetShearY { get { return offsetShearY; } set { offsetShearY = value; } } + + public bool Relative { get { return relative; } set { relative = value; } } + public bool Local { get { return local; } set { local = value; } } + + public TransformConstraintData (string name) : base(name) { + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs.meta new file mode 100644 index 0000000..d8b3f27 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/TransformConstraintData.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7edeecc9bd7dd44faabf24f29b119a0 +timeCreated: 1456265155 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs new file mode 100644 index 0000000..f0cc8dc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs @@ -0,0 +1,277 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; + +namespace Spine { + public class Triangulator { + private readonly ExposedList> convexPolygons = new ExposedList>(); + private readonly ExposedList> convexPolygonsIndices = new ExposedList>(); + + private readonly ExposedList indicesArray = new ExposedList(); + private readonly ExposedList isConcaveArray = new ExposedList(); + private readonly ExposedList triangles = new ExposedList(); + + private readonly Pool> polygonPool = new Pool>(); + private readonly Pool> polygonIndicesPool = new Pool>(); + + public ExposedList Triangulate (ExposedList verticesArray) { + var vertices = verticesArray.Items; + int vertexCount = verticesArray.Count >> 1; + + var indicesArray = this.indicesArray; + indicesArray.Clear(); + int[] indices = indicesArray.Resize(vertexCount).Items; + for (int i = 0; i < vertexCount; i++) + indices[i] = i; + + var isConcaveArray = this.isConcaveArray; + bool[] isConcave = isConcaveArray.Resize(vertexCount).Items; + for (int i = 0, n = vertexCount; i < n; ++i) + isConcave[i] = IsConcave(i, vertexCount, vertices, indices); + + var triangles = this.triangles; + triangles.Clear(); + triangles.EnsureCapacity(Math.Max(0, vertexCount - 2) << 2); + + while (vertexCount > 3) { + // Find ear tip. + int previous = vertexCount - 1, i = 0, next = 1; + + // outer: + while (true) { + if (!isConcave[i]) { + int p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; + float p1x = vertices[p1], p1y = vertices[p1 + 1]; + float p2x = vertices[p2], p2y = vertices[p2 + 1]; + float p3x = vertices[p3], p3y = vertices[p3 + 1]; + for (int ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { + if (!isConcave[ii]) continue; + int v = indices[ii] << 1; + float vx = vertices[v], vy = vertices[v + 1]; + if (PositiveArea(p3x, p3y, p1x, p1y, vx, vy)) { + if (PositiveArea(p1x, p1y, p2x, p2y, vx, vy)) { + if (PositiveArea(p2x, p2y, p3x, p3y, vx, vy)) goto break_outer; // break outer; + } + } + } + break; + } + break_outer: + + if (next == 0) { + do { + if (!isConcave[i]) break; + i--; + } while (i > 0); + break; + } + + previous = i; + i = next; + next = (next + 1) % vertexCount; + } + + // Cut ear tip. + triangles.Add(indices[(vertexCount + i - 1) % vertexCount]); + triangles.Add(indices[i]); + triangles.Add(indices[(i + 1) % vertexCount]); + indicesArray.RemoveAt(i); + isConcaveArray.RemoveAt(i); + vertexCount--; + + int previousIndex = (vertexCount + i - 1) % vertexCount; + int nextIndex = i == vertexCount ? 0 : i; + isConcave[previousIndex] = IsConcave(previousIndex, vertexCount, vertices, indices); + isConcave[nextIndex] = IsConcave(nextIndex, vertexCount, vertices, indices); + } + + if (vertexCount == 3) { + triangles.Add(indices[2]); + triangles.Add(indices[0]); + triangles.Add(indices[1]); + } + + return triangles; + } + + public ExposedList> Decompose (ExposedList verticesArray, ExposedList triangles) { + var vertices = verticesArray.Items; + var convexPolygons = this.convexPolygons; + for (int i = 0, n = convexPolygons.Count; i < n; i++) { + polygonPool.Free(convexPolygons.Items[i]); + } + convexPolygons.Clear(); + + var convexPolygonsIndices = this.convexPolygonsIndices; + for (int i = 0, n = convexPolygonsIndices.Count; i < n; i++) { + polygonIndicesPool.Free(convexPolygonsIndices.Items[i]); + } + convexPolygonsIndices.Clear(); + + var polygonIndices = polygonIndicesPool.Obtain(); + polygonIndices.Clear(); + + var polygon = polygonPool.Obtain(); + polygon.Clear(); + + // Merge subsequent triangles if they form a triangle fan. + int fanBaseIndex = -1, lastWinding = 0; + int[] trianglesItems = triangles.Items; + for (int i = 0, n = triangles.Count; i < n; i += 3) { + int t1 = trianglesItems[i] << 1, t2 = trianglesItems[i + 1] << 1, t3 = trianglesItems[i + 2] << 1; + float x1 = vertices[t1], y1 = vertices[t1 + 1]; + float x2 = vertices[t2], y2 = vertices[t2 + 1]; + float x3 = vertices[t3], y3 = vertices[t3 + 1]; + + // If the base of the last triangle is the same as this triangle, check if they form a convex polygon (triangle fan). + var merged = false; + if (fanBaseIndex == t1) { + int o = polygon.Count - 4; + float[] p = polygon.Items; + int winding1 = Winding(p[o], p[o + 1], p[o + 2], p[o + 3], x3, y3); + int winding2 = Winding(x3, y3, p[0], p[1], p[2], p[3]); + if (winding1 == lastWinding && winding2 == lastWinding) { + polygon.Add(x3); + polygon.Add(y3); + polygonIndices.Add(t3); + merged = true; + } + } + + // Otherwise make this triangle the new base. + if (!merged) { + if (polygon.Count > 0) { + convexPolygons.Add(polygon); + convexPolygonsIndices.Add(polygonIndices); + } else { + polygonPool.Free(polygon); + polygonIndicesPool.Free(polygonIndices); + } + polygon = polygonPool.Obtain(); + polygon.Clear(); + polygon.Add(x1); + polygon.Add(y1); + polygon.Add(x2); + polygon.Add(y2); + polygon.Add(x3); + polygon.Add(y3); + polygonIndices = polygonIndicesPool.Obtain(); + polygonIndices.Clear(); + polygonIndices.Add(t1); + polygonIndices.Add(t2); + polygonIndices.Add(t3); + lastWinding = Winding(x1, y1, x2, y2, x3, y3); + fanBaseIndex = t1; + } + } + + if (polygon.Count > 0) { + convexPolygons.Add(polygon); + convexPolygonsIndices.Add(polygonIndices); + } + + // Go through the list of polygons and try to merge the remaining triangles with the found triangle fans. + for (int i = 0, n = convexPolygons.Count; i < n; i++) { + polygonIndices = convexPolygonsIndices.Items[i]; + if (polygonIndices.Count == 0) continue; + int firstIndex = polygonIndices.Items[0]; + int lastIndex = polygonIndices.Items[polygonIndices.Count - 1]; + + polygon = convexPolygons.Items[i]; + int o = polygon.Count - 4; + float[] p = polygon.Items; + float prevPrevX = p[o], prevPrevY = p[o + 1]; + float prevX = p[o + 2], prevY = p[o + 3]; + float firstX = p[0], firstY = p[1]; + float secondX = p[2], secondY = p[3]; + int winding = Winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); + + for (int ii = 0; ii < n; ii++) { + if (ii == i) continue; + var otherIndices = convexPolygonsIndices.Items[ii]; + if (otherIndices.Count != 3) continue; + int otherFirstIndex = otherIndices.Items[0]; + int otherSecondIndex = otherIndices.Items[1]; + int otherLastIndex = otherIndices.Items[2]; + + var otherPoly = convexPolygons.Items[ii]; + float x3 = otherPoly.Items[otherPoly.Count - 2], y3 = otherPoly.Items[otherPoly.Count - 1]; + + if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; + int winding1 = Winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); + int winding2 = Winding(x3, y3, firstX, firstY, secondX, secondY); + if (winding1 == winding && winding2 == winding) { + otherPoly.Clear(); + otherIndices.Clear(); + polygon.Add(x3); + polygon.Add(y3); + polygonIndices.Add(otherLastIndex); + prevPrevX = prevX; + prevPrevY = prevY; + prevX = x3; + prevY = y3; + ii = 0; + } + } + } + + // Remove empty polygons that resulted from the merge step above. + for (int i = convexPolygons.Count - 1; i >= 0; i--) { + polygon = convexPolygons.Items[i]; + if (polygon.Count == 0) { + convexPolygons.RemoveAt(i); + polygonPool.Free(polygon); + polygonIndices = convexPolygonsIndices.Items[i]; + convexPolygonsIndices.RemoveAt(i); + polygonIndicesPool.Free(polygonIndices); + } + } + + return convexPolygons; + } + + static private bool IsConcave (int index, int vertexCount, float[] vertices, int[] indices) { + int previous = indices[(vertexCount + index - 1) % vertexCount] << 1; + int current = indices[index] << 1; + int next = indices[(index + 1) % vertexCount] << 1; + return !PositiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], + vertices[next + 1]); + } + + static private bool PositiveArea (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { + return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; + } + + static private int Winding (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { + float px = p2x - p1x, py = p2y - p1y; + return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs.meta new file mode 100644 index 0000000..cdabaeb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-csharp/Triangulator.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 90a8832a1f3c5f846b8773dc0e1c3238 +timeCreated: 1493126637 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef new file mode 100644 index 0000000..cabce6f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef @@ -0,0 +1,4 @@ +{ + "name": "spine-unity", + "references": [] +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef.meta new file mode 100644 index 0000000..549f3cb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 68765d262e2128e4ab49c983f3411946 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.meta new file mode 100644 index 0000000..f89227f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 29a3535756b284a428d35dcd4327185e +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types.meta new file mode 100644 index 0000000..ade58c0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1dc4b7c23385e8c43ad19d01cbed78ce +folderAsset: yes +timeCreated: 1455489521 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs new file mode 100644 index 0000000..494ce23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs @@ -0,0 +1,66 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#define AUTOINIT_SPINEREFERENCE + +using UnityEngine; + +namespace Spine.Unity { + [CreateAssetMenu(menuName = "Spine/Animation Reference Asset", order = 100)] + public class AnimationReferenceAsset : ScriptableObject, IHasSkeletonDataAsset { + const bool QuietSkeletonData = true; + + [SerializeField] protected SkeletonDataAsset skeletonDataAsset; + [SerializeField, SpineAnimation] protected string animationName; + private Animation animation; + + public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } + + public Animation Animation { + get { + #if AUTOINIT_SPINEREFERENCE + if (animation == null) + Initialize(); + #endif + + return animation; + } + } + + public void Initialize () { + if (skeletonDataAsset == null) return; + this.animation = skeletonDataAsset.GetSkeletonData(AnimationReferenceAsset.QuietSkeletonData).FindAnimation(animationName); + if (this.animation == null) Debug.LogWarningFormat("Animation '{0}' not found in SkeletonData : {1}.", animationName, skeletonDataAsset.name); + } + + public static implicit operator Animation (AnimationReferenceAsset asset) { + return asset.Animation; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs.meta new file mode 100644 index 0000000..dbfadcd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AnimationReferenceAsset.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6e3e95a05e4c9774397eeeb7bdee8ccb +timeCreated: 1523328498 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 52b12ec801461494185a4d3dc66f3d1d, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs new file mode 100644 index 0000000..a987b54 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs @@ -0,0 +1,44 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + public abstract class AtlasAssetBase : ScriptableObject { + public abstract Material PrimaryMaterial { get; } + public abstract IEnumerable Materials { get; } + public abstract int MaterialCount { get; } + + public abstract bool IsLoaded { get; } + public abstract void Clear (); + public abstract Atlas GetAtlas (); + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs.meta new file mode 100644 index 0000000..5469af6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/AtlasAssetBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 787a36933c1c6e14db2104c01ed92dcb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs new file mode 100644 index 0000000..4ddcf1b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs @@ -0,0 +1,144 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using Spine; + +namespace Spine.Unity { + [System.Serializable] + public class BlendModeMaterials { + + [System.Serializable] + public class ReplacementMaterial { + public string pageName; + public Material material; + } + + [SerializeField, HideInInspector] protected bool requiresBlendModeMaterials = false; + public bool applyAdditiveMaterial = false; + + public List additiveMaterials = new List(); + public List multiplyMaterials = new List(); + public List screenMaterials = new List(); + + public bool RequiresBlendModeMaterials { get { return requiresBlendModeMaterials; } set { requiresBlendModeMaterials = value; } } + + #if UNITY_EDITOR + public void TransferSettingsFrom (BlendModeMaterialsAsset modifierAsset) { + applyAdditiveMaterial = modifierAsset.applyAdditiveMaterial; + } + + public bool UpdateBlendmodeMaterialsRequiredState (SkeletonData skeletonData) { + requiresBlendModeMaterials = false; + + if (skeletonData == null) throw new ArgumentNullException("skeletonData"); + + var skinEntries = new List(); + var slotsItems = skeletonData.Slots.Items; + for (int slotIndex = 0, slotCount = skeletonData.Slots.Count; slotIndex < slotCount; slotIndex++) { + var slot = slotsItems[slotIndex]; + if (slot.blendMode == BlendMode.Normal) continue; + if (!applyAdditiveMaterial && slot.blendMode == BlendMode.Additive) continue; + + skinEntries.Clear(); + foreach (var skin in skeletonData.Skins) + skin.GetAttachments(slotIndex, skinEntries); + + foreach (var entry in skinEntries) { + if (entry.Attachment is IHasRendererObject) { + requiresBlendModeMaterials = true; + return true; + } + } + } + return false; + } + #endif + public void ApplyMaterials (SkeletonData skeletonData) { + if (skeletonData == null) throw new ArgumentNullException("skeletonData"); + if (!requiresBlendModeMaterials) + return; + + var skinEntries = new List(); + var slotsItems = skeletonData.Slots.Items; + for (int slotIndex = 0, slotCount = skeletonData.Slots.Count; slotIndex < slotCount; slotIndex++) { + var slot = slotsItems[slotIndex]; + if (slot.blendMode == BlendMode.Normal) continue; + if (!applyAdditiveMaterial && slot.blendMode == BlendMode.Additive) continue; + + List replacementMaterials = null; + switch (slot.blendMode) { + case BlendMode.Multiply: + replacementMaterials = multiplyMaterials; + break; + case BlendMode.Screen: + replacementMaterials = screenMaterials; + break; + case BlendMode.Additive: + replacementMaterials = additiveMaterials; + break; + } + if (replacementMaterials == null) + continue; + + skinEntries.Clear(); + foreach (var skin in skeletonData.Skins) + skin.GetAttachments(slotIndex, skinEntries); + + foreach (var entry in skinEntries) { + var renderableAttachment = entry.Attachment as IHasRendererObject; + if (renderableAttachment != null) { + renderableAttachment.RendererObject = CloneAtlasRegionWithMaterial( + (AtlasRegion)renderableAttachment.RendererObject, replacementMaterials); + } + } + } + } + + protected AtlasRegion CloneAtlasRegionWithMaterial (AtlasRegion originalRegion, List replacementMaterials) { + var newRegion = originalRegion.Clone(); + Material material = null; + foreach (var replacement in replacementMaterials) { + if (replacement.pageName == originalRegion.page.name) { + material = replacement.material; + break; + } + } + + AtlasPage originalPage = originalRegion.page; + var newPage = originalPage.Clone(); + newPage.rendererObject = material; + newRegion.page = newPage; + return newRegion; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs.meta new file mode 100644 index 0000000..8c1222e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/BlendModeMaterials.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d03ca55657e89b949a4c07bc9207beac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs new file mode 100644 index 0000000..38e41df --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs @@ -0,0 +1,65 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#define AUTOINIT_SPINEREFERENCE + +using UnityEngine; + +namespace Spine.Unity { + [CreateAssetMenu(menuName = "Spine/EventData Reference Asset", order = 100)] + public class EventDataReferenceAsset : ScriptableObject { + const bool QuietSkeletonData = true; + + [SerializeField] protected SkeletonDataAsset skeletonDataAsset; + [SerializeField, SpineEvent(dataField: "skeletonDataAsset")] protected string eventName; + + EventData eventData; + public EventData EventData { + get { + #if AUTOINIT_SPINEREFERENCE + if (eventData == null) + Initialize(); + #endif + return eventData; + } + } + + public void Initialize () { + if (skeletonDataAsset == null) + return; + this.eventData = skeletonDataAsset.GetSkeletonData(EventDataReferenceAsset.QuietSkeletonData).FindEvent(eventName); + if (this.eventData == null) + Debug.LogWarningFormat("Event Data '{0}' not found in SkeletonData : {1}.", eventName, skeletonDataAsset.name); + } + + public static implicit operator EventData (EventDataReferenceAsset asset) { + return asset.EventData; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs.meta new file mode 100644 index 0000000..cb26130 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/EventDataReferenceAsset.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8e60be42c1473144db0fd3337c25b500 +timeCreated: 1523330891 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: d226a80acc775714aa78b85e16a00e9b, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs new file mode 100644 index 0000000..37e7eaa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs @@ -0,0 +1,83 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using UnityEngine; + +namespace Spine.Unity { + + public class RegionlessAttachmentLoader : AttachmentLoader { + + static AtlasRegion emptyRegion; + static AtlasRegion EmptyRegion { + get { + if (emptyRegion == null) { + emptyRegion = new AtlasRegion { + name = "Empty AtlasRegion", + page = new AtlasPage { + name = "Empty AtlasPage", + rendererObject = new Material(Shader.Find("Spine/Special/HiddenPass")) { name = "NoRender Material" } + } + }; + } + return emptyRegion; + } + } + + public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) { + RegionAttachment attachment = new RegionAttachment(name) { + RendererObject = EmptyRegion + }; + return attachment; + } + + public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) { + MeshAttachment attachment = new MeshAttachment(name) { + RendererObject = EmptyRegion + }; + return attachment; + } + + public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) { + return new BoundingBoxAttachment(name); + } + + public PathAttachment NewPathAttachment (Skin skin, string name) { + return new PathAttachment(name); + } + + public PointAttachment NewPointAttachment (Skin skin, string name) { + return new PointAttachment(name); + } + + public ClippingAttachment NewClippingAttachment (Skin skin, string name) { + return new ClippingAttachment(name); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta new file mode 100644 index 0000000..5d7a368 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/RegionlessAttachmentLoader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 15f0f78b87720c047a320c5e0e3f91b7 +timeCreated: 1520505662 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs new file mode 100644 index 0000000..746d2a4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs @@ -0,0 +1,262 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +using CompatibilityProblemInfo = Spine.Unity.SkeletonDataCompatibility.CompatibilityProblemInfo; + +namespace Spine.Unity { + + [CreateAssetMenu(fileName = "New SkeletonDataAsset", menuName = "Spine/SkeletonData Asset")] + public class SkeletonDataAsset : ScriptableObject { + #region Inspector + public AtlasAssetBase[] atlasAssets = new AtlasAssetBase[0]; + + #if SPINE_TK2D + public tk2dSpriteCollectionData spriteCollection; + public float scale = 1f; + #else + public float scale = 0.01f; + #endif + public TextAsset skeletonJSON; + + public bool isUpgradingBlendModeMaterials = false; + public BlendModeMaterials blendModeMaterials = new BlendModeMaterials(); + + [Tooltip("Use SkeletonDataModifierAssets to apply changes to the SkeletonData after being loaded, such as apply blend mode Materials to Attachments under slots with special blend modes.")] + public List skeletonDataModifiers = new List(); + + [SpineAnimation(includeNone: false)] + public string[] fromAnimation = new string[0]; + [SpineAnimation(includeNone: false)] + public string[] toAnimation = new string[0]; + public float[] duration = new float[0]; + public float defaultMix; + public RuntimeAnimatorController controller; + + public bool IsLoaded { get { return this.skeletonData != null; } } + + void Reset () { + Clear(); + } + #endregion + + SkeletonData skeletonData; + AnimationStateData stateData; + + #region Runtime Instantiation + /// + /// Creates a runtime SkeletonDataAsset. + public static SkeletonDataAsset CreateRuntimeInstance (TextAsset skeletonDataFile, AtlasAssetBase atlasAsset, bool initialize, float scale = 0.01f) { + return CreateRuntimeInstance(skeletonDataFile, new [] {atlasAsset}, initialize, scale); + } + + /// + /// Creates a runtime SkeletonDataAsset. + public static SkeletonDataAsset CreateRuntimeInstance (TextAsset skeletonDataFile, AtlasAssetBase[] atlasAssets, bool initialize, float scale = 0.01f) { + SkeletonDataAsset skeletonDataAsset = ScriptableObject.CreateInstance(); + skeletonDataAsset.Clear(); + skeletonDataAsset.skeletonJSON = skeletonDataFile; + skeletonDataAsset.atlasAssets = atlasAssets; + skeletonDataAsset.scale = scale; + + if (initialize) + skeletonDataAsset.GetSkeletonData(true); + + return skeletonDataAsset; + } + #endregion + + /// Clears the loaded SkeletonData and AnimationStateData. Use this to force a reload for the next time GetSkeletonData is called. + public void Clear () { + skeletonData = null; + stateData = null; + } + + public AnimationStateData GetAnimationStateData () { + if (stateData != null) + return stateData; + GetSkeletonData(false); + return stateData; + } + + /// Loads, caches and returns the SkeletonData from the skeleton data file. Returns the cached SkeletonData after the first time it is called. Pass false to prevent direct errors from being logged. + public SkeletonData GetSkeletonData (bool quiet) { + if (skeletonJSON == null) { + if (!quiet) + Debug.LogError("Skeleton JSON file not set for SkeletonData asset: " + name, this); + Clear(); + return null; + } + + // Disabled to support attachmentless/skinless SkeletonData. + // if (atlasAssets == null) { + // atlasAssets = new AtlasAsset[0]; + // if (!quiet) + // Debug.LogError("Atlas not set for SkeletonData asset: " + name, this); + // Clear(); + // return null; + // } + // #if !SPINE_TK2D + // if (atlasAssets.Length == 0) { + // Clear(); + // return null; + // } + // #else + // if (atlasAssets.Length == 0 && spriteCollection == null) { + // Clear(); + // return null; + // } + // #endif + + if (skeletonData != null) + return skeletonData; + + AttachmentLoader attachmentLoader; + float skeletonDataScale; + Atlas[] atlasArray = this.GetAtlasArray(); + + #if !SPINE_TK2D + attachmentLoader = (atlasArray.Length == 0) ? (AttachmentLoader)new RegionlessAttachmentLoader() : (AttachmentLoader)new AtlasAttachmentLoader(atlasArray); + skeletonDataScale = scale; + #else + if (spriteCollection != null) { + attachmentLoader = new Spine.Unity.TK2D.SpriteCollectionAttachmentLoader(spriteCollection); + skeletonDataScale = (1.0f / (spriteCollection.invOrthoSize * spriteCollection.halfTargetHeight) * scale); + } else { + if (atlasArray.Length == 0) { + Reset(); + if (!quiet) Debug.LogError("Atlas not set for SkeletonData asset: " + name, this); + return null; + } + attachmentLoader = new AtlasAttachmentLoader(atlasArray); + skeletonDataScale = scale; + } + #endif + + bool hasBinaryExtension = skeletonJSON.name.ToLower().Contains(".skel"); + SkeletonData loadedSkeletonData = null; + + try { + if (hasBinaryExtension) + loadedSkeletonData = SkeletonDataAsset.ReadSkeletonData(skeletonJSON.bytes, attachmentLoader, skeletonDataScale); + else + loadedSkeletonData = SkeletonDataAsset.ReadSkeletonData(skeletonJSON.text, attachmentLoader, skeletonDataScale); + } catch (Exception ex) { + if (!quiet) + Debug.LogError("Error reading skeleton JSON file for SkeletonData asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, skeletonJSON); + } + + #if UNITY_EDITOR + if (loadedSkeletonData == null && !quiet && skeletonJSON != null) { + string problemDescription = null; + bool isSpineSkeletonData; + SkeletonDataCompatibility.VersionInfo fileVersion = SkeletonDataCompatibility.GetVersionInfo(skeletonJSON, out isSpineSkeletonData, ref problemDescription); + if (problemDescription != null) { + if (!quiet) + Debug.LogError(problemDescription, skeletonJSON); + return null; + } + CompatibilityProblemInfo compatibilityProblemInfo = SkeletonDataCompatibility.GetCompatibilityProblemInfo(fileVersion); + if (compatibilityProblemInfo != null) { + SkeletonDataCompatibility.DisplayCompatibilityProblem(compatibilityProblemInfo.DescriptionString(), skeletonJSON); + return null; + } + } + #endif + if (loadedSkeletonData == null) + return null; + + if (skeletonDataModifiers != null) { + foreach (var modifier in skeletonDataModifiers) { + if (modifier != null && !(isUpgradingBlendModeMaterials && modifier is BlendModeMaterialsAsset)) { + modifier.Apply(loadedSkeletonData); + } + } + } + if (!isUpgradingBlendModeMaterials) + blendModeMaterials.ApplyMaterials(loadedSkeletonData); + + this.InitializeWithData(loadedSkeletonData); + + return skeletonData; + } + + internal void InitializeWithData (SkeletonData sd) { + this.skeletonData = sd; + this.stateData = new AnimationStateData(skeletonData); + FillStateData(); + } + + public void FillStateData () { + if (stateData != null) { + stateData.defaultMix = defaultMix; + + for (int i = 0, n = fromAnimation.Length; i < n; i++) { + if (fromAnimation[i].Length == 0 || toAnimation[i].Length == 0) + continue; + stateData.SetMix(fromAnimation[i], toAnimation[i], duration[i]); + } + } + } + + internal Atlas[] GetAtlasArray () { + var returnList = new System.Collections.Generic.List(atlasAssets.Length); + for (int i = 0; i < atlasAssets.Length; i++) { + var aa = atlasAssets[i]; + if (aa == null) continue; + var a = aa.GetAtlas(); + if (a == null) continue; + returnList.Add(a); + } + return returnList.ToArray(); + } + + internal static SkeletonData ReadSkeletonData (byte[] bytes, AttachmentLoader attachmentLoader, float scale) { + using (var input = new MemoryStream(bytes)) { + var binary = new SkeletonBinary(attachmentLoader) { + Scale = scale + }; + return binary.ReadSkeletonData(input); + } + } + + internal static SkeletonData ReadSkeletonData (string text, AttachmentLoader attachmentLoader, float scale) { + var input = new StringReader(text); + var json = new SkeletonJson(attachmentLoader) { + Scale = scale + }; + return json.ReadSkeletonData(input); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs.meta new file mode 100644 index 0000000..941ef0f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataAsset.cs.meta @@ -0,0 +1,20 @@ +fileFormatVersion: 2 +guid: f1b3b4b945939a54ea0b23d3396115fb +timeCreated: 1536403985 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: + - multiplyMaterialTemplate: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df, + type: 2} + - screenMaterialTemplate: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be, + type: 2} + - additiveMaterialTemplate: {fileID: 2100000, guid: 4deba332d47209e4780b3c5fcf0e3745, + type: 2} + - skeletonJSON: {instanceID: 0} + - controller: {instanceID: 0} + executionOrder: 0 + icon: {fileID: 2800000, guid: 68defdbc95b30a74a9ad396bfc9a2277, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs new file mode 100644 index 0000000..2be8e6c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs @@ -0,0 +1,215 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using System; +#if UNITY_EDITOR +using System.Globalization; +using System.Text.RegularExpressions; +#endif + +namespace Spine.Unity { + + public static class SkeletonDataCompatibility { + + #if UNITY_EDITOR + static readonly int[][] compatibleBinaryVersions = { new[] { 3, 8, 0 } }; + static readonly int[][] compatibleJsonVersions = { new[] { 3, 8, 0 } }; + + static bool wasVersionDialogShown = false; + static readonly Regex jsonVersionRegex = new Regex(@"""spine""\s*:\s*""([^""]+)""", RegexOptions.CultureInvariant); + #endif + + public enum SourceType { + Json, + Binary + } + + [System.Serializable] + public class VersionInfo { + public string rawVersion = null; + public int[] version = null; + public SourceType sourceType; + } + + [System.Serializable] + public class CompatibilityProblemInfo { + public VersionInfo actualVersion; + public int[][] compatibleVersions; + public string explicitProblemDescription = null; + + public string DescriptionString () { + if (!string.IsNullOrEmpty(explicitProblemDescription)) + return explicitProblemDescription; + + string compatibleVersionString = ""; + string optionalOr = null; + foreach (int[] version in compatibleVersions) { + compatibleVersionString += string.Format("{0}{1}.{2}", optionalOr, version[0], version[1]); + optionalOr = " or "; + } + return string.Format("Skeleton data could not be loaded. Data version: {0}. Required version: {1}.\nPlease re-export skeleton data with Spine {1} or change runtime to version {2}.{3}.", + actualVersion.rawVersion, compatibleVersionString, actualVersion.version[0], actualVersion.version[1]); + } + } + + #if UNITY_EDITOR + public static VersionInfo GetVersionInfo (TextAsset asset, out bool isSpineSkeletonData, ref string problemDescription) { + isSpineSkeletonData = false; + if (asset == null) + return null; + + VersionInfo fileVersion = new VersionInfo(); + bool hasBinaryExtension = asset.name.Contains(".skel"); + fileVersion.sourceType = hasBinaryExtension ? SourceType.Binary : SourceType.Json; + + bool isJsonFileByContent = IsJsonFile(asset); + if (hasBinaryExtension == isJsonFileByContent) { + if (hasBinaryExtension) { + problemDescription = string.Format("Failed to read '{0}'. Extension is '.skel.bytes' but content looks like a '.json' file.\n" + + "Did you choose the wrong extension upon export?\n", asset.name); + } + else { + problemDescription = string.Format("Failed to read '{0}'. Extension is '.json' but content looks like binary 'skel.bytes' file.\n" + + "Did you choose the wrong extension upon export?\n", asset.name); + } + isSpineSkeletonData = false; + return null; + } + + if (fileVersion.sourceType == SourceType.Binary) { + try { + using (var memStream = new MemoryStream(asset.bytes)) { + fileVersion.rawVersion = SkeletonBinary.GetVersionString(memStream); + } + } + catch (System.Exception e) { + problemDescription = string.Format("Failed to read '{0}'. It is likely not a binary Spine SkeletonData file.\n{1}", asset.name, e); + isSpineSkeletonData = false; + return null; + } + } + else { + Match match = jsonVersionRegex.Match(asset.text); + if (match != null) { + fileVersion.rawVersion = match.Groups[1].Value; + } + else { + object obj = Json.Deserialize(new StringReader(asset.text)); + if (obj == null) { + problemDescription = string.Format("'{0}' is not valid JSON.", asset.name); + isSpineSkeletonData = false; + return null; + } + + var root = obj as Dictionary; + if (root == null) { + problemDescription = string.Format("'{0}' is not compatible JSON. Parser returned an incorrect type while parsing version info.", asset.name); + isSpineSkeletonData = false; + return null; + } + + if (root.ContainsKey("skeleton")) { + var skeletonInfo = (Dictionary)root["skeleton"]; + object jv; + skeletonInfo.TryGetValue("spine", out jv); + fileVersion.rawVersion = jv as string; + } + } + } + + if (string.IsNullOrEmpty(fileVersion.rawVersion)) { + // very likely not a Spine skeleton json file at all. Could be another valid json file, don't report errors. + isSpineSkeletonData = false; + return null; + } + + var versionSplit = fileVersion.rawVersion.Split('.'); + try { + fileVersion.version = new[]{ int.Parse(versionSplit[0], CultureInfo.InvariantCulture), + int.Parse(versionSplit[1], CultureInfo.InvariantCulture) }; + } + catch (System.Exception e) { + problemDescription = string.Format("Failed to read version info at skeleton '{0}'. It is likely not a valid Spine SkeletonData file.\n{1}", asset.name, e); + isSpineSkeletonData = false; + return null; + } + isSpineSkeletonData = true; + return fileVersion; + } + + public static bool IsJsonFile (TextAsset file) { + byte[] content = file.bytes; + const int maxCharsToCheck = 256; + int numCharsToCheck = Math.Min(content.Length, maxCharsToCheck); + int i = 0; + if (content.Length >= 3 && content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF) // skip potential BOM + i = 3; + for (; i < numCharsToCheck; ++i) { + char c = (char)content[i]; + if (char.IsWhiteSpace(c)) + continue; + return c == '{'; + } + return true; + } + + public static CompatibilityProblemInfo GetCompatibilityProblemInfo (VersionInfo fileVersion) { + if (fileVersion == null) { + return null; // it's most likely not a Spine skeleton file, e.g. another json file. don't report problems. + } + + CompatibilityProblemInfo info = new CompatibilityProblemInfo(); + info.actualVersion = fileVersion; + info.compatibleVersions = (fileVersion.sourceType == SourceType.Binary) ? compatibleBinaryVersions + : compatibleJsonVersions; + + foreach (var compatibleVersion in info.compatibleVersions) { + bool majorMatch = fileVersion.version[0] == compatibleVersion[0]; + bool minorMatch = fileVersion.version[1] == compatibleVersion[1]; + if (majorMatch && minorMatch) { + return null; // is compatible, thus no problem info returned + } + } + return info; + } + + public static void DisplayCompatibilityProblem (string descriptionString, TextAsset spineJson) { + if (!wasVersionDialogShown) { + wasVersionDialogShown = true; + UnityEditor.EditorUtility.DisplayDialog("Version mismatch!", descriptionString, "OK"); + } + Debug.LogError(string.Format("Error importing skeleton '{0}': {1}", + spineJson.name, descriptionString), spineJson); + } + #endif // UNITY_EDITOR + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs.meta new file mode 100644 index 0000000..1df7111 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataCompatibility.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4224df6e20549f0449154531ae080201 +timeCreated: 1567002861 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs new file mode 100644 index 0000000..34fef4f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs @@ -0,0 +1,39 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + /// Can be stored by SkeletonDataAsset to automatically apply modifications to loaded SkeletonData. + public abstract class SkeletonDataModifierAsset : ScriptableObject { + public abstract void Apply (SkeletonData skeletonData); + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs.meta new file mode 100644 index 0000000..ffcc5f1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SkeletonDataModifierAsset.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 79a44aba1f342f440965874280b4c318 +timeCreated: 1536412736 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs new file mode 100644 index 0000000..55aba23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs @@ -0,0 +1,245 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using Spine; + +namespace Spine.Unity { + /// Loads and stores a Spine atlas and list of materials. + [CreateAssetMenu(fileName = "New Spine Atlas Asset", menuName = "Spine/Spine Atlas Asset")] + public class SpineAtlasAsset : AtlasAssetBase { + public TextAsset atlasFile; + public Material[] materials; + protected Atlas atlas; + + public override bool IsLoaded { get { return this.atlas != null; } } + + public override IEnumerable Materials { get { return materials; } } + public override int MaterialCount { get { return materials == null ? 0 : materials.Length; } } + public override Material PrimaryMaterial { get { return materials[0]; } } + + #region Runtime Instantiation + /// + /// Creates a runtime AtlasAsset + public static SpineAtlasAsset CreateRuntimeInstance (TextAsset atlasText, Material[] materials, bool initialize) { + SpineAtlasAsset atlasAsset = ScriptableObject.CreateInstance(); + atlasAsset.Reset(); + atlasAsset.atlasFile = atlasText; + atlasAsset.materials = materials; + + if (initialize) + atlasAsset.GetAtlas(); + + return atlasAsset; + } + + /// + /// Creates a runtime AtlasAsset. Only providing the textures is slower because it has to search for atlas page matches. + public static SpineAtlasAsset CreateRuntimeInstance (TextAsset atlasText, Texture2D[] textures, Material materialPropertySource, bool initialize) { + // Get atlas page names. + string atlasString = atlasText.text; + atlasString = atlasString.Replace("\r", ""); + string[] atlasLines = atlasString.Split('\n'); + var pages = new List(); + for (int i = 0; i < atlasLines.Length - 1; i++) { + if (atlasLines[i].Trim().Length == 0) + pages.Add(atlasLines[i + 1].Trim().Replace(".png", "")); + } + + // Populate Materials[] by matching texture names with page names. + var materials = new Material[pages.Count]; + for (int i = 0, n = pages.Count; i < n; i++) { + Material mat = null; + + // Search for a match. + string pageName = pages[i]; + for (int j = 0, m = textures.Length; j < m; j++) { + if (string.Equals(pageName, textures[j].name, System.StringComparison.OrdinalIgnoreCase)) { + // Match found. + mat = new Material(materialPropertySource); + mat.mainTexture = textures[j]; + break; + } + } + + if (mat != null) + materials[i] = mat; + else + throw new ArgumentException("Could not find matching atlas page in the texture array."); + } + + // Create AtlasAsset normally + return CreateRuntimeInstance(atlasText, materials, initialize); + } + + /// + /// Creates a runtime AtlasAsset. Only providing the textures is slower because it has to search for atlas page matches. + public static SpineAtlasAsset CreateRuntimeInstance (TextAsset atlasText, Texture2D[] textures, Shader shader, bool initialize) { + if (shader == null) + shader = Shader.Find("Spine/Skeleton"); + + Material materialProperySource = new Material(shader); + var oa = CreateRuntimeInstance(atlasText, textures, materialProperySource, initialize); + + return oa; + } + #endregion + + void Reset () { + Clear(); + } + + public override void Clear () { + atlas = null; + } + + /// The atlas or null if it could not be loaded. + public override Atlas GetAtlas () { + if (atlasFile == null) { + Debug.LogError("Atlas file not set for atlas asset: " + name, this); + Clear(); + return null; + } + + if (materials == null || materials.Length == 0) { + Debug.LogError("Materials not set for atlas asset: " + name, this); + Clear(); + return null; + } + + if (atlas != null) return atlas; + + try { + atlas = new Atlas(new StringReader(atlasFile.text), "", new MaterialsTextureLoader(this)); + atlas.FlipV(); + return atlas; + } catch (Exception ex) { + Debug.LogError("Error reading atlas file for atlas asset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this); + return null; + } + } + + public Mesh GenerateMesh (string name, Mesh mesh, out Material material, float scale = 0.01f) { + AtlasRegion region = atlas.FindRegion(name); + material = null; + if (region != null) { + if (mesh == null) { + mesh = new Mesh(); + mesh.name = name; + } + + Vector3[] verts = new Vector3[4]; + Vector2[] uvs = new Vector2[4]; + Color[] colors = { Color.white, Color.white, Color.white, Color.white }; + int[] triangles = { 0, 1, 2, 2, 3, 0 }; + + float left, right, top, bottom; + left = region.width / -2f; + right = left * -1f; + top = region.height / 2f; + bottom = top * -1; + + verts[0] = new Vector3(left, bottom, 0) * scale; + verts[1] = new Vector3(left, top, 0) * scale; + verts[2] = new Vector3(right, top, 0) * scale; + verts[3] = new Vector3(right, bottom, 0) * scale; + float u, v, u2, v2; + u = region.u; + v = region.v; + u2 = region.u2; + v2 = region.v2; + + if (!region.rotate) { + uvs[0] = new Vector2(u, v2); + uvs[1] = new Vector2(u, v); + uvs[2] = new Vector2(u2, v); + uvs[3] = new Vector2(u2, v2); + } else { + uvs[0] = new Vector2(u2, v2); + uvs[1] = new Vector2(u, v2); + uvs[2] = new Vector2(u, v); + uvs[3] = new Vector2(u2, v); + } + + mesh.triangles = new int[0]; + mesh.vertices = verts; + mesh.uv = uvs; + mesh.colors = colors; + mesh.triangles = triangles; + mesh.RecalculateNormals(); + mesh.RecalculateBounds(); + + material = (Material)region.page.rendererObject; + } else { + mesh = null; + } + + return mesh; + } + } + + public class MaterialsTextureLoader : TextureLoader { + SpineAtlasAsset atlasAsset; + + public MaterialsTextureLoader (SpineAtlasAsset atlasAsset) { + this.atlasAsset = atlasAsset; + } + + public void Load (AtlasPage page, string path) { + String name = Path.GetFileNameWithoutExtension(path); + Material material = null; + foreach (Material other in atlasAsset.materials) { + if (other.mainTexture == null) { + Debug.LogError("Material is missing texture: " + other.name, other); + return; + } + if (other.mainTexture.name == name) { + material = other; + break; + } + } + if (material == null) { + Debug.LogError("Material with texture name \"" + name + "\" not found for atlas asset: " + atlasAsset.name, atlasAsset); + return; + } + page.rendererObject = material; + + // Very old atlas files expected the texture's actual size to be used at runtime. + if (page.width == 0 || page.height == 0) { + page.width = material.mainTexture.width; + page.height = material.mainTexture.height; + } + } + + public void Unload (object texture) { } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs.meta new file mode 100644 index 0000000..e6a4920 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineAtlasAsset.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a6b194f808b1af6499c93410e504af42 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 3fc714a0dc1cf6b4b959e073fff2844e, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs new file mode 100644 index 0000000..12b1a70 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs @@ -0,0 +1,397 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_2_OR_NEWER +#define EXPOSES_SPRITE_ATLAS_UTILITIES +#endif + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using Spine; +using UnityEngine.U2D; + +#if UNITY_EDITOR +using UnityEditor; +using System.Reflection; +#endif + +namespace Spine.Unity { + /// Loads and stores a Spine atlas and list of materials. + [CreateAssetMenu(fileName = "New Spine SpriteAtlas Asset", menuName = "Spine/Spine SpriteAtlas Asset")] + public class SpineSpriteAtlasAsset : AtlasAssetBase { + public SpriteAtlas spriteAtlasFile; + public Material[] materials; + protected Atlas atlas; + public bool updateRegionsInPlayMode; + + [System.Serializable] + protected class SavedRegionInfo { + public float x, y, width, height; + public SpritePackingRotation packingRotation; + } + [SerializeField] protected SavedRegionInfo[] savedRegions; + + public override bool IsLoaded { get { return this.atlas != null; } } + + public override IEnumerable Materials { get { return materials; } } + public override int MaterialCount { get { return materials == null ? 0 : materials.Length; } } + public override Material PrimaryMaterial { get { return materials[0]; } } + + #if UNITY_EDITOR + static MethodInfo GetPackedSpritesMethod, GetPreviewTexturesMethod; + #if !EXPOSES_SPRITE_ATLAS_UTILITIES + static MethodInfo PackAtlasesMethod; + #endif + #endif + + #region Runtime Instantiation + /// + /// Creates a runtime AtlasAsset + public static SpineSpriteAtlasAsset CreateRuntimeInstance (SpriteAtlas spriteAtlasFile, Material[] materials, bool initialize) { + SpineSpriteAtlasAsset atlasAsset = ScriptableObject.CreateInstance(); + atlasAsset.Reset(); + atlasAsset.spriteAtlasFile = spriteAtlasFile; + atlasAsset.materials = materials; + + if (initialize) + atlasAsset.GetAtlas(); + + return atlasAsset; + } + #endregion + + void Reset () { + Clear(); + } + + public override void Clear () { + atlas = null; + } + + /// The atlas or null if it could not be loaded. + public override Atlas GetAtlas () { + if (spriteAtlasFile == null) { + Debug.LogError("SpriteAtlas file not set for SpineSpriteAtlasAsset: " + name, this); + Clear(); + return null; + } + + if (materials == null || materials.Length == 0) { + Debug.LogError("Materials not set for SpineSpriteAtlasAsset: " + name, this); + Clear(); + return null; + } + + if (atlas != null) return atlas; + + try { + atlas = LoadAtlas(spriteAtlasFile); + return atlas; + } catch (Exception ex) { + Debug.LogError("Error analyzing SpriteAtlas for SpineSpriteAtlasAsset: " + name + "\n" + ex.Message + "\n" + ex.StackTrace, this); + return null; + } + } + + protected void AssignRegionsFromSavedRegions (Sprite[] sprites, Atlas usedAtlas) { + + if (savedRegions == null || savedRegions.Length != sprites.Length) + return; + + int i = 0; + foreach (var region in usedAtlas) { + var savedRegion = savedRegions[i]; + var page = region.page; + + region.degrees = savedRegion.packingRotation == SpritePackingRotation.None ? 0 : 90; + region.rotate = region.degrees != 0; + + float x = savedRegion.x; + float y = savedRegion.y; + float width = savedRegion.width; + float height = savedRegion.height; + + region.u = x / (float)page.width; + region.v = y / (float)page.height; + if (region.rotate) { + region.u2 = (x + height) / (float)page.width; + region.v2 = (y + width) / (float)page.height; + } + else { + region.u2 = (x + width) / (float)page.width; + region.v2 = (y + height) / (float)page.height; + } + region.x = (int)x; + region.y = (int)y; + region.width = Math.Abs((int)width); + region.height = Math.Abs((int)height); + + // flip upside down + var temp = region.v; + region.v = region.v2; + region.v2 = temp; + + region.originalWidth = (int)width; + region.originalHeight = (int)height; + + // note: currently sprite pivot offsets are ignored. + // var sprite = sprites[i]; + region.offsetX = 0;//sprite.pivot.x; + region.offsetY = 0;//sprite.pivot.y; + + ++i; + } + } + + private Atlas LoadAtlas (UnityEngine.U2D.SpriteAtlas spriteAtlas) { + + List pages = new List(); + List regions = new List(); + + Sprite[] sprites = new UnityEngine.Sprite[spriteAtlas.spriteCount]; + spriteAtlas.GetSprites(sprites); + if (sprites.Length == 0) + return new Atlas(pages, regions); + + Texture2D texture = null; + #if UNITY_EDITOR + if (!Application.isPlaying) + texture = AccessPackedTextureEditor(spriteAtlas); + else + #endif + texture = AccessPackedTexture(sprites); + + Material material = materials[0]; + #if !UNITY_EDITOR + material.mainTexture = texture; + #endif + + Spine.AtlasPage page = new AtlasPage(); + page.name = spriteAtlas.name; + page.width = texture.width; + page.height = texture.height; + page.format = Spine.Format.RGBA8888; + + page.minFilter = TextureFilter.Linear; + page.magFilter = TextureFilter.Linear; + page.uWrap = TextureWrap.ClampToEdge; + page.vWrap = TextureWrap.ClampToEdge; + page.rendererObject = material; + pages.Add(page); + + sprites = AccessPackedSprites(spriteAtlas); + + int i = 0; + for ( ; i < sprites.Length; ++i) { + var sprite = sprites[i]; + AtlasRegion region = new AtlasRegion(); + region.name = sprite.name.Replace("(Clone)", ""); + region.page = page; + region.degrees = sprite.packingRotation == SpritePackingRotation.None ? 0 : 90; + region.rotate = region.degrees != 0; + + region.u2 = 1; + region.v2 = 1; + region.width = page.width; + region.height = page.height; + region.originalWidth = page.width; + region.originalHeight = page.height; + + region.index = i; + regions.Add(region); + } + + var atlas = new Atlas(pages, regions); + AssignRegionsFromSavedRegions(sprites, atlas); + + return atlas; + } + +#if UNITY_EDITOR + public static void UpdateByStartingEditorPlayMode () { + EditorApplication.isPlaying = true; + } + + public static bool AnySpriteAtlasNeedsRegionsLoaded () { + string[] guids = UnityEditor.AssetDatabase.FindAssets("t:SpineSpriteAtlasAsset"); + foreach (var guid in guids) { + string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(path)) { + var atlasAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(path); + if (atlasAsset) { + if (atlasAsset.RegionsNeedLoading) + return true; + } + } + } + return false; + } + + public static void UpdateWhenEditorPlayModeStarted () { + if (!EditorApplication.isPlaying) + return; + + EditorApplication.update -= UpdateWhenEditorPlayModeStarted; + string[] guids = UnityEditor.AssetDatabase.FindAssets("t:SpineSpriteAtlasAsset"); + if (guids.Length == 0) + return; + + Debug.Log("Updating SpineSpriteAtlasAssets"); + foreach (var guid in guids) { + string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(path)) { + var atlasAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(path); + if (atlasAsset) { + atlasAsset.atlas = atlasAsset.LoadAtlas(atlasAsset.spriteAtlasFile); + atlasAsset.LoadRegionsInEditorPlayMode(); + Debug.Log(string.Format("Updated regions of '{0}'", atlasAsset.name), atlasAsset); + } + } + } + + EditorApplication.isPlaying = false; + } + + public bool RegionsNeedLoading { + get { return savedRegions == null || savedRegions.Length == 0 || updateRegionsInPlayMode; } + } + + public void LoadRegionsInEditorPlayMode () { + + Sprite[] sprites = null; + System.Type T = Type.GetType("UnityEditor.U2D.SpriteAtlasExtensions,UnityEditor"); + var method = T.GetMethod("GetPackedSprites", BindingFlags.NonPublic | BindingFlags.Static); + if (method != null) { + object retval = method.Invoke(null, new object[] { spriteAtlasFile }); + var spritesArray = retval as Sprite[]; + if (spritesArray != null && spritesArray.Length > 0) { + sprites = spritesArray; + } + } + if (sprites == null) { + sprites = new UnityEngine.Sprite[spriteAtlasFile.spriteCount]; + spriteAtlasFile.GetSprites(sprites); + } + if (sprites.Length == 0) { + Debug.LogWarning(string.Format("SpriteAtlas '{0}' contains no sprites. Please make sure all assigned images are set to import type 'Sprite'.", spriteAtlasFile.name), spriteAtlasFile); + return; + } + else if (sprites[0].packingMode == SpritePackingMode.Tight) { + Debug.LogError(string.Format("SpriteAtlas '{0}': Tight packing is not supported. Please disable 'Tight Packing' in the SpriteAtlas Inspector.", spriteAtlasFile.name), spriteAtlasFile); + return; + } + + if (savedRegions == null || savedRegions.Length != sprites.Length) + savedRegions = new SavedRegionInfo[sprites.Length]; + + int i = 0; + foreach (var region in atlas) { + var sprite = sprites[i]; + var rect = sprite.textureRect; + float x = rect.min.x; + float y = rect.min.y; + float width = rect.width; + float height = rect.height; + + var savedRegion = new SavedRegionInfo(); + savedRegion.x = x; + savedRegion.y = y; + savedRegion.width = width; + savedRegion.height = height; + savedRegion.packingRotation = sprite.packingRotation; + savedRegions[i] = savedRegion; + + ++i; + } + updateRegionsInPlayMode = false; + AssignRegionsFromSavedRegions(sprites, atlas); + EditorUtility.SetDirty(this); + AssetDatabase.SaveAssets(); + } + + public static Texture2D AccessPackedTextureEditor (SpriteAtlas spriteAtlas) { + #if EXPOSES_SPRITE_ATLAS_UTILITIES + UnityEditor.U2D.SpriteAtlasUtility.PackAtlases(new SpriteAtlas[] { spriteAtlas }, EditorUserBuildSettings.activeBuildTarget); + #else + /*if (PackAtlasesMethod == null) { + System.Type T = Type.GetType("UnityEditor.U2D.SpriteAtlasUtility,UnityEditor"); + PackAtlasesMethod = T.GetMethod("PackAtlases", BindingFlags.NonPublic | BindingFlags.Static); + } + if (PackAtlasesMethod != null) { + PackAtlasesMethod.Invoke(null, new object[] { new SpriteAtlas[] { spriteAtlas }, EditorUserBuildSettings.activeBuildTarget }); + }*/ + #endif + if (GetPreviewTexturesMethod == null) { + System.Type T = Type.GetType("UnityEditor.U2D.SpriteAtlasExtensions,UnityEditor"); + GetPreviewTexturesMethod = T.GetMethod("GetPreviewTextures", BindingFlags.NonPublic | BindingFlags.Static); + } + if (GetPreviewTexturesMethod != null) { + object retval = GetPreviewTexturesMethod.Invoke(null, new object[] { spriteAtlas }); + var textures = retval as Texture2D[]; + if (textures.Length > 0) + return textures[0]; + } + return null; + } +#endif + public static Texture2D AccessPackedTexture (Sprite[] sprites) { + return sprites[0].texture; + } + + + public static Sprite[] AccessPackedSprites (UnityEngine.U2D.SpriteAtlas spriteAtlas) { + Sprite[] sprites = null; +#if UNITY_EDITOR + if (!Application.isPlaying) { + + if (GetPackedSpritesMethod == null) { + System.Type T = Type.GetType("UnityEditor.U2D.SpriteAtlasExtensions,UnityEditor"); + GetPackedSpritesMethod = T.GetMethod("GetPackedSprites", BindingFlags.NonPublic | BindingFlags.Static); + } + if (GetPackedSpritesMethod != null) { + object retval = GetPackedSpritesMethod.Invoke(null, new object[] { spriteAtlas }); + var spritesArray = retval as Sprite[]; + if (spritesArray != null && spritesArray.Length > 0) { + sprites = spritesArray; + } + } + } +#endif + if (sprites == null) { + sprites = new UnityEngine.Sprite[spriteAtlas.spriteCount]; + spriteAtlas.GetSprites(sprites); + if (sprites.Length == 0) + return null; + } + return sprites; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs.meta new file mode 100644 index 0000000..e61e24e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Asset Types/SpineSpriteAtlasAsset.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce59897dd7e6cbc4690a05ebaf975dff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components.meta new file mode 100644 index 0000000..c8b4659 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 954179821df28404683b8289f05d0c6f +folderAsset: yes +timeCreated: 1518344191 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following.meta new file mode 100644 index 0000000..39fdc6c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b0fd98019ca00c74f929c6d1f7ee3544 +folderAsset: yes +timeCreated: 1563290418 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs new file mode 100644 index 0000000..cb75c43 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs @@ -0,0 +1,217 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using System; +using UnityEngine; + +namespace Spine.Unity { + + /// Sets a GameObject's transform to match a bone on a Spine skeleton. + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [AddComponentMenu("Spine/BoneFollower")] + [HelpURL("http://esotericsoftware.com/spine-unity#BoneFollower")] + public class BoneFollower : MonoBehaviour { + + #region Inspector + public SkeletonRenderer skeletonRenderer; + public SkeletonRenderer SkeletonRenderer { + get { return skeletonRenderer; } + set { + skeletonRenderer = value; + Initialize(); + } + } + + /// If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly. + [SpineBone(dataField: "skeletonRenderer")] + public string boneName; + + public bool followXYPosition = true; + public bool followZPosition = true; + public bool followBoneRotation = true; + + [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")] + public bool followSkeletonFlip = true; + + [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")] + public bool followLocalScale = false; + + public enum AxisOrientation { + XAxis = 1, + YAxis + } + [Tooltip("Applies when 'Follow Skeleton Flip' is disabled but 'Follow Bone Rotation' is enabled." + + " When flipping the skeleton by scaling its Transform, this follower's rotation is adjusted" + + " instead of its scale to follow the bone orientation. When one of the axes is flipped, " + + " only one axis can be followed, either the X or the Y axis, which is selected here.")] + public AxisOrientation maintainedAxisOrientation = AxisOrientation.XAxis; + + [UnityEngine.Serialization.FormerlySerializedAs("resetOnAwake")] + public bool initializeOnAwake = true; + #endregion + + [NonSerialized] public bool valid; + [NonSerialized] public Bone bone; + + Transform skeletonTransform; + bool skeletonTransformIsParent; + + /// + /// Sets the target bone by its bone name. Returns false if no bone was found. To set the bone by reference, use BoneFollower.bone directly. + public bool SetBone (string name) { + bone = skeletonRenderer.skeleton.FindBone(name); + if (bone == null) { + Debug.LogError("Bone not found: " + name, this); + return false; + } + boneName = name; + return true; + } + + public void Awake () { + if (initializeOnAwake) Initialize(); + } + + public void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) { + Initialize(); + } + + public void Initialize () { + bone = null; + valid = skeletonRenderer != null && skeletonRenderer.valid; + if (!valid) return; + + skeletonTransform = skeletonRenderer.transform; + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + skeletonRenderer.OnRebuild += HandleRebuildRenderer; + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + + if (!string.IsNullOrEmpty(boneName)) + bone = skeletonRenderer.skeleton.FindBone(boneName); + + #if UNITY_EDITOR + if (Application.isEditor) + LateUpdate(); + #endif + } + + void OnDestroy () { + if (skeletonRenderer != null) + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + } + + public void LateUpdate () { + if (!valid) { + Initialize(); + return; + } + + #if UNITY_EDITOR + if (!Application.isPlaying) + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + #endif + + if (bone == null) { + if (string.IsNullOrEmpty(boneName)) return; + bone = skeletonRenderer.skeleton.FindBone(boneName); + if (!SetBone(boneName)) return; + } + + Transform thisTransform = this.transform; + float additionalFlipScale = 1; + if (skeletonTransformIsParent) { + // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent + thisTransform.localPosition = new Vector3(followXYPosition ? bone.worldX : thisTransform.localPosition.x, + followXYPosition ? bone.worldY : thisTransform.localPosition.y, + followZPosition ? 0f : thisTransform.localPosition.z); + if (followBoneRotation) { + float halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; + if (followLocalScale && bone.scaleX < 0) // Negate rotation from negative scaleX. Don't use negative determinant. local scaleY doesn't factor into used rotation. + halfRotation += Mathf.PI * 0.5f; + + var q = default(Quaternion); + q.z = Mathf.Sin(halfRotation); + q.w = Mathf.Cos(halfRotation); + thisTransform.localRotation = q; + } + } else { + // For special cases: Use transform world properties if transform relationship is complicated + Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY, 0f)); + if (!followZPosition) targetWorldPosition.z = thisTransform.position.z; + if (!followXYPosition) { + targetWorldPosition.x = thisTransform.position.x; + targetWorldPosition.y = thisTransform.position.y; + } + + Vector3 skeletonLossyScale = skeletonTransform.lossyScale; + Transform transformParent = thisTransform.parent; + Vector3 parentLossyScale = transformParent != null ? transformParent.lossyScale : Vector3.one; + if (followBoneRotation) { + float boneWorldRotation = bone.WorldRotationX; + + if ((skeletonLossyScale.x * skeletonLossyScale.y) < 0) + boneWorldRotation = -boneWorldRotation; + + if (followSkeletonFlip || maintainedAxisOrientation == AxisOrientation.XAxis) { + if ((skeletonLossyScale.x * parentLossyScale.x < 0)) + boneWorldRotation += 180f; + } + else { + if ((skeletonLossyScale.y * parentLossyScale.y < 0)) + boneWorldRotation += 180f; + } + + Vector3 worldRotation = skeletonTransform.rotation.eulerAngles; + if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f; + thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation)); + } else { + thisTransform.position = targetWorldPosition; + } + + additionalFlipScale = Mathf.Sign(skeletonLossyScale.x * parentLossyScale.x + * skeletonLossyScale.y * parentLossyScale.y); + } + + Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f); + if (followSkeletonFlip) + localScale.y *= Mathf.Sign(bone.skeleton.ScaleX * bone.skeleton.ScaleY) * additionalFlipScale; + + thisTransform.localScale = localScale; + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs.meta new file mode 100644 index 0000000..c5bb78c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollower.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a1fd8daaed7b64148a34acb96ba14ce1 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs new file mode 100644 index 0000000..6d5ea7b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs @@ -0,0 +1,196 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; + + +namespace Spine.Unity { + using AxisOrientation = BoneFollower.AxisOrientation; + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [RequireComponent(typeof(RectTransform)), DisallowMultipleComponent] + [AddComponentMenu("Spine/UI/BoneFollowerGraphic")] + [HelpURL("http://esotericsoftware.com/spine-unity#BoneFollowerGraphic")] + public class BoneFollowerGraphic : MonoBehaviour { + public SkeletonGraphic skeletonGraphic; + public SkeletonGraphic SkeletonGraphic { + get { return skeletonGraphic; } + set { + skeletonGraphic = value; + Initialize(); + } + } + + public bool initializeOnAwake = true; + + /// If a bone isn't set in code, boneName is used to find the bone at the beginning. For runtime switching by name, use SetBoneByName. You can also set the BoneFollower.bone field directly. + [SpineBone(dataField: "skeletonGraphic")] + public string boneName; + + public bool followBoneRotation = true; + [Tooltip("Follows the skeleton's flip state by controlling this Transform's local scale.")] + public bool followSkeletonFlip = true; + [Tooltip("Follows the target bone's local scale. BoneFollower cannot inherit world/skewed scale because of UnityEngine.Transform property limitations.")] + public bool followLocalScale = false; + public bool followXYPosition = true; + public bool followZPosition = true; + [Tooltip("Applies when 'Follow Skeleton Flip' is disabled but 'Follow Bone Rotation' is enabled." + + " When flipping the skeleton by scaling its Transform, this follower's rotation is adjusted" + + " instead of its scale to follow the bone orientation. When one of the axes is flipped, " + + " only one axis can be followed, either the X or the Y axis, which is selected here.")] + public AxisOrientation maintainedAxisOrientation = AxisOrientation.XAxis; + + [System.NonSerialized] public Bone bone; + + Transform skeletonTransform; + bool skeletonTransformIsParent; + + [System.NonSerialized] public bool valid; + + /// + /// Sets the target bone by its bone name. Returns false if no bone was found. + public bool SetBone (string name) { + bone = skeletonGraphic.Skeleton.FindBone(name); + if (bone == null) { + Debug.LogError("Bone not found: " + name, this); + return false; + } + boneName = name; + return true; + } + + public void Awake () { + if (initializeOnAwake) Initialize(); + } + + public void Initialize () { + bone = null; + valid = skeletonGraphic != null && skeletonGraphic.IsValid; + if (!valid) return; + + skeletonTransform = skeletonGraphic.transform; +// skeletonGraphic.OnRebuild -= HandleRebuildRenderer; +// skeletonGraphic.OnRebuild += HandleRebuildRenderer; + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + + if (!string.IsNullOrEmpty(boneName)) + bone = skeletonGraphic.Skeleton.FindBone(boneName); + + #if UNITY_EDITOR + if (Application.isEditor) { + LateUpdate(); + } + #endif + } + + public void LateUpdate () { + if (!valid) { + Initialize(); + return; + } + + #if UNITY_EDITOR + if (!Application.isPlaying) + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + #endif + + if (bone == null) { + if (string.IsNullOrEmpty(boneName)) return; + bone = skeletonGraphic.Skeleton.FindBone(boneName); + if (!SetBone(boneName)) return; + } + + var thisTransform = this.transform as RectTransform; + if (thisTransform == null) return; + + var canvas = skeletonGraphic.canvas; + if (canvas == null) canvas = skeletonGraphic.GetComponentInParent(); + float scale = canvas != null ? canvas.referencePixelsPerUnit : 100.0f; + + float additionalFlipScale = 1; + if (skeletonTransformIsParent) { + // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent + thisTransform.localPosition = new Vector3(followXYPosition ? bone.worldX * scale : thisTransform.localPosition.x, + followXYPosition ? bone.worldY * scale : thisTransform.localPosition.y, + followZPosition ? 0f : thisTransform.localPosition.z); + if (followBoneRotation) thisTransform.localRotation = bone.GetQuaternion(); + } else { + // For special cases: Use transform world properties if transform relationship is complicated + Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(bone.worldX * scale, bone.worldY * scale, 0f)); + if (!followZPosition) targetWorldPosition.z = thisTransform.position.z; + if (!followXYPosition) { + targetWorldPosition.x = thisTransform.position.x; + targetWorldPosition.y = thisTransform.position.y; + } + + Vector3 skeletonLossyScale = skeletonTransform.lossyScale; + Transform transformParent = thisTransform.parent; + Vector3 parentLossyScale = transformParent != null ? transformParent.lossyScale : Vector3.one; + if (followBoneRotation) { + float boneWorldRotation = bone.WorldRotationX; + + if ((skeletonLossyScale.x * skeletonLossyScale.y) < 0) + boneWorldRotation = -boneWorldRotation; + + if (followSkeletonFlip || maintainedAxisOrientation == AxisOrientation.XAxis) { + if ((skeletonLossyScale.x * parentLossyScale.x < 0)) + boneWorldRotation += 180f; + } + else { + if ((skeletonLossyScale.y * parentLossyScale.y < 0)) + boneWorldRotation += 180f; + } + + Vector3 worldRotation = skeletonTransform.rotation.eulerAngles; + if (followLocalScale && bone.scaleX < 0) boneWorldRotation += 180f; + thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(worldRotation.x, worldRotation.y, worldRotation.z + boneWorldRotation)); + } else { + thisTransform.position = targetWorldPosition; + } + + additionalFlipScale = Mathf.Sign(skeletonLossyScale.x * parentLossyScale.x + * skeletonLossyScale.y * parentLossyScale.y); + } + + Vector3 localScale = followLocalScale ? new Vector3(bone.scaleX, bone.scaleY, 1f) : new Vector3(1f, 1f, 1f); + if (followSkeletonFlip) + localScale.y *= Mathf.Sign(bone.skeleton.ScaleX * bone.skeleton.ScaleY) * additionalFlipScale; + thisTransform.localScale = localScale; + } + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs.meta new file mode 100644 index 0000000..b227966 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoneFollowerGraphic.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b42a195b47491d34b9bcbc40898bcb29 +timeCreated: 1499211965 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs new file mode 100644 index 0000000..f841a02 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs @@ -0,0 +1,253 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using System.Collections.Generic; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [HelpURL("http://esotericsoftware.com/spine-unity#BoundingBoxFollower")] + public class BoundingBoxFollower : MonoBehaviour { + internal static bool DebugMessages = true; + + #region Inspector + public SkeletonRenderer skeletonRenderer; + [SpineSlot(dataField: "skeletonRenderer", containsBoundingBoxes: true)] + public string slotName; + public bool isTrigger; + public bool clearStateOnDisable = true; + #endregion + + Slot slot; + BoundingBoxAttachment currentAttachment; + string currentAttachmentName; + PolygonCollider2D currentCollider; + + public readonly Dictionary colliderTable = new Dictionary(); + public readonly Dictionary nameTable = new Dictionary(); + + public Slot Slot { get { return slot; } } + public BoundingBoxAttachment CurrentAttachment { get { return currentAttachment; } } + public string CurrentAttachmentName { get { return currentAttachmentName; } } + public PolygonCollider2D CurrentCollider { get { return currentCollider; } } + public bool IsTrigger { get { return isTrigger; } } + + void Start () { + Initialize(); + } + + void OnEnable () { + if (skeletonRenderer != null) { + skeletonRenderer.OnRebuild -= HandleRebuild; + skeletonRenderer.OnRebuild += HandleRebuild; + } + + Initialize(); + } + + void HandleRebuild (SkeletonRenderer sr) { + //if (BoundingBoxFollower.DebugMessages) Debug.Log("Skeleton was rebuilt. Repopulating BoundingBoxFollower."); + Initialize(); + } + + /// + /// Initialize and instantiate the BoundingBoxFollower colliders. This is method checks if the BoundingBoxFollower has already been initialized for the skeleton instance and slotName and prevents overwriting unless it detects a new setup. + public void Initialize (bool overwrite = false) { + if (skeletonRenderer == null) + return; + + skeletonRenderer.Initialize(false); + + if (string.IsNullOrEmpty(slotName)) + return; + + // Don't reinitialize if the setup did not change. + if (!overwrite + && + colliderTable.Count > 0 && slot != null // Slot is set and colliders already populated. + && + skeletonRenderer.skeleton == slot.Skeleton // Skeleton object did not change. + && + slotName == slot.data.name // Slot object did not change. + ) + return; + + slot = null; + currentAttachment = null; + currentAttachmentName = null; + currentCollider = null; + colliderTable.Clear(); + nameTable.Clear(); + + var skeleton = skeletonRenderer.skeleton; + if (skeleton == null) + return; + slot = skeleton.FindSlot(slotName); + int slotIndex = skeleton.FindSlotIndex(slotName); + + if (slot == null) { + if (BoundingBoxFollower.DebugMessages) + Debug.LogWarning(string.Format("Slot '{0}' not found for BoundingBoxFollower on '{1}'. (Previous colliders were disposed.)", slotName, this.gameObject.name)); + return; + } + + int requiredCollidersCount = 0; + var colliders = GetComponents(); + if (this.gameObject.activeInHierarchy) { + foreach (var skin in skeleton.Data.Skins) + AddCollidersForSkin(skin, slotIndex, colliders, ref requiredCollidersCount); + + if (skeleton.skin != null) + AddCollidersForSkin(skeleton.skin, slotIndex, colliders, ref requiredCollidersCount); + } + DisposeExcessCollidersAfter(requiredCollidersCount); + + if (BoundingBoxFollower.DebugMessages) { + bool valid = colliderTable.Count != 0; + if (!valid) { + if (this.gameObject.activeInHierarchy) + Debug.LogWarning("Bounding Box Follower not valid! Slot [" + slotName + "] does not contain any Bounding Box Attachments!"); + else + Debug.LogWarning("Bounding Box Follower tried to rebuild as a prefab."); + } + } + } + + void AddCollidersForSkin (Skin skin, int slotIndex, PolygonCollider2D[] previousColliders, ref int collidersCount) { + if (skin == null) return; + var skinEntries = new List(); + skin.GetAttachments(slotIndex, skinEntries); + + foreach (var entry in skinEntries) { + var attachment = skin.GetAttachment(slotIndex, entry.Name); + var boundingBoxAttachment = attachment as BoundingBoxAttachment; + + if (BoundingBoxFollower.DebugMessages && attachment != null && boundingBoxAttachment == null) + Debug.Log("BoundingBoxFollower tried to follow a slot that contains non-boundingbox attachments: " + slotName); + + if (boundingBoxAttachment != null) { + if (!colliderTable.ContainsKey(boundingBoxAttachment)) { + var bbCollider = collidersCount < previousColliders.Length ? + previousColliders[collidersCount] : gameObject.AddComponent(); + ++collidersCount; + SkeletonUtility.SetColliderPointsLocal(bbCollider, slot, boundingBoxAttachment); + bbCollider.isTrigger = isTrigger; + bbCollider.enabled = false; + bbCollider.hideFlags = HideFlags.NotEditable; + bbCollider.isTrigger = IsTrigger; + colliderTable.Add(boundingBoxAttachment, bbCollider); + nameTable.Add(boundingBoxAttachment, entry.Name); + } + } + } + } + + void OnDisable () { + if (clearStateOnDisable) + ClearState(); + + if (skeletonRenderer != null) + skeletonRenderer.OnRebuild -= HandleRebuild; + } + + public void ClearState () { + if (colliderTable != null) + foreach (var col in colliderTable.Values) + col.enabled = false; + + currentAttachment = null; + currentAttachmentName = null; + currentCollider = null; + } + + void DisposeExcessCollidersAfter (int requiredCount) { + var colliders = GetComponents(); + if (colliders.Length == 0) return; + + for (int i = requiredCount; i < colliders.Length; ++i) { + var collider = colliders[i]; + if (collider != null) { +#if UNITY_EDITOR + if (Application.isEditor && !Application.isPlaying) + DestroyImmediate(collider); + else +#endif + Destroy(collider); + } + } + } + + void LateUpdate () { + if (slot != null && slot.Attachment != currentAttachment) + MatchAttachment(slot.Attachment); + } + + /// Sets the current collider to match attachment. + /// If the attachment is not a bounding box, it will be treated as null. + void MatchAttachment (Attachment attachment) { + var bbAttachment = attachment as BoundingBoxAttachment; + + if (BoundingBoxFollower.DebugMessages && attachment != null && bbAttachment == null) + Debug.LogWarning("BoundingBoxFollower tried to match a non-boundingbox attachment. It will treat it as null."); + + if (currentCollider != null) + currentCollider.enabled = false; + + if (bbAttachment == null) { + currentCollider = null; + currentAttachment = null; + currentAttachmentName = null; + } else { + PolygonCollider2D foundCollider; + colliderTable.TryGetValue(bbAttachment, out foundCollider); + if (foundCollider != null) { + currentCollider = foundCollider; + currentCollider.enabled = true; + currentAttachment = bbAttachment; + currentAttachmentName = nameTable[bbAttachment]; + } else { + currentCollider = null; + currentAttachment = bbAttachment; + currentAttachmentName = null; + if (BoundingBoxFollower.DebugMessages) Debug.LogFormat("Collider for BoundingBoxAttachment named '{0}' was not initialized. It is possibly from a new skin. currentAttachmentName will be null. You may need to call BoundingBoxFollower.Initialize(overwrite: true);", bbAttachment.Name); + } + } + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs.meta new file mode 100644 index 0000000..d81fd14 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollower.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0317ee9ba6e1b1e49a030268e026d372 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs new file mode 100644 index 0000000..674a0fb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs @@ -0,0 +1,257 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using System.Collections.Generic; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [HelpURL("http://esotericsoftware.com/spine-unity#BoundingBoxFollowerGraphic")] + public class BoundingBoxFollowerGraphic : MonoBehaviour { + internal static bool DebugMessages = true; + + #region Inspector + public SkeletonGraphic skeletonGraphic; + [SpineSlot(dataField: "skeletonGraphic", containsBoundingBoxes: true)] + public string slotName; + public bool isTrigger; + public bool clearStateOnDisable = true; + #endregion + + Slot slot; + BoundingBoxAttachment currentAttachment; + string currentAttachmentName; + PolygonCollider2D currentCollider; + + public readonly Dictionary colliderTable = new Dictionary(); + public readonly Dictionary nameTable = new Dictionary(); + + public Slot Slot { get { return slot; } } + public BoundingBoxAttachment CurrentAttachment { get { return currentAttachment; } } + public string CurrentAttachmentName { get { return currentAttachmentName; } } + public PolygonCollider2D CurrentCollider { get { return currentCollider; } } + public bool IsTrigger { get { return isTrigger; } } + + void Start () { + Initialize(); + } + + void OnEnable () { + if (skeletonGraphic != null) { + skeletonGraphic.OnRebuild -= HandleRebuild; + skeletonGraphic.OnRebuild += HandleRebuild; + } + + Initialize(); + } + + void HandleRebuild (SkeletonGraphic sr) { + //if (BoundingBoxFollowerGraphic.DebugMessages) Debug.Log("Skeleton was rebuilt. Repopulating BoundingBoxFollowerGraphic."); + Initialize(); + } + + /// + /// Initialize and instantiate the BoundingBoxFollowerGraphic colliders. This is method checks if the BoundingBoxFollowerGraphic has already been initialized for the skeleton instance and slotName and prevents overwriting unless it detects a new setup. + public void Initialize (bool overwrite = false) { + if (skeletonGraphic == null) + return; + + skeletonGraphic.Initialize(false); + + if (string.IsNullOrEmpty(slotName)) + return; + + // Don't reinitialize if the setup did not change. + if (!overwrite + && + colliderTable.Count > 0 && slot != null // Slot is set and colliders already populated. + && + skeletonGraphic.Skeleton == slot.Skeleton // Skeleton object did not change. + && + slotName == slot.data.name // Slot object did not change. + ) + return; + + slot = null; + currentAttachment = null; + currentAttachmentName = null; + currentCollider = null; + colliderTable.Clear(); + nameTable.Clear(); + + var skeleton = skeletonGraphic.Skeleton; + if (skeleton == null) + return; + slot = skeleton.FindSlot(slotName); + int slotIndex = skeleton.FindSlotIndex(slotName); + + if (slot == null) { + if (BoundingBoxFollowerGraphic.DebugMessages) + Debug.LogWarning(string.Format("Slot '{0}' not found for BoundingBoxFollowerGraphic on '{1}'. (Previous colliders were disposed.)", slotName, this.gameObject.name)); + return; + } + + int requiredCollidersCount = 0; + var colliders = GetComponents(); + if (this.gameObject.activeInHierarchy) { + var canvas = skeletonGraphic.canvas; + if (canvas == null) canvas = skeletonGraphic.GetComponentInParent(); + float scale = canvas != null ? canvas.referencePixelsPerUnit : 100.0f; + + foreach (var skin in skeleton.Data.Skins) + AddCollidersForSkin(skin, slotIndex, colliders, scale, ref requiredCollidersCount); + + if (skeleton.skin != null) + AddCollidersForSkin(skeleton.skin, slotIndex, colliders, scale, ref requiredCollidersCount); + } + DisposeExcessCollidersAfter(requiredCollidersCount); + + if (BoundingBoxFollowerGraphic.DebugMessages) { + bool valid = colliderTable.Count != 0; + if (!valid) { + if (this.gameObject.activeInHierarchy) + Debug.LogWarning("Bounding Box Follower not valid! Slot [" + slotName + "] does not contain any Bounding Box Attachments!"); + else + Debug.LogWarning("Bounding Box Follower tried to rebuild as a prefab."); + } + } + } + + void AddCollidersForSkin (Skin skin, int slotIndex, PolygonCollider2D[] previousColliders, float scale, ref int collidersCount) { + if (skin == null) return; + var skinEntries = new List(); + skin.GetAttachments(slotIndex, skinEntries); + + foreach (var entry in skinEntries) { + var attachment = skin.GetAttachment(slotIndex, entry.Name); + var boundingBoxAttachment = attachment as BoundingBoxAttachment; + + if (BoundingBoxFollowerGraphic.DebugMessages && attachment != null && boundingBoxAttachment == null) + Debug.Log("BoundingBoxFollowerGraphic tried to follow a slot that contains non-boundingbox attachments: " + slotName); + + if (boundingBoxAttachment != null) { + if (!colliderTable.ContainsKey(boundingBoxAttachment)) { + var bbCollider = collidersCount < previousColliders.Length ? + previousColliders[collidersCount] : gameObject.AddComponent(); + ++collidersCount; + SkeletonUtility.SetColliderPointsLocal(bbCollider, slot, boundingBoxAttachment, scale); + bbCollider.isTrigger = isTrigger; + bbCollider.enabled = false; + bbCollider.hideFlags = HideFlags.NotEditable; + bbCollider.isTrigger = IsTrigger; + colliderTable.Add(boundingBoxAttachment, bbCollider); + nameTable.Add(boundingBoxAttachment, entry.Name); + } + } + } + } + + void OnDisable () { + if (clearStateOnDisable) + ClearState(); + + if (skeletonGraphic != null) + skeletonGraphic.OnRebuild -= HandleRebuild; + } + + public void ClearState () { + if (colliderTable != null) + foreach (var col in colliderTable.Values) + col.enabled = false; + + currentAttachment = null; + currentAttachmentName = null; + currentCollider = null; + } + + void DisposeExcessCollidersAfter (int requiredCount) { + var colliders = GetComponents(); + if (colliders.Length == 0) return; + + for (int i = requiredCount; i < colliders.Length; ++i) { + var collider = colliders[i]; + if (collider != null) { +#if UNITY_EDITOR + if (Application.isEditor && !Application.isPlaying) + DestroyImmediate(collider); + else +#endif + Destroy(collider); + } + } + } + + void LateUpdate () { + if (slot != null && slot.Attachment != currentAttachment) + MatchAttachment(slot.Attachment); + } + + /// Sets the current collider to match attachment. + /// If the attachment is not a bounding box, it will be treated as null. + void MatchAttachment (Attachment attachment) { + var bbAttachment = attachment as BoundingBoxAttachment; + + if (BoundingBoxFollowerGraphic.DebugMessages && attachment != null && bbAttachment == null) + Debug.LogWarning("BoundingBoxFollowerGraphic tried to match a non-boundingbox attachment. It will treat it as null."); + + if (currentCollider != null) + currentCollider.enabled = false; + + if (bbAttachment == null) { + currentCollider = null; + currentAttachment = null; + currentAttachmentName = null; + } else { + PolygonCollider2D foundCollider; + colliderTable.TryGetValue(bbAttachment, out foundCollider); + if (foundCollider != null) { + currentCollider = foundCollider; + currentCollider.enabled = true; + currentAttachment = bbAttachment; + currentAttachmentName = nameTable[bbAttachment]; + } else { + currentCollider = null; + currentAttachment = bbAttachment; + currentAttachmentName = null; + if (BoundingBoxFollowerGraphic.DebugMessages) Debug.LogFormat("Collider for BoundingBoxAttachment named '{0}' was not initialized. It is possibly from a new skin. currentAttachmentName will be null. You may need to call BoundingBoxFollowerGraphic.Initialize(overwrite: true);", bbAttachment.Name); + } + } + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs.meta new file mode 100644 index 0000000..05dc862 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/BoundingBoxFollowerGraphic.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c0bf7b497af9f74280040d96cdf88da +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs new file mode 100644 index 0000000..25aa203 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs @@ -0,0 +1,164 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [AddComponentMenu("Spine/Point Follower")] + [HelpURL("http://esotericsoftware.com/spine-unity#PointFollower")] + public class PointFollower : MonoBehaviour, IHasSkeletonRenderer, IHasSkeletonComponent { + + public SkeletonRenderer skeletonRenderer; + public SkeletonRenderer SkeletonRenderer { get { return this.skeletonRenderer; } } + public ISkeletonComponent SkeletonComponent { get { return skeletonRenderer as ISkeletonComponent; } } + + [SpineSlot(dataField:"skeletonRenderer", includeNone: true)] + public string slotName; + + [SpineAttachment(slotField:"slotName", dataField: "skeletonRenderer", fallbackToTextField:true, includeNone: true)] + public string pointAttachmentName; + + public bool followRotation = true; + public bool followSkeletonFlip = true; + public bool followSkeletonZPosition = false; + + Transform skeletonTransform; + bool skeletonTransformIsParent; + PointAttachment point; + Bone bone; + bool valid; + public bool IsValid { get { return valid; } } + + public void Initialize () { + valid = skeletonRenderer != null && skeletonRenderer.valid; + if (!valid) + return; + + UpdateReferences(); + + #if UNITY_EDITOR + if (Application.isEditor) LateUpdate(); + #endif + } + + private void HandleRebuildRenderer (SkeletonRenderer skeletonRenderer) { + Initialize(); + } + + void UpdateReferences () { + skeletonTransform = skeletonRenderer.transform; + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + skeletonRenderer.OnRebuild += HandleRebuildRenderer; + skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + + bone = null; + point = null; + if (!string.IsNullOrEmpty(pointAttachmentName)) { + var skeleton = skeletonRenderer.Skeleton; + + int slotIndex = skeleton.FindSlotIndex(slotName); + if (slotIndex >= 0) { + var slot = skeleton.slots.Items[slotIndex]; + bone = slot.bone; + point = skeleton.GetAttachment(slotIndex, pointAttachmentName) as PointAttachment; + } + } + } + + void OnDestroy () { + if (skeletonRenderer != null) + skeletonRenderer.OnRebuild -= HandleRebuildRenderer; + } + + public void LateUpdate () { + #if UNITY_EDITOR + if (!Application.isPlaying) skeletonTransformIsParent = Transform.ReferenceEquals(skeletonTransform, transform.parent); + #endif + + if (point == null) { + if (string.IsNullOrEmpty(pointAttachmentName)) return; + UpdateReferences(); + if (point == null) return; + } + + Vector2 worldPos; + point.ComputeWorldPosition(bone, out worldPos.x, out worldPos.y); + float rotation = point.ComputeWorldRotation(bone); + + Transform thisTransform = this.transform; + if (skeletonTransformIsParent) { + // Recommended setup: Use local transform properties if Spine GameObject is the immediate parent + thisTransform.localPosition = new Vector3(worldPos.x, worldPos.y, followSkeletonZPosition ? 0f : thisTransform.localPosition.z); + if (followRotation) { + float halfRotation = rotation * 0.5f * Mathf.Deg2Rad; + + var q = default(Quaternion); + q.z = Mathf.Sin(halfRotation); + q.w = Mathf.Cos(halfRotation); + thisTransform.localRotation = q; + } + } else { + // For special cases: Use transform world properties if transform relationship is complicated + Vector3 targetWorldPosition = skeletonTransform.TransformPoint(new Vector3(worldPos.x, worldPos.y, 0f)); + if (!followSkeletonZPosition) + targetWorldPosition.z = thisTransform.position.z; + + Transform transformParent = thisTransform.parent; + if (transformParent != null) { + Matrix4x4 m = transformParent.localToWorldMatrix; + if (m.m00 * m.m11 - m.m01 * m.m10 < 0) // Determinant2D is negative + rotation = -rotation; + } + + if (followRotation) { + Vector3 transformWorldRotation = skeletonTransform.rotation.eulerAngles; + thisTransform.SetPositionAndRotation(targetWorldPosition, Quaternion.Euler(transformWorldRotation.x, transformWorldRotation.y, transformWorldRotation.z + rotation)); + } else { + thisTransform.position = targetWorldPosition; + } + } + + if (followSkeletonFlip) { + Vector3 localScale = thisTransform.localScale; + localScale.y = Mathf.Abs(localScale.y) * Mathf.Sign(bone.skeleton.ScaleX * bone.skeleton.ScaleY); + thisTransform.localScale = localScale; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs.meta new file mode 100644 index 0000000..1af3893 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/Following/PointFollower.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: daf461e4341180341a648c07e1899528 +timeCreated: 1518094986 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion.meta new file mode 100644 index 0000000..13afcb8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 01776890e2374864d9a09bb3d687ae9f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonMecanimRootMotion.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonMecanimRootMotion.cs new file mode 100644 index 0000000..4a90bdb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonMecanimRootMotion.cs @@ -0,0 +1,121 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using Spine.Unity.AnimationTools; + +namespace Spine.Unity { + + /// + /// Add this component to a SkeletonMecanim GameObject + /// to turn motion of a selected root bone into Transform or RigidBody motion. + /// Local bone translation movement is used as motion. + /// All top-level bones of the skeleton are moved to compensate the root + /// motion bone location, keeping the distance relationship between bones intact. + /// + /// + /// Only compatible with SkeletonMecanim. + /// For SkeletonAnimation or SkeletonGraphic please use + /// SkeletonRootMotion instead. + /// + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonMecanimRootMotion")] + public class SkeletonMecanimRootMotion : SkeletonRootMotionBase { + #region Inspector + const int DefaultMecanimLayerFlags = -1; + public int mecanimLayerFlags = DefaultMecanimLayerFlags; + #endregion + + protected Vector2 movementDelta; + + SkeletonMecanim skeletonMecanim; + public SkeletonMecanim SkeletonMecanim { + get { + return skeletonMecanim ? skeletonMecanim : skeletonMecanim = GetComponent(); + } + } + + public override Vector2 GetRemainingRootMotion (int layerIndex) { + var pair = skeletonMecanim.Translator.GetActiveAnimationAndTime(layerIndex); + var animation = pair.Key; + var time = pair.Value; + if (animation == null) + return Vector2.zero; + + float start = time; + float end = animation.duration; + return GetAnimationRootMotion(start, end, animation); + } + + public override RootMotionInfo GetRootMotionInfo (int layerIndex) { + var pair = skeletonMecanim.Translator.GetActiveAnimationAndTime(layerIndex); + var animation = pair.Key; + var time = pair.Value; + if (animation == null) + return new RootMotionInfo(); + return GetAnimationRootMotionInfo(animation, time); + } + + protected override void Reset () { + base.Reset(); + mecanimLayerFlags = DefaultMecanimLayerFlags; + } + + protected override void Start () { + base.Start(); + skeletonMecanim = GetComponent(); + if (skeletonMecanim) { + skeletonMecanim.Translator.OnClipApplied -= OnClipApplied; + skeletonMecanim.Translator.OnClipApplied += OnClipApplied; + } + } + + void OnClipApplied(Spine.Animation animation, int layerIndex, float weight, + float time, float lastTime, bool playsBackward) { + + if (((mecanimLayerFlags & 1< + /// Add this component to a SkeletonAnimation or SkeletonGraphic GameObject + /// to turn motion of a selected root bone into Transform or RigidBody motion. + /// Local bone translation movement is used as motion. + /// All top-level bones of the skeleton are moved to compensate the root + /// motion bone location, keeping the distance relationship between bones intact. + /// + /// + /// Only compatible with SkeletonAnimation (or other components that implement + /// ISkeletonComponent, ISkeletonAnimation and IAnimationStateComponent). + /// For SkeletonMecanim please use + /// SkeletonMecanimRootMotion instead. + /// + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRootMotion")] + public class SkeletonRootMotion : SkeletonRootMotionBase { + #region Inspector + const int DefaultAnimationTrackFlags = -1; + public int animationTrackFlags = DefaultAnimationTrackFlags; + #endregion + + AnimationState animationState; + Canvas canvas; + + public override Vector2 GetRemainingRootMotion (int trackIndex) { + TrackEntry track = animationState.GetCurrent(trackIndex); + if (track == null) + return Vector2.zero; + + var animation = track.Animation; + float start = track.AnimationTime; + float end = animation.duration; + return GetAnimationRootMotion(start, end, animation); + } + + public override RootMotionInfo GetRootMotionInfo (int trackIndex) { + TrackEntry track = animationState.GetCurrent(trackIndex); + if (track == null) + return new RootMotionInfo(); + + var animation = track.Animation; + float time = track.AnimationTime; + return GetAnimationRootMotionInfo(track.Animation, time); + } + + protected override float AdditionalScale { + get { + return canvas ? canvas.referencePixelsPerUnit: 1.0f; + } + } + + protected override void Reset () { + base.Reset(); + animationTrackFlags = DefaultAnimationTrackFlags; + } + + protected override void Start () { + base.Start(); + var animstateComponent = skeletonComponent as IAnimationStateComponent; + this.animationState = (animstateComponent != null) ? animstateComponent.AnimationState : null; + + if (this.GetComponent() != null) { + canvas = this.GetComponentInParent(); + } + } + + protected override Vector2 CalculateAnimationsMovementDelta () { + Vector2 localDelta = Vector2.zero; + int trackCount = animationState.Tracks.Count; + + for (int trackIndex = 0; trackIndex < trackCount; ++trackIndex) { + // note: animationTrackFlags != -1 below covers trackIndex >= 32, + // with -1 corresponding to entry "everything" of the dropdown list. + if (animationTrackFlags != -1 && (animationTrackFlags & 1 << trackIndex) == 0) + continue; + + TrackEntry track = animationState.GetCurrent(trackIndex); + TrackEntry next = null; + while (track != null) { + var animation = track.Animation; + float start = track.animationLast; + float end = track.AnimationTime; + var currentDelta = GetAnimationRootMotion(start, end, animation); + if (currentDelta != Vector2.zero) { + ApplyMixAlphaToDelta(ref currentDelta, next, track); + localDelta += currentDelta; + } + + // Traverse mixingFrom chain. + next = track; + track = track.mixingFrom; + } + } + return localDelta; + } + + void ApplyMixAlphaToDelta (ref Vector2 currentDelta, TrackEntry next, TrackEntry track) { + // Apply mix alpha to the delta position (based on AnimationState.cs). + float mix; + if (next != null) { + if (next.mixDuration == 0) { // Single frame mix to undo mixingFrom changes. + mix = 1; + } + else { + mix = next.mixTime / next.mixDuration; + if (mix > 1) mix = 1; + } + float mixAndAlpha = track.alpha * next.interruptAlpha * (1 - mix); + currentDelta *= mixAndAlpha; + } + else { + if (track.mixDuration == 0) { + mix = 1; + } + else { + mix = track.alpha * (track.mixTime / track.mixDuration); + if (mix > 1) mix = 1; + } + currentDelta *= mix; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotion.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotion.cs.meta new file mode 100644 index 0000000..bef9e2e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotion.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f21c9538588898a45a3da22bf4779ab3 +timeCreated: 1591121072 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs new file mode 100644 index 0000000..a6222fb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs @@ -0,0 +1,322 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using Spine.Unity.AnimationTools; +using System; + +namespace Spine.Unity { + + /// + /// Base class for skeleton root motion components. + /// + abstract public class SkeletonRootMotionBase : MonoBehaviour { + + #region Inspector + [SpineBone] + [SerializeField] + protected string rootMotionBoneName = "root"; + public bool transformPositionX = true; + public bool transformPositionY = true; + + public float rootMotionScaleX = 1; + public float rootMotionScaleY = 1; + /// Skeleton space X translation per skeleton space Y translation root motion. + public float rootMotionTranslateXPerY = 0; + /// Skeleton space Y translation per skeleton space X translation root motion. + public float rootMotionTranslateYPerX = 0; + + [Header("Optional")] + public Rigidbody2D rigidBody2D; + public Rigidbody rigidBody; + + public bool UsesRigidbody { + get { return rigidBody != null || rigidBody2D != null; } + } + #endregion + + protected ISkeletonComponent skeletonComponent; + protected Bone rootMotionBone; + protected int rootMotionBoneIndex; + protected List topLevelBones = new List(); + protected Vector2 initialOffset = Vector2.zero; + protected Vector2 tempSkeletonDisplacement; + protected Vector2 rigidbodyDisplacement; + + protected virtual void Reset () { + FindRigidbodyComponent(); + } + + protected virtual void Start () { + skeletonComponent = GetComponent(); + GatherTopLevelBones(); + SetRootMotionBone(rootMotionBoneName); + if (rootMotionBone != null) + initialOffset = new Vector2(rootMotionBone.x, rootMotionBone.y); + + var skeletonAnimation = skeletonComponent as ISkeletonAnimation; + if (skeletonAnimation != null) { + skeletonAnimation.UpdateLocal -= HandleUpdateLocal; + skeletonAnimation.UpdateLocal += HandleUpdateLocal; + } + } + + protected virtual void FixedUpdate () { + if (!this.isActiveAndEnabled) + return; // Root motion is only applied when component is enabled. + + if (rigidBody2D != null) { + rigidBody2D.MovePosition(new Vector2(transform.position.x, transform.position.y) + + rigidbodyDisplacement); + } + if (rigidBody != null) { + rigidBody.MovePosition(transform.position + + new Vector3(rigidbodyDisplacement.x, rigidbodyDisplacement.y, 0)); + } + Vector2 parentBoneScale; + GetScaleAffectingRootMotion(out parentBoneScale); + ClearEffectiveBoneOffsets(parentBoneScale); + rigidbodyDisplacement = Vector2.zero; + tempSkeletonDisplacement = Vector2.zero; + } + + protected virtual void OnDisable () { + rigidbodyDisplacement = Vector2.zero; + tempSkeletonDisplacement = Vector2.zero; + } + + protected void FindRigidbodyComponent () { + rigidBody2D = this.GetComponent(); + if (!rigidBody2D) + rigidBody = this.GetComponent(); + + if (!rigidBody2D && !rigidBody) { + rigidBody2D = this.GetComponentInParent(); + if (!rigidBody2D) + rigidBody = this.GetComponentInParent(); + } + } + + protected virtual float AdditionalScale { get { return 1.0f; } } + abstract protected Vector2 CalculateAnimationsMovementDelta (); + abstract public Vector2 GetRemainingRootMotion (int trackIndex = 0); + + public struct RootMotionInfo { + public Vector2 start; + public Vector2 current; + public Vector2 mid; + public Vector2 end; + public bool timeIsPastMid; + }; + abstract public RootMotionInfo GetRootMotionInfo (int trackIndex = 0); + + public void SetRootMotionBone (string name) { + var skeleton = skeletonComponent.Skeleton; + int index = skeleton.FindBoneIndex(name); + if (index >= 0) { + this.rootMotionBoneIndex = index; + this.rootMotionBone = skeleton.bones.Items[index]; + } + else { + Debug.Log("Bone named \"" + name + "\" could not be found."); + this.rootMotionBoneIndex = 0; + this.rootMotionBone = skeleton.RootBone; + } + } + + public void AdjustRootMotionToDistance (Vector2 distanceToTarget, int trackIndex = 0, bool adjustX = true, bool adjustY = true, + float minX = 0, float maxX = float.MaxValue, float minY = 0, float maxY = float.MaxValue, + bool allowXTranslation = false, bool allowYTranslation = false) { + + Vector2 distanceToTargetSkeletonSpace = (Vector2)transform.InverseTransformVector(distanceToTarget); + Vector2 scaleAffectingRootMotion = GetScaleAffectingRootMotion(); + if (UsesRigidbody) + distanceToTargetSkeletonSpace -= tempSkeletonDisplacement; + + Vector2 remainingRootMotionSkeletonSpace = GetRemainingRootMotion(trackIndex); + remainingRootMotionSkeletonSpace.Scale(scaleAffectingRootMotion); + if (remainingRootMotionSkeletonSpace.x == 0) + remainingRootMotionSkeletonSpace.x = 0.0001f; + if (remainingRootMotionSkeletonSpace.y == 0) + remainingRootMotionSkeletonSpace.y = 0.0001f; + + if (adjustX) + rootMotionScaleX = Math.Min(maxX, Math.Max(minX, distanceToTargetSkeletonSpace.x / remainingRootMotionSkeletonSpace.x)); + if (adjustY) + rootMotionScaleY = Math.Min(maxY, Math.Max(minY, distanceToTargetSkeletonSpace.y / remainingRootMotionSkeletonSpace.y)); + + if (allowXTranslation) + rootMotionTranslateXPerY = (distanceToTargetSkeletonSpace.x - remainingRootMotionSkeletonSpace.x * rootMotionScaleX) / remainingRootMotionSkeletonSpace.y; + if (allowYTranslation) + rootMotionTranslateYPerX = (distanceToTargetSkeletonSpace.y - remainingRootMotionSkeletonSpace.y * rootMotionScaleY) / remainingRootMotionSkeletonSpace.x; + } + + public Vector2 GetAnimationRootMotion (Animation animation) { + return GetAnimationRootMotion(0, animation.duration, animation); + } + + public Vector2 GetAnimationRootMotion (float startTime, float endTime, + Animation animation) { + + var timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex); + if (timeline != null) { + return GetTimelineMovementDelta(startTime, endTime, timeline, animation); + } + return Vector2.zero; + } + + public RootMotionInfo GetAnimationRootMotionInfo (Animation animation, float currentTime) { + RootMotionInfo rootMotion = new RootMotionInfo(); + var timeline = animation.FindTranslateTimelineForBone(rootMotionBoneIndex); + if (timeline != null) { + float duration = animation.duration; + float mid = duration * 0.5f; + rootMotion.start = timeline.Evaluate(0); + rootMotion.current = timeline.Evaluate(currentTime); + rootMotion.mid = timeline.Evaluate(mid); + rootMotion.end = timeline.Evaluate(duration); + rootMotion.timeIsPastMid = currentTime > mid; + } + return rootMotion; + } + + Vector2 GetTimelineMovementDelta (float startTime, float endTime, + TranslateTimeline timeline, Animation animation) { + + Vector2 currentDelta; + if (startTime > endTime) // Looped + currentDelta = (timeline.Evaluate(animation.duration) - timeline.Evaluate(startTime)) + + (timeline.Evaluate(endTime) - timeline.Evaluate(0)); + else if (startTime != endTime) // Non-looped + currentDelta = timeline.Evaluate(endTime) - timeline.Evaluate(startTime); + else + currentDelta = Vector2.zero; + return currentDelta; + } + + void GatherTopLevelBones () { + topLevelBones.Clear(); + var skeleton = skeletonComponent.Skeleton; + foreach (var bone in skeleton.Bones) { + if (bone.Parent == null) + topLevelBones.Add(bone); + } + } + + void HandleUpdateLocal (ISkeletonAnimation animatedSkeletonComponent) { + if (!this.isActiveAndEnabled) + return; // Root motion is only applied when component is enabled. + + var boneLocalDelta = CalculateAnimationsMovementDelta(); + Vector2 parentBoneScale; + Vector2 skeletonDelta = GetSkeletonSpaceMovementDelta(boneLocalDelta, out parentBoneScale); + ApplyRootMotion(skeletonDelta, parentBoneScale); + } + + void ApplyRootMotion (Vector2 skeletonDelta, Vector2 parentBoneScale) { + // Apply root motion to Transform or RigidBody; + if (UsesRigidbody) { + rigidbodyDisplacement += (Vector2)transform.TransformVector(skeletonDelta); + + // Accumulated displacement is applied on the next Physics update in FixedUpdate. + // Until the next Physics update, tempBoneDisplacement is offsetting bone locations + // to prevent stutter which would otherwise occur if we don't move every Update. + tempSkeletonDisplacement += skeletonDelta; + SetEffectiveBoneOffsetsTo(tempSkeletonDisplacement, parentBoneScale); + } + else { + transform.position += transform.TransformVector(skeletonDelta); + ClearEffectiveBoneOffsets(parentBoneScale); + } + } + + Vector2 GetScaleAffectingRootMotion () { + Vector2 parentBoneScale; + return GetScaleAffectingRootMotion(out parentBoneScale); + } + + Vector2 GetScaleAffectingRootMotion (out Vector2 parentBoneScale) { + var skeleton = skeletonComponent.Skeleton; + Vector2 totalScale = Vector2.one; + totalScale.x *= skeleton.ScaleX; + totalScale.y *= skeleton.ScaleY; + + parentBoneScale = Vector2.one; + Bone scaleBone = rootMotionBone; + while ((scaleBone = scaleBone.parent) != null) { + parentBoneScale.x *= scaleBone.ScaleX; + parentBoneScale.y *= scaleBone.ScaleY; + } + totalScale = Vector2.Scale(totalScale, parentBoneScale); + totalScale *= AdditionalScale; + return totalScale; + } + + Vector2 GetSkeletonSpaceMovementDelta (Vector2 boneLocalDelta, out Vector2 parentBoneScale) { + Vector2 skeletonDelta = boneLocalDelta; + Vector2 totalScale = GetScaleAffectingRootMotion(out parentBoneScale); + skeletonDelta.Scale(totalScale); + + Vector2 rootMotionTranslation = new Vector2( + rootMotionTranslateXPerY * skeletonDelta.y, + rootMotionTranslateYPerX * skeletonDelta.x); + + skeletonDelta.x *= rootMotionScaleX; + skeletonDelta.y *= rootMotionScaleY; + skeletonDelta.x += rootMotionTranslation.x; + skeletonDelta.y += rootMotionTranslation.y; + + if (!transformPositionX) skeletonDelta.x = 0f; + if (!transformPositionY) skeletonDelta.y = 0f; + return skeletonDelta; + } + + void SetEffectiveBoneOffsetsTo (Vector2 displacementSkeletonSpace, Vector2 parentBoneScale) { + // Move top level bones in opposite direction of the root motion bone + var skeleton = skeletonComponent.Skeleton; + foreach (var topLevelBone in topLevelBones) { + if (topLevelBone == rootMotionBone) { + if (transformPositionX) topLevelBone.x = displacementSkeletonSpace.x / skeleton.ScaleX; + if (transformPositionY) topLevelBone.y = displacementSkeletonSpace.y / skeleton.ScaleY; + } + else { + float offsetX = (initialOffset.x - rootMotionBone.x) * parentBoneScale.x; + float offsetY = (initialOffset.y - rootMotionBone.y) * parentBoneScale.y; + if (transformPositionX) topLevelBone.x = (displacementSkeletonSpace.x / skeleton.ScaleX) + offsetX; + if (transformPositionY) topLevelBone.y = (displacementSkeletonSpace.y / skeleton.ScaleY) + offsetY; + } + } + } + + void ClearEffectiveBoneOffsets (Vector2 parentBoneScale) { + SetEffectiveBoneOffsetsTo(Vector2.zero, parentBoneScale); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs.meta new file mode 100644 index 0000000..719fd62 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/RootMotion/SkeletonRootMotionBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fc23a4f220b20024ab0592719f92587d +timeCreated: 1592849332 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs new file mode 100644 index 0000000..48c4ec7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs @@ -0,0 +1,251 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [AddComponentMenu("Spine/SkeletonAnimation")] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonAnimation-Component")] + public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent { + + #region IAnimationStateComponent + /// + /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. + /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start + public Spine.AnimationState state; + /// + /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it. + /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start + public Spine.AnimationState AnimationState { + get { + Initialize(false); + return this.state; + } + } + private bool wasUpdatedAfterInit = true; + #endregion + + #region Bone Callbacks ISkeletonAnimation + protected event UpdateBonesDelegate _BeforeApply; + protected event UpdateBonesDelegate _UpdateLocal; + protected event UpdateBonesDelegate _UpdateWorld; + protected event UpdateBonesDelegate _UpdateComplete; + + /// + /// Occurs before the animations are applied. + /// Use this callback when you want to change the skeleton state before animations are applied on top. + /// + public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } } + + /// + /// Occurs after the animations are applied and before world space values are resolved. + /// Use this callback when you want to set bone local values. + /// + public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Using this callback will cause the world space values to be solved an extra time. + /// Use this callback if want to use bone world space values, and also set bone local values. + public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values. + /// This callback can also be used when setting world position and the bone matrix. + public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } + #endregion + + #region Serialized state and Beginner API + [SerializeField] + [SpineAnimation] + private string _animationName; + + /// + /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized. + /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property. + public string AnimationName { + get { + if (!valid) { + return _animationName; + } else { + TrackEntry entry = state.GetCurrent(0); + return entry == null ? null : entry.Animation.Name; + } + } + set { + Initialize(false); + if (_animationName == value) { + TrackEntry entry = state.GetCurrent(0); + if (entry != null && entry.loop == loop) + return; + } + _animationName = value; + + if (string.IsNullOrEmpty(value)) { + state.ClearTrack(0); + } else { + var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(value); + if (animationObject != null) + state.SetAnimation(0, animationObject, loop); + } + } + } + + /// Whether or not should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected. + public bool loop; + + /// + /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%. + /// AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively. + public float timeScale = 1; + #endregion + + #region Runtime Instantiation + /// Adds and prepares a SkeletonAnimation component to a GameObject at runtime. + /// The newly instantiated SkeletonAnimation + public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, + bool quiet = false) { + return SkeletonRenderer.AddSpineComponent(gameObject, skeletonDataAsset, quiet); + } + + /// Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it. + /// The newly instantiated SkeletonAnimation component. + public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset, + bool quiet = false) { + return SkeletonRenderer.NewSpineGameObject(skeletonDataAsset, quiet); + } + #endregion + + /// + /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations. + public override void ClearState () { + base.ClearState(); + if (state != null) state.ClearTracks(); + } + + /// + /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers. + /// If set to true, force overwrite an already initialized object. + public override void Initialize (bool overwrite, bool quiet = false) { + if (valid && !overwrite) + return; + base.Initialize(overwrite, quiet); + + if (!valid) + return; + state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); + wasUpdatedAfterInit = false; + + if (!string.IsNullOrEmpty(_animationName)) { + var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName); + if (animationObject != null) { + state.SetAnimation(0, animationObject, loop); + #if UNITY_EDITOR + if (!Application.isPlaying) + Update(0f); + #endif + } + } + } + + void Update () { + #if UNITY_EDITOR + if (!Application.isPlaying) { + Update(0f); + return; + } + #endif + + Update(Time.deltaTime); + } + + /// Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time. + public void Update (float deltaTime) { + if (!valid || state == null) + return; + + wasUpdatedAfterInit = true; + if (updateMode < UpdateMode.OnlyAnimationStatus) + return; + UpdateAnimationStatus(deltaTime); + + if (updateMode == UpdateMode.OnlyAnimationStatus) + return; + ApplyAnimation(); + } + + protected void UpdateAnimationStatus (float deltaTime) { + deltaTime *= timeScale; + skeleton.Update(deltaTime); + state.Update(deltaTime); + } + + protected void ApplyAnimation () { + if (_BeforeApply != null) + _BeforeApply(this); + + if (updateMode != UpdateMode.OnlyEventTimelines) + state.Apply(skeleton); + else + state.ApplyEventTimelinesOnly(skeleton); + + if (_UpdateLocal != null) + _UpdateLocal(this); + + skeleton.UpdateWorldTransform(); + + if (_UpdateWorld != null) { + _UpdateWorld(this); + skeleton.UpdateWorldTransform(); + } + + if (_UpdateComplete != null) { + _UpdateComplete(this); + } + } + + public override void LateUpdate () { + // instantiation can happen from Update() after this component, leading to a missing Update() call. + if (!wasUpdatedAfterInit) Update(0); + base.LateUpdate(); + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs.meta new file mode 100644 index 0000000..23ede7b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonAnimation.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: d247ba06193faa74d9335f5481b2b56c +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs new file mode 100644 index 0000000..aae79e0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs @@ -0,0 +1,825 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; + +namespace Spine.Unity { + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [RequireComponent(typeof(CanvasRenderer), typeof(RectTransform)), DisallowMultipleComponent] + [AddComponentMenu("Spine/SkeletonGraphic (Unity UI Canvas)")] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonGraphic-Component")] + public class SkeletonGraphic : MaskableGraphic, ISkeletonComponent, IAnimationStateComponent, ISkeletonAnimation, IHasSkeletonDataAsset { + + #region Inspector + public SkeletonDataAsset skeletonDataAsset; + public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } + + [SpineSkin(dataField:"skeletonDataAsset", defaultAsEmptyString:true)] + public string initialSkinName; + public bool initialFlipX, initialFlipY; + + [SpineAnimation(dataField:"skeletonDataAsset")] + public string startingAnimation; + public bool startingLoop; + public float timeScale = 1f; + public bool freeze; + + /// Update mode to optionally limit updates to e.g. only apply animations but not update the mesh. + public UpdateMode UpdateMode { get { return updateMode; } set { updateMode = value; } } + protected UpdateMode updateMode = UpdateMode.FullUpdate; + + /// Update mode used when the MeshRenderer becomes invisible + /// (when OnBecameInvisible() is called). Update mode is automatically + /// reset to UpdateMode.FullUpdate when the mesh becomes visible again. + public UpdateMode updateWhenInvisible = UpdateMode.FullUpdate; + + public bool unscaledTime; + public bool allowMultipleCanvasRenderers = false; + public List canvasRenderers = new List(); + protected List rawImages = new List(); + protected int usedRenderersCount = 0; + + // Submesh Separation + public const string SeparatorPartGameObjectName = "Part"; + /// Slot names used to populate separatorSlots list when the Skeleton is initialized. Changing this after initialization does nothing. + [SerializeField] [SpineSlot] protected string[] separatorSlotNames = new string[0]; + + /// Slots that determine where the render is split. This is used by components such as SkeletonRenderSeparator so that the skeleton can be rendered by two separate renderers on different GameObjects. + [System.NonSerialized] public readonly List separatorSlots = new List(); + public bool enableSeparatorSlots = false; + [SerializeField] protected List separatorParts = new List(); + public List SeparatorParts { get { return separatorParts; } } + public bool updateSeparatorPartLocation = true; + + private bool wasUpdatedAfterInit = true; + private Texture baseTexture = null; + + #if UNITY_EDITOR + protected override void OnValidate () { + // This handles Scene View preview. + base.OnValidate (); + if (this.IsValid) { + if (skeletonDataAsset == null) { + Clear(); + } else if (skeletonDataAsset.skeletonJSON == null) { + Clear(); + } else if (skeletonDataAsset.GetSkeletonData(true) != skeleton.data) { + Clear(); + Initialize(true); + if (!allowMultipleCanvasRenderers && (skeletonDataAsset.atlasAssets.Length > 1 || skeletonDataAsset.atlasAssets[0].MaterialCount > 1)) + Debug.LogError("Unity UI does not support multiple textures per Renderer. Please enable 'Advanced - Multiple CanvasRenderers' to generate the required CanvasRenderer GameObjects. Otherwise your skeleton will not be rendered correctly.", this); + } else { + if (freeze) return; + + if (!string.IsNullOrEmpty(initialSkinName)) { + var skin = skeleton.data.FindSkin(initialSkinName); + if (skin != null) { + if (skin == skeleton.data.defaultSkin) + skeleton.SetSkin((Skin)null); + else + skeleton.SetSkin(skin); + } + + } + + // Only provide visual feedback to inspector changes in Unity Editor Edit mode. + if (!Application.isPlaying) { + skeleton.ScaleX = this.initialFlipX ? -1 : 1; + skeleton.ScaleY = this.initialFlipY ? -1 : 1; + + state.ClearTrack(0); + skeleton.SetToSetupPose(); + if (!string.IsNullOrEmpty(startingAnimation)) { + state.SetAnimation(0, startingAnimation, startingLoop); + Update(0f); + } + } + } + } else { + // Under some circumstances (e.g. sometimes on the first import) OnValidate is called + // before SpineEditorUtilities.ImportSpineContent, causing an unnecessary exception. + // The (skeletonDataAsset.skeletonJSON != null) condition serves to prevent this exception. + if (skeletonDataAsset != null && skeletonDataAsset.skeletonJSON != null) + Initialize(true); + } + } + + protected override void Reset () { + + base.Reset(); + if (material == null || material.shader != Shader.Find("Spine/SkeletonGraphic")) + Debug.LogWarning("SkeletonGraphic works best with the SkeletonGraphic material."); + } + #endif + #endregion + + #region Runtime Instantiation + /// Create a new GameObject with a SkeletonGraphic component. + /// Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work. + public static SkeletonGraphic NewSkeletonGraphicGameObject (SkeletonDataAsset skeletonDataAsset, Transform parent, Material material) { + var sg = SkeletonGraphic.AddSkeletonGraphicComponent(new GameObject("New Spine GameObject"), skeletonDataAsset, material); + if (parent != null) sg.transform.SetParent(parent, false); + return sg; + } + + /// Add a SkeletonGraphic component to a GameObject. + /// Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work. + public static SkeletonGraphic AddSkeletonGraphicComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, Material material) { + var c = gameObject.AddComponent(); + if (skeletonDataAsset != null) { + c.material = material; + c.skeletonDataAsset = skeletonDataAsset; + c.Initialize(false); + } + return c; + } + #endregion + + #region Overrides + [System.NonSerialized] readonly Dictionary customTextureOverride = new Dictionary(); + /// Use this Dictionary to override a Texture with a different Texture. + public Dictionary CustomTextureOverride { get { return customTextureOverride; } } + + [System.NonSerialized] readonly Dictionary customMaterialOverride = new Dictionary(); + /// Use this Dictionary to override the Material where the Texture was used at the original atlas. + public Dictionary CustomMaterialOverride { get { return customMaterialOverride; } } + + // This is used by the UI system to determine what to put in the MaterialPropertyBlock. + Texture overrideTexture; + public Texture OverrideTexture { + get { return overrideTexture; } + set { + overrideTexture = value; + canvasRenderer.SetTexture(this.mainTexture); // Refresh canvasRenderer's texture. Make sure it handles null. + } + } + #endregion + + #region Internals + public override Texture mainTexture { + get { + if (overrideTexture != null) return overrideTexture; + return baseTexture; + } + } + + protected override void Awake () { + + base.Awake (); + this.onCullStateChanged.AddListener(OnCullStateChanged); + + SyncRawImagesWithCanvasRenderers(); + if (!this.IsValid) { +#if UNITY_EDITOR + // workaround for special import case of open scene where OnValidate and Awake are + // called in wrong order, before setup of Spine assets. + if (!Application.isPlaying) { + if (this.skeletonDataAsset != null && this.skeletonDataAsset.skeletonJSON == null) + return; + } +#endif + Initialize(false); + Rebuild(CanvasUpdate.PreRender); + } + } + + protected override void OnDestroy () { + Clear(); + base.OnDestroy(); + } + + public override void Rebuild (CanvasUpdate update) { + base.Rebuild(update); + if (canvasRenderer.cull) return; + if (update == CanvasUpdate.PreRender) UpdateMesh(keepRendererCount : true); + if (allowMultipleCanvasRenderers) canvasRenderer.Clear(); + } + + protected override void OnDisable () { + base.OnDisable(); + foreach (var canvasRenderer in canvasRenderers) { + canvasRenderer.Clear(); + } + } + + public virtual void Update () { + #if UNITY_EDITOR + if (!Application.isPlaying) { + Update(0f); + return; + } + #endif + + if (freeze) return; + Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime); + } + + public virtual void Update (float deltaTime) { + if (!this.IsValid) return; + + wasUpdatedAfterInit = true; + if (updateMode < UpdateMode.OnlyAnimationStatus) + return; + UpdateAnimationStatus(deltaTime); + + if (updateMode == UpdateMode.OnlyAnimationStatus) + return; + ApplyAnimation(); + } + + protected void SyncRawImagesWithCanvasRenderers () { + rawImages.Clear(); + foreach (var canvasRenderer in canvasRenderers) { + var rawImage = canvasRenderer.GetComponent(); + if (rawImage == null) { + rawImage = canvasRenderer.gameObject.AddComponent(); + rawImage.maskable = this.maskable; + rawImage.raycastTarget = false; + } + rawImages.Add(rawImage); + } + } + + protected void UpdateAnimationStatus (float deltaTime) { + deltaTime *= timeScale; + skeleton.Update(deltaTime); + state.Update(deltaTime); + } + + protected void ApplyAnimation () { + if (BeforeApply != null) + BeforeApply(this); + + if (updateMode != UpdateMode.OnlyEventTimelines) + state.Apply(skeleton); + else + state.ApplyEventTimelinesOnly(skeleton); + + if (UpdateLocal != null) + UpdateLocal(this); + + skeleton.UpdateWorldTransform(); + + if (UpdateWorld != null) { + UpdateWorld(this); + skeleton.UpdateWorldTransform(); + } + + if (UpdateComplete != null) + UpdateComplete(this); + } + + public void LateUpdate () { + // instantiation can happen from Update() after this component, leading to a missing Update() call. + if (!wasUpdatedAfterInit) Update(0); + if (freeze) return; + if (updateMode != UpdateMode.FullUpdate) return; + + UpdateMesh(); + } + + protected void OnCullStateChanged (bool culled) { + if (culled) + OnBecameInvisible(); + else + OnBecameVisible(); + } + + public void OnBecameVisible () { + updateMode = UpdateMode.FullUpdate; + } + + public void OnBecameInvisible () { + updateMode = updateWhenInvisible; + } + + public void ReapplySeparatorSlotNames () { + if (!IsValid) + return; + + separatorSlots.Clear(); + for (int i = 0, n = separatorSlotNames.Length; i < n; i++) { + string slotName = separatorSlotNames[i]; + if (slotName == "") + continue; + var slot = skeleton.FindSlot(slotName); + if (slot != null) { + separatorSlots.Add(slot); + } + #if UNITY_EDITOR + else + { + Debug.LogWarning(slotName + " is not a slot in " + skeletonDataAsset.skeletonJSON.name); + } + #endif + } + UpdateSeparatorPartParents(); + } + #endregion + + #region API + protected Skeleton skeleton; + public Skeleton Skeleton { + get { + Initialize(false); + return skeleton; + } + set { + skeleton = value; + } + } + public SkeletonData SkeletonData { get { return skeleton == null ? null : skeleton.data; } } + public bool IsValid { get { return skeleton != null; } } + + public delegate void SkeletonRendererDelegate (SkeletonGraphic skeletonGraphic); + + /// OnRebuild is raised after the Skeleton is successfully initialized. + public event SkeletonRendererDelegate OnRebuild; + + /// OnMeshAndMaterialsUpdated is at the end of LateUpdate after the Mesh and + /// all materials have been updated. + public event SkeletonRendererDelegate OnMeshAndMaterialsUpdated; + + protected Spine.AnimationState state; + public Spine.AnimationState AnimationState { + get { + Initialize(false); + return state; + } + } + + [SerializeField] protected Spine.Unity.MeshGenerator meshGenerator = new MeshGenerator(); + public Spine.Unity.MeshGenerator MeshGenerator { get { return this.meshGenerator; } } + DoubleBuffered meshBuffers; + SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); + readonly ExposedList meshes = new ExposedList(); + + public Mesh GetLastMesh () { + return meshBuffers.GetCurrent().mesh; + } + + public bool MatchRectTransformWithBounds () { + UpdateMesh(); + + if (!this.allowMultipleCanvasRenderers) + return MatchRectTransformSingleRenderer(); + else + return MatchRectTransformMultipleRenderers(); + } + + protected bool MatchRectTransformSingleRenderer () { + Mesh mesh = this.GetLastMesh(); + if (mesh == null) { + return false; + } + if (mesh.vertexCount == 0) { + this.rectTransform.sizeDelta = new Vector2(50f, 50f); + this.rectTransform.pivot = new Vector2(0.5f, 0.5f); + return false; + } + mesh.RecalculateBounds(); + SetRectTransformBounds(mesh.bounds); + return true; + } + + protected bool MatchRectTransformMultipleRenderers () { + bool anyBoundsAdded = false; + Bounds combinedBounds = new Bounds(); + for (int i = 0; i < canvasRenderers.Count; ++i) { + var canvasRenderer = canvasRenderers[i]; + if (!canvasRenderer.gameObject.activeSelf) + continue; + + Mesh mesh = meshes.Items[i]; + if (mesh == null || mesh.vertexCount == 0) + continue; + + mesh.RecalculateBounds(); + var bounds = mesh.bounds; + if (anyBoundsAdded) + combinedBounds.Encapsulate(bounds); + else { + anyBoundsAdded = true; + combinedBounds = bounds; + } + } + + if (!anyBoundsAdded) { + this.rectTransform.sizeDelta = new Vector2(50f, 50f); + this.rectTransform.pivot = new Vector2(0.5f, 0.5f); + return false; + } + + SetRectTransformBounds(combinedBounds); + return true; + } + + private void SetRectTransformBounds (Bounds combinedBounds) { + var size = combinedBounds.size; + var center = combinedBounds.center; + var p = new Vector2( + 0.5f - (center.x / size.x), + 0.5f - (center.y / size.y) + ); + + this.rectTransform.sizeDelta = size; + this.rectTransform.pivot = p; + } + + public event UpdateBonesDelegate BeforeApply; + public event UpdateBonesDelegate UpdateLocal; + public event UpdateBonesDelegate UpdateWorld; + public event UpdateBonesDelegate UpdateComplete; + + /// Occurs after the vertex data populated every frame, before the vertices are pushed into the mesh. + public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; + + public void Clear () { + skeleton = null; + canvasRenderer.Clear(); + + for (int i = 0; i < canvasRenderers.Count; ++i) + canvasRenderers[i].Clear(); + DestroyMeshes(); + DisposeMeshBuffers(); + } + + public void TrimRenderers () { + var newList = new List(); + foreach (var canvasRenderer in canvasRenderers) { + if (canvasRenderer.gameObject.activeSelf) { + newList.Add(canvasRenderer); + } + else { + if (Application.isEditor && !Application.isPlaying) + DestroyImmediate(canvasRenderer.gameObject); + else + Destroy(canvasRenderer.gameObject); + } + } + canvasRenderers = newList; + SyncRawImagesWithCanvasRenderers(); + } + + public void Initialize (bool overwrite) { + if (this.IsValid && !overwrite) return; + + if (this.skeletonDataAsset == null) return; + var skeletonData = this.skeletonDataAsset.GetSkeletonData(false); + if (skeletonData == null) return; + + if (skeletonDataAsset.atlasAssets.Length <= 0 || skeletonDataAsset.atlasAssets[0].MaterialCount <= 0) return; + + this.state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); + if (state == null) { + Clear(); + return; + } + + this.skeleton = new Skeleton(skeletonData) { + ScaleX = this.initialFlipX ? -1 : 1, + ScaleY = this.initialFlipY ? -1 : 1 + }; + + InitMeshBuffers(); + baseTexture = skeletonDataAsset.atlasAssets[0].PrimaryMaterial.mainTexture; + canvasRenderer.SetTexture(this.mainTexture); // Needed for overwriting initializations. + + // Set the initial Skin and Animation + if (!string.IsNullOrEmpty(initialSkinName)) + skeleton.SetSkin(initialSkinName); + + separatorSlots.Clear(); + for (int i = 0; i < separatorSlotNames.Length; i++) + separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); + + wasUpdatedAfterInit = false; + if (!string.IsNullOrEmpty(startingAnimation)) { + var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(startingAnimation); + if (animationObject != null) { + state.SetAnimation(0, animationObject, startingLoop); + #if UNITY_EDITOR + if (!Application.isPlaying) + Update(0f); + #endif + } + } + + if (OnRebuild != null) + OnRebuild(this); + } + + public void UpdateMesh (bool keepRendererCount = false) { + if (!this.IsValid) return; + + skeleton.SetColor(this.color); + + var currentInstructions = this.currentInstructions; + if (!this.allowMultipleCanvasRenderers) { + UpdateMeshSingleCanvasRenderer(); + } + else { + UpdateMeshMultipleCanvasRenderers(currentInstructions, keepRendererCount); + } + + if (OnMeshAndMaterialsUpdated != null) + OnMeshAndMaterialsUpdated(this); + } + + public bool HasMultipleSubmeshInstructions () { + if (!IsValid) + return false; + return MeshGenerator.RequiresMultipleSubmeshesByDrawOrder(skeleton); + } + #endregion + + protected void InitMeshBuffers () { + if (meshBuffers != null) { + meshBuffers.GetNext().Clear(); + meshBuffers.GetNext().Clear(); + } + else { + meshBuffers = new DoubleBuffered(); + } + } + + protected void DisposeMeshBuffers () { + if (meshBuffers != null) { + meshBuffers.GetNext().Dispose(); + meshBuffers.GetNext().Dispose(); + meshBuffers = null; + } + } + + protected void UpdateMeshSingleCanvasRenderer () { + if (canvasRenderers.Count > 0) + DisableUnusedCanvasRenderers(usedCount : 0); + + var smartMesh = meshBuffers.GetNext(); + MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, null); + bool updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, smartMesh.instructionUsed); + + meshGenerator.Begin(); + if (currentInstructions.hasActiveClipping && currentInstructions.submeshInstructions.Count > 0) { + meshGenerator.AddSubmesh(currentInstructions.submeshInstructions.Items[0], updateTriangles); + } + else { + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + if (canvas != null) meshGenerator.ScaleVertexData(canvas.referencePixelsPerUnit); + if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); + + var mesh = smartMesh.mesh; + meshGenerator.FillVertexData(mesh); + if (updateTriangles) meshGenerator.FillTriangles(mesh); + meshGenerator.FillLateVertexData(mesh); + + canvasRenderer.SetMesh(mesh); + smartMesh.instructionUsed.Set(currentInstructions); + + if (currentInstructions.submeshInstructions.Count > 0) { + var material = currentInstructions.submeshInstructions.Items[0].material; + if (material != null && baseTexture != material.mainTexture) { + baseTexture = material.mainTexture; + if (overrideTexture == null) + canvasRenderer.SetTexture(this.mainTexture); + } + } + + //this.UpdateMaterial(); // note: This would allocate memory. + usedRenderersCount = 0; + } + + protected void UpdateMeshMultipleCanvasRenderers (SkeletonRendererInstruction currentInstructions, bool keepRendererCount) { + MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, null, + enableSeparatorSlots ? separatorSlots : null, + enableSeparatorSlots ? separatorSlots.Count > 0 : false, + false); + + int submeshCount = currentInstructions.submeshInstructions.Count; + if (keepRendererCount && submeshCount != usedRenderersCount) + return; + EnsureCanvasRendererCount(submeshCount); + EnsureMeshesCount(submeshCount); + EnsureSeparatorPartCount(); + + var c = canvas; + float scale = (c == null) ? 100 : c.referencePixelsPerUnit; + + // Generate meshes. + var meshesItems = meshes.Items; + bool useOriginalTextureAndMaterial = (customMaterialOverride.Count == 0 && customTextureOverride.Count == 0); + int separatorSlotGroupIndex = 0; + Transform parent = this.separatorSlots.Count == 0 ? this.transform : this.separatorParts[0]; + + if (updateSeparatorPartLocation) { + for (int p = 0; p < this.separatorParts.Count; ++p) { + separatorParts[p].position = this.transform.position; + separatorParts[p].rotation = this.transform.rotation; + } + } + + int targetSiblingIndex = 0; + for (int i = 0; i < submeshCount; i++) { + var submeshInstructionItem = currentInstructions.submeshInstructions.Items[i]; + meshGenerator.Begin(); + meshGenerator.AddSubmesh(submeshInstructionItem); + + var targetMesh = meshesItems[i]; + meshGenerator.ScaleVertexData(scale); + if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); + meshGenerator.FillVertexData(targetMesh); + meshGenerator.FillTriangles(targetMesh); + meshGenerator.FillLateVertexData(targetMesh); + + var submeshMaterial = submeshInstructionItem.material; + var canvasRenderer = canvasRenderers[i]; + if (i >= usedRenderersCount) + canvasRenderer.gameObject.SetActive(true); + + canvasRenderer.SetMesh(targetMesh); + canvasRenderer.materialCount = 1; + + if (canvasRenderer.transform.parent != parent.transform) { + canvasRenderer.transform.SetParent(parent.transform, false); + canvasRenderer.transform.localPosition = Vector3.zero; + } + canvasRenderer.transform.SetSiblingIndex(targetSiblingIndex++); + if (submeshInstructionItem.forceSeparate) { + targetSiblingIndex = 0; + parent = separatorParts[++separatorSlotGroupIndex]; + } + + if (useOriginalTextureAndMaterial) + canvasRenderer.SetMaterial(this.materialForRendering, submeshMaterial.mainTexture); + else { + var originalTexture = submeshMaterial.mainTexture; + Material usedMaterial; + Texture usedTexture; + if (!customMaterialOverride.TryGetValue(originalTexture, out usedMaterial)) + usedMaterial = material; + if (!customTextureOverride.TryGetValue(originalTexture, out usedTexture)) + usedTexture = originalTexture; + canvasRenderer.SetMaterial(usedMaterial, usedTexture); + } + } + + DisableUnusedCanvasRenderers(usedCount : submeshCount); + usedRenderersCount = submeshCount; + } + + protected void EnsureCanvasRendererCount (int targetCount) { + #if UNITY_EDITOR + RemoveNullCanvasRenderers(); + #endif + int currentCount = canvasRenderers.Count; + for (int i = currentCount; i < targetCount; ++i) { + var go = new GameObject(string.Format("Renderer{0}", i), typeof(RectTransform)); + go.transform.SetParent(this.transform, false); + go.transform.localPosition = Vector3.zero; + var canvasRenderer = go.AddComponent(); + canvasRenderers.Add(canvasRenderer); + var rawImage = go.AddComponent(); + rawImage.maskable = this.maskable; + rawImage.raycastTarget = false; + rawImages.Add(rawImage); + } + } + + protected void DisableUnusedCanvasRenderers (int usedCount) { + #if UNITY_EDITOR + RemoveNullCanvasRenderers(); + #endif + for (int i = usedCount; i < canvasRenderers.Count; i++) { + canvasRenderers[i].Clear(); + canvasRenderers[i].gameObject.SetActive(false); + } + } + + #if UNITY_EDITOR + private void RemoveNullCanvasRenderers () { + if (Application.isEditor && !Application.isPlaying) { + for (int i = canvasRenderers.Count - 1; i >= 0; --i) { + if (canvasRenderers[i] == null) { + canvasRenderers.RemoveAt(i); + } + } + } + } + #endif + + protected void EnsureMeshesCount (int targetCount) { + int oldCount = meshes.Count; + meshes.EnsureCapacity(targetCount); + for (int i = oldCount; i < targetCount; i++) + meshes.Add(SpineMesh.NewSkeletonMesh()); + } + + protected void DestroyMeshes () { + foreach (var mesh in meshes) { +#if UNITY_EDITOR + if (Application.isEditor && !Application.isPlaying) + UnityEngine.Object.DestroyImmediate(mesh); + else + UnityEngine.Object.Destroy(mesh); +#else + UnityEngine.Object.Destroy(mesh); +#endif + } + meshes.Clear(); + } + + protected void EnsureSeparatorPartCount () { + #if UNITY_EDITOR + RemoveNullSeparatorParts(); + #endif + int targetCount = separatorSlots.Count + 1; + if (targetCount == 1) + return; + + #if UNITY_EDITOR + if (Application.isEditor && !Application.isPlaying) { + for (int i = separatorParts.Count-1; i >= 0; --i) { + if (separatorParts[i] == null) { + separatorParts.RemoveAt(i); + } + } + } + #endif + int currentCount = separatorParts.Count; + for (int i = currentCount; i < targetCount; ++i) { + var go = new GameObject(string.Format("{0}[{1}]", SeparatorPartGameObjectName, i), typeof(RectTransform)); + go.transform.SetParent(this.transform, false); + go.transform.localPosition = Vector3.zero; + separatorParts.Add(go.transform); + } + } + + protected void UpdateSeparatorPartParents () { + int usedCount = separatorSlots.Count + 1; + if (usedCount == 1) { + usedCount = 0; // placed directly at the SkeletonGraphic parent + for (int i = 0; i < canvasRenderers.Count; ++i) { + var canvasRenderer = canvasRenderers[i]; + if (canvasRenderer.transform.parent.name.Contains(SeparatorPartGameObjectName)) { + canvasRenderer.transform.SetParent(this.transform, false); + canvasRenderer.transform.localPosition = Vector3.zero; + } + } + } + for (int i = 0; i < separatorParts.Count; ++i) { + bool isUsed = i < usedCount; + separatorParts[i].gameObject.SetActive(isUsed); + } + } + + #if UNITY_EDITOR + private void RemoveNullSeparatorParts () { + if (Application.isEditor && !Application.isPlaying) { + for (int i = separatorParts.Count - 1; i >= 0; --i) { + if (separatorParts[i] == null) { + separatorParts.RemoveAt(i); + } + } + } + } + #endif + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs.meta new file mode 100644 index 0000000..e44ab78 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonGraphic.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: d85b887af7e6c3f45a2e2d2920d641bc +timeCreated: 1455576193 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: + - m_Material: {fileID: 2100000, guid: b66cf7a186d13054989b33a5c90044e4, type: 2} + - skeletonDataAsset: {instanceID: 0} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs new file mode 100644 index 0000000..3355aa6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs @@ -0,0 +1,661 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; + +namespace Spine.Unity { + [RequireComponent(typeof(Animator))] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonMecanim-Component")] + public class SkeletonMecanim : SkeletonRenderer, ISkeletonAnimation { + + [SerializeField] protected MecanimTranslator translator; + public MecanimTranslator Translator { get { return translator; } } + private bool wasUpdatedAfterInit = true; + + #region Bone Callbacks (ISkeletonAnimation) + protected event UpdateBonesDelegate _BeforeApply; + protected event UpdateBonesDelegate _UpdateLocal; + protected event UpdateBonesDelegate _UpdateWorld; + protected event UpdateBonesDelegate _UpdateComplete; + + /// + /// Occurs before the animations are applied. + /// Use this callback when you want to change the skeleton state before animations are applied on top. + /// + public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } } + + /// + /// Occurs after the animations are applied and before world space values are resolved. + /// Use this callback when you want to set bone local values. + public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Using this callback will cause the world space values to be solved an extra time. + /// Use this callback if want to use bone world space values, and also set bone local values. + public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } } + + /// + /// Occurs after the Skeleton's bone world space values are resolved (including all constraints). + /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values. + /// This callback can also be used when setting world position and the bone matrix. + public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } } + #endregion + + public override void Initialize (bool overwrite, bool quiet = false) { + if (valid && !overwrite) + return; + + base.Initialize(overwrite, quiet); + + if (!valid) + return; + + if (translator == null) translator = new MecanimTranslator(); + translator.Initialize(GetComponent(), this.skeletonDataAsset); + wasUpdatedAfterInit = false; + } + + public void Update () { + if (!valid) return; + + wasUpdatedAfterInit = true; + // animation status is kept by Mecanim Animator component + if (updateMode <= UpdateMode.OnlyAnimationStatus) + return; + ApplyAnimation(); + } + + protected void ApplyAnimation () { + if (_BeforeApply != null) + _BeforeApply(this); + + #if UNITY_EDITOR + var translatorAnimator = translator.Animator; + if (translatorAnimator != null && !translatorAnimator.isInitialized) + translatorAnimator.Rebind(); + + if (Application.isPlaying) { + translator.Apply(skeleton); + } + else { + if (translatorAnimator != null && translatorAnimator.isInitialized && + translatorAnimator.isActiveAndEnabled && translatorAnimator.runtimeAnimatorController != null) { + // Note: Rebind is required to prevent warning "Animator is not playing an AnimatorController" with prefabs + translatorAnimator.Rebind(); + translator.Apply(skeleton); + } + } + #else + translator.Apply(skeleton); + #endif + + // UpdateWorldTransform and Bone Callbacks + { + if (_UpdateLocal != null) + _UpdateLocal(this); + + skeleton.UpdateWorldTransform(); + + if (_UpdateWorld != null) { + _UpdateWorld(this); + skeleton.UpdateWorldTransform(); + } + + if (_UpdateComplete != null) + _UpdateComplete(this); + } + } + + public override void LateUpdate () { + // instantiation can happen from Update() after this component, leading to a missing Update() call. + if (!wasUpdatedAfterInit) Update(); + base.LateUpdate(); + } + + [System.Serializable] + public class MecanimTranslator { + + const float WeightEpsilon = 0.0001f; + + #region Inspector + public bool autoReset = true; + public bool useCustomMixMode = true; + public MixMode[] layerMixModes = new MixMode[0]; + public MixBlend[] layerBlendModes = new MixBlend[0]; + #endregion + + public delegate void OnClipAppliedDelegate (Spine.Animation clip, int layerIndex, float weight, + float time, float lastTime, bool playsBackward); + protected event OnClipAppliedDelegate _OnClipApplied; + + public event OnClipAppliedDelegate OnClipApplied { add { _OnClipApplied += value; } remove { _OnClipApplied -= value; } } + + public enum MixMode { AlwaysMix, MixNext, Hard } + + readonly Dictionary animationTable = new Dictionary(IntEqualityComparer.Instance); + readonly Dictionary clipNameHashCodeTable = new Dictionary(AnimationClipEqualityComparer.Instance); + readonly List previousAnimations = new List(); + + protected class ClipInfos { + public bool isInterruptionActive = false; + public bool isLastFrameOfInterruption = false; + + public int clipInfoCount = 0; + public int nextClipInfoCount = 0; + public int interruptingClipInfoCount = 0; + public readonly List clipInfos = new List(); + public readonly List nextClipInfos = new List(); + public readonly List interruptingClipInfos = new List(); + + public AnimatorStateInfo stateInfo; + public AnimatorStateInfo nextStateInfo; + public AnimatorStateInfo interruptingStateInfo; + + public float interruptingClipTimeAddition = 0; + } + protected ClipInfos[] layerClipInfos = new ClipInfos[0]; + + Animator animator; + public Animator Animator { get { return this.animator; } } + + public int MecanimLayerCount { + get { + if (!animator) + return 0; + return animator.layerCount; + } + } + + public string[] MecanimLayerNames { + get { + if (!animator) + return new string[0]; + string[] layerNames = new string[animator.layerCount]; + for (int i = 0; i < animator.layerCount; ++i) { + layerNames[i] = animator.GetLayerName(i); + } + return layerNames; + } + } + + public void Initialize(Animator animator, SkeletonDataAsset skeletonDataAsset) { + this.animator = animator; + + previousAnimations.Clear(); + + animationTable.Clear(); + var data = skeletonDataAsset.GetSkeletonData(true); + foreach (var a in data.Animations) + animationTable.Add(a.Name.GetHashCode(), a); + + clipNameHashCodeTable.Clear(); + ClearClipInfosForLayers(); + } + + private bool ApplyAnimation (Skeleton skeleton, AnimatorClipInfo info, AnimatorStateInfo stateInfo, + int layerIndex, float layerWeight, MixBlend layerBlendMode, bool useClipWeight1 = false) { + float weight = info.weight * layerWeight; + if (weight < WeightEpsilon) + return false; + + var clip = GetAnimation(info.clip); + if (clip == null) + return false; + + var time = AnimationTime(stateInfo.normalizedTime, info.clip.length, + info.clip.isLooping, stateInfo.speed < 0); + weight = useClipWeight1 ? layerWeight : weight; + clip.Apply(skeleton, 0, time, info.clip.isLooping, null, + weight, layerBlendMode, MixDirection.In); + if (_OnClipApplied != null) + OnClipAppliedCallback(clip, stateInfo, layerIndex, time, info.clip.isLooping, weight); + return true; + } + + private bool ApplyInterruptionAnimation (Skeleton skeleton, + bool interpolateWeightTo1, AnimatorClipInfo info, AnimatorStateInfo stateInfo, + int layerIndex, float layerWeight, MixBlend layerBlendMode, float interruptingClipTimeAddition, + bool useClipWeight1 = false) { + + float clipWeight = interpolateWeightTo1 ? (info.weight + 1.0f) * 0.5f : info.weight; + float weight = clipWeight * layerWeight; + if (weight < WeightEpsilon) + return false; + + var clip = GetAnimation(info.clip); + if (clip == null) + return false; + + var time = AnimationTime(stateInfo.normalizedTime + interruptingClipTimeAddition, + info.clip.length, stateInfo.speed < 0); + weight = useClipWeight1 ? layerWeight : weight; + clip.Apply(skeleton, 0, time, info.clip.isLooping, null, + weight, layerBlendMode, MixDirection.In); + if (_OnClipApplied != null) { + OnClipAppliedCallback(clip, stateInfo, layerIndex, time, info.clip.isLooping, weight); + } + return true; + } + + private void OnClipAppliedCallback (Spine.Animation clip, AnimatorStateInfo stateInfo, + int layerIndex, float time, bool isLooping, float weight) { + + float speedFactor = stateInfo.speedMultiplier * stateInfo.speed; + float lastTime = time - (Time.deltaTime * speedFactor); + if (isLooping && clip.duration != 0) { + time %= clip.duration; + lastTime %= clip.duration; + } + _OnClipApplied(clip, layerIndex, weight, time, lastTime, speedFactor < 0); + } + + public void Apply (Skeleton skeleton) { + #if UNITY_EDITOR + if (!Application.isPlaying) { + GetLayerBlendModes(); + } + #endif + + if (layerMixModes.Length < animator.layerCount) { + int oldSize = layerMixModes.Length; + System.Array.Resize(ref layerMixModes, animator.layerCount); + for (int layer = oldSize; layer < animator.layerCount; ++layer) { + bool isAdditiveLayer = false; + if (layer < layerBlendModes.Length) + isAdditiveLayer = layerBlendModes[layer] == MixBlend.Add; + layerMixModes[layer] = isAdditiveLayer ? MixMode.AlwaysMix : MixMode.MixNext; + } + } + + InitClipInfosForLayers(); + for (int layer = 0, n = animator.layerCount; layer < n; layer++) { + GetStateUpdatesFromAnimator(layer); + } + + // Clear Previous + if (autoReset) { + var previousAnimations = this.previousAnimations; + for (int i = 0, n = previousAnimations.Count; i < n; i++) + previousAnimations[i].SetKeyedItemsToSetupPose(skeleton); + + previousAnimations.Clear(); + for (int layer = 0, n = animator.layerCount; layer < n; layer++) { + float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1. + if (layerWeight <= 0) continue; + + AnimatorStateInfo nextStateInfo = animator.GetNextAnimatorStateInfo(layer); + + bool hasNext = nextStateInfo.fullPathHash != 0; + + int clipInfoCount, nextClipInfoCount, interruptingClipInfoCount; + IList clipInfo, nextClipInfo, interruptingClipInfo; + bool isInterruptionActive, shallInterpolateWeightTo1; + GetAnimatorClipInfos(layer, out isInterruptionActive, out clipInfoCount, out nextClipInfoCount, out interruptingClipInfoCount, + out clipInfo, out nextClipInfo, out interruptingClipInfo, out shallInterpolateWeightTo1); + + for (int c = 0; c < clipInfoCount; c++) { + var info = clipInfo[c]; + float weight = info.weight * layerWeight; if (weight < WeightEpsilon) continue; + var clip = GetAnimation(info.clip); + if (clip != null) + previousAnimations.Add(clip); + } + + if (hasNext) { + for (int c = 0; c < nextClipInfoCount; c++) { + var info = nextClipInfo[c]; + float weight = info.weight * layerWeight; if (weight < WeightEpsilon) continue; + var clip = GetAnimation(info.clip); + if (clip != null) + previousAnimations.Add(clip); + } + } + + if (isInterruptionActive) { + for (int c = 0; c < interruptingClipInfoCount; c++) + { + var info = interruptingClipInfo[c]; + float clipWeight = shallInterpolateWeightTo1 ? (info.weight + 1.0f) * 0.5f : info.weight; + float weight = clipWeight * layerWeight; if (weight < WeightEpsilon) continue; + var clip = GetAnimation(info.clip); + if (clip != null) + previousAnimations.Add(clip); + } + } + } + } + + // Apply + for (int layer = 0, n = animator.layerCount; layer < n; layer++) { + float layerWeight = (layer == 0) ? 1 : animator.GetLayerWeight(layer); // Animator.GetLayerWeight always returns 0 on the first layer. Should be interpreted as 1. + + bool isInterruptionActive; + AnimatorStateInfo stateInfo; + AnimatorStateInfo nextStateInfo; + AnimatorStateInfo interruptingStateInfo; + float interruptingClipTimeAddition; + GetAnimatorStateInfos(layer, out isInterruptionActive, out stateInfo, out nextStateInfo, out interruptingStateInfo, out interruptingClipTimeAddition); + + bool hasNext = nextStateInfo.fullPathHash != 0; + + int clipInfoCount, nextClipInfoCount, interruptingClipInfoCount; + IList clipInfo, nextClipInfo, interruptingClipInfo; + bool interpolateWeightTo1; + GetAnimatorClipInfos(layer, out isInterruptionActive, out clipInfoCount, out nextClipInfoCount, out interruptingClipInfoCount, + out clipInfo, out nextClipInfo, out interruptingClipInfo, out interpolateWeightTo1); + + MixBlend layerBlendMode = (layer < layerBlendModes.Length) ? layerBlendModes[layer] : MixBlend.Replace; + MixMode mode = GetMixMode(layer, layerBlendMode); + if (mode == MixMode.AlwaysMix) { + // Always use Mix instead of Applying the first non-zero weighted clip. + for (int c = 0; c < clipInfoCount; c++) { + ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode); + } + if (hasNext) { + for (int c = 0; c < nextClipInfoCount; c++) { + ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode); + } + } + if (isInterruptionActive) { + for (int c = 0; c < interruptingClipInfoCount; c++) + { + ApplyInterruptionAnimation(skeleton, interpolateWeightTo1, + interruptingClipInfo[c], interruptingStateInfo, + layer, layerWeight, layerBlendMode, interruptingClipTimeAddition); + } + } + } else { // case MixNext || Hard + // Apply first non-zero weighted clip + int c = 0; + for (; c < clipInfoCount; c++) { + if (!ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode, useClipWeight1:true)) + continue; + ++c; break; + } + // Mix the rest + for (; c < clipInfoCount; c++) { + ApplyAnimation(skeleton, clipInfo[c], stateInfo, layer, layerWeight, layerBlendMode); + } + + c = 0; + if (hasNext) { + // Apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights) + if (mode == MixMode.Hard) { + for (; c < nextClipInfoCount; c++) { + if (!ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode, useClipWeight1:true)) + continue; + ++c; break; + } + } + // Mix the rest + for (; c < nextClipInfoCount; c++) { + if (!ApplyAnimation(skeleton, nextClipInfo[c], nextStateInfo, layer, layerWeight, layerBlendMode)) + continue; + } + } + + c = 0; + if (isInterruptionActive) { + // Apply next clip directly instead of mixing (ie: no crossfade, ignores mecanim transition weights) + if (mode == MixMode.Hard) { + for (; c < interruptingClipInfoCount; c++) { + if (ApplyInterruptionAnimation(skeleton, interpolateWeightTo1, + interruptingClipInfo[c], interruptingStateInfo, + layer, layerWeight, layerBlendMode, interruptingClipTimeAddition, useClipWeight1:true)) { + + ++c; break; + } + } + } + // Mix the rest + for (; c < interruptingClipInfoCount; c++) { + ApplyInterruptionAnimation(skeleton, interpolateWeightTo1, + interruptingClipInfo[c], interruptingStateInfo, + layer, layerWeight, layerBlendMode, interruptingClipTimeAddition); + } + } + } + } + } + + public KeyValuePair GetActiveAnimationAndTime (int layer) { + if (layer >= layerClipInfos.Length) + return new KeyValuePair(null, 0); + + var layerInfos = layerClipInfos[layer]; + bool isInterruptionActive = layerInfos.isInterruptionActive; + AnimationClip clip = null; + Spine.Animation animation = null; + AnimatorStateInfo stateInfo; + if (isInterruptionActive && layerInfos.interruptingClipInfoCount > 0) { + clip = layerInfos.interruptingClipInfos[0].clip; + stateInfo = layerInfos.interruptingStateInfo; + } + else { + clip = layerInfos.clipInfos[0].clip; + stateInfo = layerInfos.stateInfo; + } + animation = GetAnimation(clip); + float time = AnimationTime(stateInfo.normalizedTime, clip.length, + clip.isLooping, stateInfo.speed < 0); + return new KeyValuePair(animation, time); + } + + static float AnimationTime (float normalizedTime, float clipLength, bool loop, bool reversed) { + float time = AnimationTime(normalizedTime, clipLength, reversed); + if (loop) return time; + const float EndSnapEpsilon = 1f / 30f; // Workaround for end-duration keys not being applied. + return (clipLength - time < EndSnapEpsilon) ? clipLength : time; // return a time snapped to clipLength; + } + + static float AnimationTime (float normalizedTime, float clipLength, bool reversed) { + if (reversed) + normalizedTime = (1 - normalizedTime); + if (normalizedTime < 0.0f) + normalizedTime = (normalizedTime % 1.0f) + 1.0f; + return normalizedTime * clipLength; + } + + void InitClipInfosForLayers () { + if (layerClipInfos.Length < animator.layerCount) { + System.Array.Resize(ref layerClipInfos, animator.layerCount); + for (int layer = 0, n = animator.layerCount; layer < n; ++layer) { + if (layerClipInfos[layer] == null) + layerClipInfos[layer] = new ClipInfos(); + } + } + } + + void ClearClipInfosForLayers () { + for (int layer = 0, n = layerClipInfos.Length; layer < n; ++layer) { + if (layerClipInfos[layer] == null) + layerClipInfos[layer] = new ClipInfos(); + else { + layerClipInfos[layer].isInterruptionActive = false; + layerClipInfos[layer].isLastFrameOfInterruption = false; + layerClipInfos[layer].clipInfos.Clear(); + layerClipInfos[layer].nextClipInfos.Clear(); + layerClipInfos[layer].interruptingClipInfos.Clear(); + } + } + } + + private MixMode GetMixMode (int layer, MixBlend layerBlendMode) { + if (useCustomMixMode) { + MixMode mode = layerMixModes[layer]; + // Note: at additive blending it makes no sense to use constant weight 1 at a fadeout anim add1 as + // with override layers, so we use AlwaysMix instead to use the proper weights. + // AlwaysMix leads to the expected result = lower_layer + lerp(add1, add2, transition_weight). + if (layerBlendMode == MixBlend.Add && mode == MixMode.MixNext) { + mode = MixMode.AlwaysMix; + layerMixModes[layer] = mode; + } + return mode; + } + else { + return layerBlendMode == MixBlend.Add ? MixMode.AlwaysMix : MixMode.MixNext; + } + } + +#if UNITY_EDITOR + void GetLayerBlendModes() { + if (layerBlendModes.Length < animator.layerCount) { + System.Array.Resize(ref layerBlendModes, animator.layerCount); + } + for (int layer = 0, n = animator.layerCount; layer < n; ++layer) { + var controller = animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController; + if (controller != null) { + layerBlendModes[layer] = MixBlend.First; + if (layer > 0) { + layerBlendModes[layer] = controller.layers[layer].blendingMode == UnityEditor.Animations.AnimatorLayerBlendingMode.Additive ? + MixBlend.Add : MixBlend.Replace; + } + } + } + } + #endif + + void GetStateUpdatesFromAnimator (int layer) { + + var layerInfos = layerClipInfos[layer]; + int clipInfoCount = animator.GetCurrentAnimatorClipInfoCount(layer); + int nextClipInfoCount = animator.GetNextAnimatorClipInfoCount(layer); + + var clipInfos = layerInfos.clipInfos; + var nextClipInfos = layerInfos.nextClipInfos; + var interruptingClipInfos = layerInfos.interruptingClipInfos; + + layerInfos.isInterruptionActive = (clipInfoCount == 0 && clipInfos.Count != 0 && + nextClipInfoCount == 0 && nextClipInfos.Count != 0); + + // Note: during interruption, GetCurrentAnimatorClipInfoCount and GetNextAnimatorClipInfoCount + // are returning 0 in calls above. Therefore we keep previous clipInfos and nextClipInfos + // until the interruption is over. + if (layerInfos.isInterruptionActive) { + + // Note: The last frame of a transition interruption + // will have fullPathHash set to 0, therefore we have to use previous + // frame's infos about interruption clips and correct some values + // accordingly (normalizedTime and weight). + var interruptingStateInfo = animator.GetNextAnimatorStateInfo(layer); + layerInfos.isLastFrameOfInterruption = interruptingStateInfo.fullPathHash == 0; + if (!layerInfos.isLastFrameOfInterruption) { + animator.GetNextAnimatorClipInfo(layer, interruptingClipInfos); + layerInfos.interruptingClipInfoCount = interruptingClipInfos.Count; + float oldTime = layerInfos.interruptingStateInfo.normalizedTime; + float newTime = interruptingStateInfo.normalizedTime; + layerInfos.interruptingClipTimeAddition = newTime - oldTime; + layerInfos.interruptingStateInfo = interruptingStateInfo; + } + } else { + layerInfos.clipInfoCount = clipInfoCount; + layerInfos.nextClipInfoCount = nextClipInfoCount; + layerInfos.interruptingClipInfoCount = 0; + layerInfos.isLastFrameOfInterruption = false; + + if (clipInfos.Capacity < clipInfoCount) clipInfos.Capacity = clipInfoCount; + if (nextClipInfos.Capacity < nextClipInfoCount) nextClipInfos.Capacity = nextClipInfoCount; + + animator.GetCurrentAnimatorClipInfo(layer, clipInfos); + animator.GetNextAnimatorClipInfo(layer, nextClipInfos); + + layerInfos.stateInfo = animator.GetCurrentAnimatorStateInfo(layer); + layerInfos.nextStateInfo = animator.GetNextAnimatorStateInfo(layer); + } + } + + void GetAnimatorClipInfos ( + int layer, + out bool isInterruptionActive, + out int clipInfoCount, + out int nextClipInfoCount, + out int interruptingClipInfoCount, + out IList clipInfo, + out IList nextClipInfo, + out IList interruptingClipInfo, + out bool shallInterpolateWeightTo1) { + + var layerInfos = layerClipInfos[layer]; + isInterruptionActive = layerInfos.isInterruptionActive; + + clipInfoCount = layerInfos.clipInfoCount; + nextClipInfoCount = layerInfos.nextClipInfoCount; + interruptingClipInfoCount = layerInfos.interruptingClipInfoCount; + + clipInfo = layerInfos.clipInfos; + nextClipInfo = layerInfos.nextClipInfos; + interruptingClipInfo = isInterruptionActive ? layerInfos.interruptingClipInfos : null; + shallInterpolateWeightTo1 = layerInfos.isLastFrameOfInterruption; + } + + void GetAnimatorStateInfos ( + int layer, + out bool isInterruptionActive, + out AnimatorStateInfo stateInfo, + out AnimatorStateInfo nextStateInfo, + out AnimatorStateInfo interruptingStateInfo, + out float interruptingClipTimeAddition) { + + var layerInfos = layerClipInfos[layer]; + isInterruptionActive = layerInfos.isInterruptionActive; + + stateInfo = layerInfos.stateInfo; + nextStateInfo = layerInfos.nextStateInfo; + interruptingStateInfo = layerInfos.interruptingStateInfo; + interruptingClipTimeAddition = layerInfos.isLastFrameOfInterruption ? layerInfos.interruptingClipTimeAddition : 0; + } + + Spine.Animation GetAnimation (AnimationClip clip) { + int clipNameHashCode; + if (!clipNameHashCodeTable.TryGetValue(clip, out clipNameHashCode)) { + clipNameHashCode = clip.name.GetHashCode(); + clipNameHashCodeTable.Add(clip, clipNameHashCode); + } + Spine.Animation animation; + animationTable.TryGetValue(clipNameHashCode, out animation); + return animation; + } + + class AnimationClipEqualityComparer : IEqualityComparer { + internal static readonly IEqualityComparer Instance = new AnimationClipEqualityComparer(); + public bool Equals (AnimationClip x, AnimationClip y) { return x.GetInstanceID() == y.GetInstanceID(); } + public int GetHashCode (AnimationClip o) { return o.GetInstanceID(); } + } + + class IntEqualityComparer : IEqualityComparer { + internal static readonly IEqualityComparer Instance = new IntEqualityComparer(); + public bool Equals (int x, int y) { return x == y; } + public int GetHashCode(int o) { return o; } + } + } + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs.meta new file mode 100644 index 0000000..ebd50dc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonMecanim.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f9db98c60740638449864eb028fbe7ad +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator.meta new file mode 100644 index 0000000..72398a4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 3a361f5ac799a5149b340f9e20da27d1 +folderAsset: yes +timeCreated: 1457405502 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs new file mode 100644 index 0000000..cb3479a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs @@ -0,0 +1,151 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + [RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderSeparator")] + public class SkeletonPartsRenderer : MonoBehaviour { + + #region Properties + MeshGenerator meshGenerator; + public MeshGenerator MeshGenerator { + get { + LazyIntialize(); + return meshGenerator; + } + } + + MeshRenderer meshRenderer; + public MeshRenderer MeshRenderer { + get { + LazyIntialize(); + return meshRenderer; + } + } + + MeshFilter meshFilter; + public MeshFilter MeshFilter { + get { + LazyIntialize(); + return meshFilter; + } + } + #endregion + + #region Callback Delegates + public delegate void SkeletonPartsRendererDelegate (SkeletonPartsRenderer skeletonPartsRenderer); + + /// OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and + /// all materials have been updated. + public event SkeletonPartsRendererDelegate OnMeshAndMaterialsUpdated; + #endregion + + MeshRendererBuffers buffers; + SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); + + + void LazyIntialize () { + if (buffers == null) { + buffers = new MeshRendererBuffers(); + buffers.Initialize(); + + if (meshGenerator != null) return; + meshGenerator = new MeshGenerator(); + meshFilter = GetComponent(); + meshRenderer = GetComponent(); + currentInstructions.Clear(); + } + } + + public void ClearMesh () { + LazyIntialize(); + meshFilter.sharedMesh = null; + } + + public void RenderParts (ExposedList instructions, int startSubmesh, int endSubmesh) { + LazyIntialize(); + + // STEP 1: Create instruction + var smartMesh = buffers.GetNextMesh(); + currentInstructions.SetWithSubset(instructions, startSubmesh, endSubmesh); + bool updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, smartMesh.instructionUsed); + + // STEP 2: Generate mesh buffers. + var currentInstructionsSubmeshesItems = currentInstructions.submeshInstructions.Items; + meshGenerator.Begin(); + if (currentInstructions.hasActiveClipping) { + for (int i = 0; i < currentInstructions.submeshInstructions.Count; i++) + meshGenerator.AddSubmesh(currentInstructionsSubmeshesItems[i], updateTriangles); + } else { + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + buffers.UpdateSharedMaterials(currentInstructions.submeshInstructions); + + // STEP 3: modify mesh. + var mesh = smartMesh.mesh; + + if (meshGenerator.VertexCount <= 0) { // Clear an empty mesh + updateTriangles = false; + mesh.Clear(); + } else { + meshGenerator.FillVertexData(mesh); + if (updateTriangles) { + meshGenerator.FillTriangles(mesh); + meshRenderer.sharedMaterials = buffers.GetUpdatedSharedMaterialsArray(); + } else if (buffers.MaterialsChangedInLastUpdate()) { + meshRenderer.sharedMaterials = buffers.GetUpdatedSharedMaterialsArray(); + } + meshGenerator.FillLateVertexData(mesh); + } + + meshFilter.sharedMesh = mesh; + smartMesh.instructionUsed.Set(currentInstructions); + + if (OnMeshAndMaterialsUpdated != null) + OnMeshAndMaterialsUpdated(this); + } + + public void SetPropertyBlock (MaterialPropertyBlock block) { + LazyIntialize(); + meshRenderer.SetPropertyBlock(block); + } + + public static SkeletonPartsRenderer NewPartsRendererGameObject (Transform parent, string name, int sortingOrder = 0) { + var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer)); + go.transform.SetParent(parent, false); + var returnComponent = go.AddComponent(); + returnComponent.MeshRenderer.sortingOrder = sortingOrder; + + return returnComponent; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs.meta new file mode 100644 index 0000000..9359388 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonPartsRenderer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1c0b968d1e7333b499e347acb644f1c1 +timeCreated: 1458045480 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs new file mode 100644 index 0000000..d2d187e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs @@ -0,0 +1,269 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif +#define SPINE_OPTIONAL_RENDEROVERRIDE + +using UnityEngine; +using System.Collections.Generic; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderSeparator")] + public class SkeletonRenderSeparator : MonoBehaviour { + public const int DefaultSortingOrderIncrement = 5; + + #region Inspector + [SerializeField] + protected SkeletonRenderer skeletonRenderer; + public SkeletonRenderer SkeletonRenderer { + get { return skeletonRenderer; } + set { + #if SPINE_OPTIONAL_RENDEROVERRIDE + if (skeletonRenderer != null) + skeletonRenderer.GenerateMeshOverride -= HandleRender; + #endif + + skeletonRenderer = value; + if (value == null) + this.enabled = false; + } + } + + MeshRenderer mainMeshRenderer; + public bool copyPropertyBlock = true; + [Tooltip("Copies MeshRenderer flags into each parts renderer")] + public bool copyMeshRendererFlags = true; + public List partsRenderers = new List(); + + #if UNITY_EDITOR + void Reset () { + if (skeletonRenderer == null) + skeletonRenderer = GetComponent(); + } + #endif + #endregion + + #region Callback Delegates + /// OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and + /// all materials have been updated. + public event SkeletonRenderer.SkeletonRendererDelegate OnMeshAndMaterialsUpdated; + #endregion + + #region Runtime Instantiation + /// Adds a SkeletonRenderSeparator and child SkeletonPartsRenderer GameObjects to a given SkeletonRenderer. + /// The to skeleton renderer. + /// The target SkeletonRenderer or SkeletonAnimation. + /// Sorting layer to be used for the parts renderers. + /// Number of additional SkeletonPartsRenderers on top of the ones determined by counting the number of separator slots. + /// The integer to increment the sorting order per SkeletonPartsRenderer to separate them. + /// The sorting order value of the first SkeletonPartsRenderer. + /// If set to true, a minimum number of SkeletonPartsRenderer GameObjects (determined by separatorSlots.Count + 1) will be added. + public static SkeletonRenderSeparator AddToSkeletonRenderer (SkeletonRenderer skeletonRenderer, int sortingLayerID = 0, int extraPartsRenderers = 0, int sortingOrderIncrement = DefaultSortingOrderIncrement, int baseSortingOrder = 0, bool addMinimumPartsRenderers = true) { + if (skeletonRenderer == null) { + Debug.Log("Tried to add SkeletonRenderSeparator to a null SkeletonRenderer reference."); + return null; + } + + var srs = skeletonRenderer.gameObject.AddComponent(); + srs.skeletonRenderer = skeletonRenderer; + + skeletonRenderer.Initialize(false); + int count = extraPartsRenderers; + if (addMinimumPartsRenderers) + count = extraPartsRenderers + skeletonRenderer.separatorSlots.Count + 1; + + var skeletonRendererTransform = skeletonRenderer.transform; + var componentRenderers = srs.partsRenderers; + + for (int i = 0; i < count; i++) { + var spr = SkeletonPartsRenderer.NewPartsRendererGameObject(skeletonRendererTransform, i.ToString()); + var mr = spr.MeshRenderer; + mr.sortingLayerID = sortingLayerID; + mr.sortingOrder = baseSortingOrder + (i * sortingOrderIncrement); + componentRenderers.Add(spr); + } + + srs.OnEnable(); + + #if UNITY_EDITOR + // Make sure editor updates properly in edit mode. + if (!Application.isPlaying) { + skeletonRenderer.enabled = false; + skeletonRenderer.enabled = true; + skeletonRenderer.LateUpdate(); + } + #endif + + return srs; + } + + /// Add a child SkeletonPartsRenderer GameObject to this SkeletonRenderSeparator. + public SkeletonPartsRenderer AddPartsRenderer (int sortingOrderIncrement = DefaultSortingOrderIncrement, string name = null) { + int sortingLayerID = 0; + int sortingOrder = 0; + if (partsRenderers.Count > 0) { + var previous = partsRenderers[partsRenderers.Count - 1]; + var previousMeshRenderer = previous.MeshRenderer; + sortingLayerID = previousMeshRenderer.sortingLayerID; + sortingOrder = previousMeshRenderer.sortingOrder + sortingOrderIncrement; + } + + if (string.IsNullOrEmpty(name)) + name = partsRenderers.Count.ToString(); + + var spr = SkeletonPartsRenderer.NewPartsRendererGameObject(skeletonRenderer.transform, name); + partsRenderers.Add(spr); + + var mr = spr.MeshRenderer; + mr.sortingLayerID = sortingLayerID; + mr.sortingOrder = sortingOrder; + + return spr; + } + #endregion + + public void OnEnable () { + if (skeletonRenderer == null) return; + if (copiedBlock == null) copiedBlock = new MaterialPropertyBlock(); + mainMeshRenderer = skeletonRenderer.GetComponent(); + + #if SPINE_OPTIONAL_RENDEROVERRIDE + skeletonRenderer.GenerateMeshOverride -= HandleRender; + skeletonRenderer.GenerateMeshOverride += HandleRender; + #endif + + if (copyMeshRendererFlags) { + var lightProbeUsage = mainMeshRenderer.lightProbeUsage; + bool receiveShadows = mainMeshRenderer.receiveShadows; + var reflectionProbeUsage = mainMeshRenderer.reflectionProbeUsage; + var shadowCastingMode = mainMeshRenderer.shadowCastingMode; + var motionVectorGenerationMode = mainMeshRenderer.motionVectorGenerationMode; + var probeAnchor = mainMeshRenderer.probeAnchor; + + for (int i = 0; i < partsRenderers.Count; i++) { + var currentRenderer = partsRenderers[i]; + if (currentRenderer == null) continue; // skip null items. + + var mr = currentRenderer.MeshRenderer; + mr.lightProbeUsage = lightProbeUsage; + mr.receiveShadows = receiveShadows; + mr.reflectionProbeUsage = reflectionProbeUsage; + mr.shadowCastingMode = shadowCastingMode; + mr.motionVectorGenerationMode = motionVectorGenerationMode; + mr.probeAnchor = probeAnchor; + } + } + } + + public void OnDisable () { + if (skeletonRenderer == null) return; + #if SPINE_OPTIONAL_RENDEROVERRIDE + skeletonRenderer.GenerateMeshOverride -= HandleRender; + #endif + + skeletonRenderer.LateUpdate(); + + foreach (var partsRenderer in partsRenderers) { + if (partsRenderer != null) + partsRenderer.ClearMesh(); + } + } + + MaterialPropertyBlock copiedBlock; + + void HandleRender (SkeletonRendererInstruction instruction) { + int rendererCount = partsRenderers.Count; + if (rendererCount <= 0) return; + + if (copyPropertyBlock) + mainMeshRenderer.GetPropertyBlock(copiedBlock); + + var settings = new MeshGenerator.Settings { + addNormals = skeletonRenderer.addNormals, + calculateTangents = skeletonRenderer.calculateTangents, + immutableTriangles = false, // parts cannot do immutable triangles. + pmaVertexColors = skeletonRenderer.pmaVertexColors, + tintBlack = skeletonRenderer.tintBlack, + useClipping = true, + zSpacing = skeletonRenderer.zSpacing + }; + + var submeshInstructions = instruction.submeshInstructions; + var submeshInstructionsItems = submeshInstructions.Items; + int lastSubmeshInstruction = submeshInstructions.Count - 1; + + int rendererIndex = 0; + var currentRenderer = partsRenderers[rendererIndex]; + for (int si = 0, start = 0; si <= lastSubmeshInstruction; si++) { + if (currentRenderer == null) + continue; + if (submeshInstructionsItems[si].forceSeparate || si == lastSubmeshInstruction) { + // Apply properties + var meshGenerator = currentRenderer.MeshGenerator; + meshGenerator.settings = settings; + + if (copyPropertyBlock) + currentRenderer.SetPropertyBlock(copiedBlock); + + // Render + currentRenderer.RenderParts(instruction.submeshInstructions, start, si + 1); + + start = si + 1; + rendererIndex++; + if (rendererIndex < rendererCount) { + currentRenderer = partsRenderers[rendererIndex]; + } else { + // Not enough renderers. Skip the rest of the instructions. + break; + } + } + } + + if (OnMeshAndMaterialsUpdated != null) + OnMeshAndMaterialsUpdated(this.skeletonRenderer); + + // Clear extra renderers if they exist. + for (; rendererIndex < rendererCount; rendererIndex++) { + currentRenderer = partsRenderers[rendererIndex]; + if (currentRenderer != null) + partsRenderers[rendererIndex].ClearMesh(); + } + + } + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs.meta new file mode 100644 index 0000000..0c344f7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5c70a5b35f6ff2541aed8e8346b7e4d5 +timeCreated: 1457405791 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt new file mode 100644 index 0000000..c42f929 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt @@ -0,0 +1,6 @@ +SkeletonRenderSeparator +======================= + +Dependencies: +- SkeletonPartsRenderer uses the `ArraysMeshGenerator` class in `Spine.Unity.MeshGeneration` +- It requires `SPINE_OPTIONAL_RENDEROVERRIDE` to be #defined in `SkeletonRenderer.cs`. diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt.meta new file mode 100644 index 0000000..5dd3c99 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderSeparator/SkeletonRenderSeparator.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f0e413eeb00eabc46bde6dbd7aaaa76c +timeCreated: 1469110129 +licenseType: Free +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs new file mode 100644 index 0000000..a40a510 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs @@ -0,0 +1,711 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +#if UNITY_2018_1_OR_NEWER +#define PER_MATERIAL_PROPERTY_BLOCKS +#endif + +#if UNITY_2017_1_OR_NEWER +#define BUILT_IN_SPRITE_MASK_COMPONENT +#endif + +#if UNITY_2019_3_OR_NEWER +#define CONFIGURABLE_ENTER_PLAY_MODE +#endif + +#define SPINE_OPTIONAL_RENDEROVERRIDE +#define SPINE_OPTIONAL_MATERIALOVERRIDE + +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + /// Base class of animated Spine skeleton components. This component manages and renders a skeleton. + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer)), DisallowMultipleComponent] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRenderer-Component")] + public class SkeletonRenderer : MonoBehaviour, ISkeletonComponent, IHasSkeletonDataAsset { + public SkeletonDataAsset skeletonDataAsset; + + #region Initialization settings + /// Skin name to use when the Skeleton is initialized. + [SpineSkin(defaultAsEmptyString:true)] public string initialSkinName; + + /// Enable this parameter when overwriting the Skeleton's skin from an editor script. + /// Otherwise any changes will be overwritten by the next inspector update. + #if UNITY_EDITOR + public bool EditorSkipSkinSync { + get { return editorSkipSkinSync; } + set { editorSkipSkinSync = value; } + } + protected bool editorSkipSkinSync = false; + #endif + /// Flip X and Y to use when the Skeleton is initialized. + public bool initialFlipX, initialFlipY; + #endregion + + #region Advanced Render Settings + + /// Update mode to optionally limit updates to e.g. only apply animations but not update the mesh. + public UpdateMode UpdateMode { get { return updateMode; } set { updateMode = value; } } + protected UpdateMode updateMode = UpdateMode.FullUpdate; + + /// Update mode used when the MeshRenderer becomes invisible + /// (when OnBecameInvisible() is called). Update mode is automatically + /// reset to UpdateMode.FullUpdate when the mesh becomes visible again. + public UpdateMode updateWhenInvisible = UpdateMode.FullUpdate; + + // Submesh Separation + /// Slot names used to populate separatorSlots list when the Skeleton is initialized. Changing this after initialization does nothing. + [UnityEngine.Serialization.FormerlySerializedAs("submeshSeparators")][SerializeField][SpineSlot] protected string[] separatorSlotNames = new string[0]; + + /// Slots that determine where the render is split. This is used by components such as SkeletonRenderSeparator so that the skeleton can be rendered by two separate renderers on different GameObjects. + [System.NonSerialized] public readonly List separatorSlots = new List(); + + // Render Settings + [Range(-0.1f, 0f)] public float zSpacing; + /// Use Spine's clipping feature. If false, ClippingAttachments will be ignored. + public bool useClipping = true; + + /// If true, triangles will not be updated. Enable this as an optimization if the skeleton does not make use of attachment swapping or hiding, or draw order keys. Otherwise, setting this to false may cause errors in rendering. + public bool immutableTriangles = false; + + /// Multiply vertex color RGB with vertex color alpha. Set this to true if the shader used for rendering is a premultiplied alpha shader. Setting this to false disables single-batch additive slots. + public bool pmaVertexColors = true; + + /// Clears the state of the render and skeleton when this component or its GameObject is disabled. This prevents previous state from being retained when it is enabled again. When pooling your skeleton, setting this to true can be helpful. + public bool clearStateOnDisable = false; + + /// If true, second colors on slots will be added to the output Mesh as UV2 and UV3. A special "tint black" shader that interprets UV2 and UV3 as black point colors is required to render this properly. + public bool tintBlack = false; + + /// If true, the renderer assumes the skeleton only requires one Material and one submesh to render. This allows the MeshGenerator to skip checking for changes in Materials. Enable this as an optimization if the skeleton only uses one Material. + /// This disables SkeletonRenderSeparator functionality. + public bool singleSubmesh = false; + + #if PER_MATERIAL_PROPERTY_BLOCKS + /// Applies only when 3+ submeshes are used (2+ materials with alternating order, e.g. "A B A"). + /// If true, GPU instancing is disabled at all materials and MaterialPropertyBlocks are assigned at each + /// material to prevent aggressive batching of submeshes by e.g. the LWRP renderer, leading to incorrect + /// draw order (e.g. "A1 B A2" changed to "A1A2 B"). + /// You can disable this parameter when everything is drawn correctly to save the additional performance cost. + /// + public bool fixDrawOrder = false; + #endif + + /// If true, the mesh generator adds normals to the output mesh. For better performance and reduced memory requirements, use a shader that assumes the desired normal. + [UnityEngine.Serialization.FormerlySerializedAs("calculateNormals")] public bool addNormals = false; + + /// If true, tangents are calculated every frame and added to the Mesh. Enable this when using a shader that uses lighting that requires tangents. + public bool calculateTangents = false; + + #if BUILT_IN_SPRITE_MASK_COMPONENT + /// This enum controls the mode under which the sprite will interact with the masking system. + /// Interaction modes with components are identical to Unity's , + /// see https://docs.unity3d.com/ScriptReference/SpriteMaskInteraction.html. + public SpriteMaskInteraction maskInteraction = SpriteMaskInteraction.None; + + [System.Serializable] + public class SpriteMaskInteractionMaterials { + public bool AnyMaterialCreated { + get { + return materialsMaskDisabled.Length > 0 || + materialsInsideMask.Length > 0 || + materialsOutsideMask.Length > 0; + } + } + + /// Material references for switching material sets at runtime when changes to . + public Material[] materialsMaskDisabled = new Material[0]; + /// Material references for switching material sets at runtime when changes to . + public Material[] materialsInsideMask = new Material[0]; + /// Material references for switching material sets at runtime when changes to . + public Material[] materialsOutsideMask = new Material[0]; + } + /// Material references for switching material sets at runtime when changes. + public SpriteMaskInteractionMaterials maskMaterials = new SpriteMaskInteractionMaterials(); + + /// Shader property ID used for the Stencil comparison function. + public static readonly int STENCIL_COMP_PARAM_ID = Shader.PropertyToID("_StencilComp"); + /// Shader property value used as Stencil comparison function for . + public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_NONE = UnityEngine.Rendering.CompareFunction.Always; + /// Shader property value used as Stencil comparison function for . + public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE = UnityEngine.Rendering.CompareFunction.LessEqual; + /// Shader property value used as Stencil comparison function for . + public const UnityEngine.Rendering.CompareFunction STENCIL_COMP_MASKINTERACTION_VISIBLE_OUTSIDE = UnityEngine.Rendering.CompareFunction.Greater; + #if UNITY_EDITOR + private static bool haveStencilParametersBeenFixed = false; + #endif + #endif // #if BUILT_IN_SPRITE_MASK_COMPONENT + #endregion + + #region Overrides + #if SPINE_OPTIONAL_RENDEROVERRIDE + // These are API for anything that wants to take over rendering for a SkeletonRenderer. + public bool disableRenderingOnOverride = true; + public delegate void InstructionDelegate (SkeletonRendererInstruction instruction); + event InstructionDelegate generateMeshOverride; + + /// Allows separate code to take over rendering for this SkeletonRenderer component. The subscriber is passed a SkeletonRendererInstruction argument to determine how to render a skeleton. + public event InstructionDelegate GenerateMeshOverride { + add { + generateMeshOverride += value; + if (disableRenderingOnOverride && generateMeshOverride != null) { + Initialize(false); + if (meshRenderer) + meshRenderer.enabled = false; + } + } + remove { + generateMeshOverride -= value; + if (disableRenderingOnOverride && generateMeshOverride == null) { + Initialize(false); + if (meshRenderer) + meshRenderer.enabled = true; + } + } + } + + /// Occurs after the vertex data is populated every frame, before the vertices are pushed into the mesh. + public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; + #endif + + #if SPINE_OPTIONAL_MATERIALOVERRIDE + [System.NonSerialized] readonly Dictionary customMaterialOverride = new Dictionary(); + /// Use this Dictionary to override a Material with a different Material. + public Dictionary CustomMaterialOverride { get { return customMaterialOverride; } } + #endif + + [System.NonSerialized] readonly Dictionary customSlotMaterials = new Dictionary(); + /// Use this Dictionary to use a different Material to render specific Slots. + public Dictionary CustomSlotMaterials { get { return customSlotMaterials; } } + #endregion + + #region Mesh Generator + [System.NonSerialized] readonly SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); + readonly MeshGenerator meshGenerator = new MeshGenerator(); + [System.NonSerialized] readonly MeshRendererBuffers rendererBuffers = new MeshRendererBuffers(); + #endregion + + #region Cached component references + MeshRenderer meshRenderer; + MeshFilter meshFilter; + #endregion + + #region Skeleton + [System.NonSerialized] public bool valid; + [System.NonSerialized] public Skeleton skeleton; + public Skeleton Skeleton { + get { + Initialize(false); + return skeleton; + } + } + #endregion + + public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); + + /// OnRebuild is raised after the Skeleton is successfully initialized. + public event SkeletonRendererDelegate OnRebuild; + + /// OnMeshAndMaterialsUpdated is called at the end of LateUpdate after the Mesh and + /// all materials have been updated. + public event SkeletonRendererDelegate OnMeshAndMaterialsUpdated; + + public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } // ISkeletonComponent + + #region Runtime Instantiation + public static T NewSpineGameObject (SkeletonDataAsset skeletonDataAsset, bool quiet = false) where T : SkeletonRenderer { + return SkeletonRenderer.AddSpineComponent(new GameObject("New Spine GameObject"), skeletonDataAsset, quiet); + } + + /// Add and prepare a Spine component that derives from SkeletonRenderer to a GameObject at runtime. + /// T should be SkeletonRenderer or any of its derived classes. + public static T AddSpineComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, bool quiet = false) where T : SkeletonRenderer { + var c = gameObject.AddComponent(); + if (skeletonDataAsset != null) { + c.skeletonDataAsset = skeletonDataAsset; + c.Initialize(false, quiet); + } + return c; + } + + /// Applies MeshGenerator settings to the SkeletonRenderer and its internal MeshGenerator. + public void SetMeshSettings (MeshGenerator.Settings settings) { + this.calculateTangents = settings.calculateTangents; + this.immutableTriangles = settings.immutableTriangles; + this.pmaVertexColors = settings.pmaVertexColors; + this.tintBlack = settings.tintBlack; + this.useClipping = settings.useClipping; + this.zSpacing = settings.zSpacing; + + this.meshGenerator.settings = settings; + } + #endregion + + + public virtual void Awake () { + Initialize(false); + updateMode = updateWhenInvisible; + } + + #if UNITY_EDITOR && CONFIGURABLE_ENTER_PLAY_MODE + public virtual void Start () { + Initialize(false); + } + #endif + + void OnDisable () { + if (clearStateOnDisable && valid) + ClearState(); + } + + void OnDestroy () { + rendererBuffers.Dispose(); + valid = false; + } + + /// + /// Clears the previously generated mesh and resets the skeleton's pose. + public virtual void ClearState () { + var meshFilter = GetComponent(); + if (meshFilter != null) meshFilter.sharedMesh = null; + currentInstructions.Clear(); + if (skeleton != null) skeleton.SetToSetupPose(); + } + + /// + /// Sets a minimum buffer size for the internal MeshGenerator to prevent excess allocations during animation. + /// + public void EnsureMeshGeneratorCapacity (int minimumVertexCount) { + meshGenerator.EnsureVertexCapacity(minimumVertexCount); + } + + /// + /// Initialize this component. Attempts to load the SkeletonData and creates the internal Skeleton object and buffers. + /// If set to true, it will overwrite internal objects if they were already generated. Otherwise, the initialized component will ignore subsequent calls to initialize. + public virtual void Initialize (bool overwrite, bool quiet = false) { + if (valid && !overwrite) + return; + + // Clear + { + // Note: do not reset meshFilter.sharedMesh or meshRenderer.sharedMaterial to null, + // otherwise constant reloading will be triggered at prefabs. + currentInstructions.Clear(); + rendererBuffers.Clear(); + meshGenerator.Begin(); + skeleton = null; + valid = false; + } + + if (skeletonDataAsset == null) + return; + + SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); + if (skeletonData == null) return; + valid = true; + + meshFilter = GetComponent(); + meshRenderer = GetComponent(); + rendererBuffers.Initialize(); + + skeleton = new Skeleton(skeletonData) { + ScaleX = initialFlipX ? -1 : 1, + ScaleY = initialFlipY ? -1 : 1 + }; + + if (!string.IsNullOrEmpty(initialSkinName) && !string.Equals(initialSkinName, "default", System.StringComparison.Ordinal)) + skeleton.SetSkin(initialSkinName); + + separatorSlots.Clear(); + for (int i = 0; i < separatorSlotNames.Length; i++) + separatorSlots.Add(skeleton.FindSlot(separatorSlotNames[i])); + + LateUpdate(); // Generate mesh for the first frame it exists. + + if (OnRebuild != null) + OnRebuild(this); + + #if UNITY_EDITOR + if (!Application.isPlaying) { + string errorMessage = null; + if (!quiet && MaterialChecks.IsMaterialSetupProblematic(this, ref errorMessage)) + Debug.LogWarningFormat(this, "Problematic material setup at {0}: {1}", this.name, errorMessage); + } + #endif + } + + /// + /// Generates a new UnityEngine.Mesh from the internal Skeleton. + public virtual void LateUpdate () { + if (!valid) return; + + #if UNITY_EDITOR && NEW_PREFAB_SYSTEM + // Don't store mesh or material at the prefab, otherwise it will permanently reload + var prefabType = UnityEditor.PrefabUtility.GetPrefabAssetType(this); + if (UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) && + (prefabType == UnityEditor.PrefabAssetType.Regular || prefabType == UnityEditor.PrefabAssetType.Variant)) { + return; + } + #endif + + if (updateMode != UpdateMode.FullUpdate) return; + + #if SPINE_OPTIONAL_RENDEROVERRIDE + bool doMeshOverride = generateMeshOverride != null; + if ((!meshRenderer.enabled) && !doMeshOverride) return; + #else + const bool doMeshOverride = false; + if (!meshRenderer.enabled) return; + #endif + var currentInstructions = this.currentInstructions; + var workingSubmeshInstructions = currentInstructions.submeshInstructions; + var currentSmartMesh = rendererBuffers.GetNextMesh(); // Double-buffer for performance. + + bool updateTriangles; + + if (this.singleSubmesh) { + // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= + MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, skeletonDataAsset.atlasAssets[0].PrimaryMaterial); + + // STEP 1.9. Post-process workingInstructions. ================================================================================== + #if SPINE_OPTIONAL_MATERIALOVERRIDE + if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated + MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); + #endif + + // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== + meshGenerator.settings = new MeshGenerator.Settings { + pmaVertexColors = this.pmaVertexColors, + zSpacing = this.zSpacing, + useClipping = this.useClipping, + tintBlack = this.tintBlack, + calculateTangents = this.calculateTangents, + addNormals = this.addNormals + }; + meshGenerator.Begin(); + updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); + if (currentInstructions.hasActiveClipping) { + meshGenerator.AddSubmesh(workingSubmeshInstructions.Items[0], updateTriangles); + } else { + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + } else { + // STEP 1. Determine a SmartMesh.Instruction. Split up instructions into submeshes. ============================================= + MeshGenerator.GenerateSkeletonRendererInstruction(currentInstructions, skeleton, customSlotMaterials, separatorSlots, doMeshOverride, this.immutableTriangles); + + // STEP 1.9. Post-process workingInstructions. ================================================================================== +#if SPINE_OPTIONAL_MATERIALOVERRIDE + if (customMaterialOverride.Count > 0) // isCustomMaterialOverridePopulated + MeshGenerator.TryReplaceMaterials(workingSubmeshInstructions, customMaterialOverride); +#endif + +#if SPINE_OPTIONAL_RENDEROVERRIDE + if (doMeshOverride) { + this.generateMeshOverride(currentInstructions); + if (disableRenderingOnOverride) return; + } +#endif + + updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, currentSmartMesh.instructionUsed); + + // STEP 2. Update vertex buffer based on verts from the attachments. =========================================================== + meshGenerator.settings = new MeshGenerator.Settings { + pmaVertexColors = this.pmaVertexColors, + zSpacing = this.zSpacing, + useClipping = this.useClipping, + tintBlack = this.tintBlack, + calculateTangents = this.calculateTangents, + addNormals = this.addNormals + }; + meshGenerator.Begin(); + if (currentInstructions.hasActiveClipping) + meshGenerator.BuildMesh(currentInstructions, updateTriangles); + else + meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); + } + + if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); + + // STEP 3. Move the mesh data into a UnityEngine.Mesh =========================================================================== + var currentMesh = currentSmartMesh.mesh; + meshGenerator.FillVertexData(currentMesh); + + rendererBuffers.UpdateSharedMaterials(workingSubmeshInstructions); + + bool materialsChanged = rendererBuffers.MaterialsChangedInLastUpdate(); + if (updateTriangles) { // Check if the triangles should also be updated. + meshGenerator.FillTriangles(currentMesh); + meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); + } else if (materialsChanged) { + meshRenderer.sharedMaterials = rendererBuffers.GetUpdatedSharedMaterialsArray(); + } + if (materialsChanged && (this.maskMaterials.AnyMaterialCreated)) { + this.maskMaterials = new SpriteMaskInteractionMaterials(); + } + + meshGenerator.FillLateVertexData(currentMesh); + + // STEP 4. The UnityEngine.Mesh is ready. Set it as the MeshFilter's mesh. Store the instructions used for that mesh. =========== + meshFilter.sharedMesh = currentMesh; + currentSmartMesh.instructionUsed.Set(currentInstructions); + + #if BUILT_IN_SPRITE_MASK_COMPONENT + if (meshRenderer != null) { + AssignSpriteMaskMaterials(); + } + #endif + + #if PER_MATERIAL_PROPERTY_BLOCKS + if (fixDrawOrder && meshRenderer.sharedMaterials.Length > 2) { + SetMaterialSettingsToFixDrawOrder(); + } + #endif + + if (OnMeshAndMaterialsUpdated != null) + OnMeshAndMaterialsUpdated(this); + } + + public void OnBecameVisible () { + UpdateMode previousUpdateMode = updateMode; + updateMode = UpdateMode.FullUpdate; + if (previousUpdateMode != UpdateMode.FullUpdate) + LateUpdate(); // OnBecameVisible is called after LateUpdate() + } + + public void OnBecameInvisible () { + updateMode = updateWhenInvisible; + } + + public void FindAndApplySeparatorSlots (string startsWith, bool clearExistingSeparators = true, bool updateStringArray = false) { + if (string.IsNullOrEmpty(startsWith)) return; + + FindAndApplySeparatorSlots( + (slotName) => slotName.StartsWith(startsWith), + clearExistingSeparators, + updateStringArray + ); + } + + public void FindAndApplySeparatorSlots (System.Func slotNamePredicate, bool clearExistingSeparators = true, bool updateStringArray = false) { + if (slotNamePredicate == null) return; + if (!valid) return; + + if (clearExistingSeparators) + separatorSlots.Clear(); + + var slots = skeleton.slots; + foreach (var slot in slots) { + if (slotNamePredicate.Invoke(slot.data.name)) + separatorSlots.Add(slot); + } + + if (updateStringArray) { + var detectedSeparatorNames = new List(); + foreach (var slot in skeleton.slots) { + string slotName = slot.data.name; + if (slotNamePredicate.Invoke(slotName)) + detectedSeparatorNames.Add(slotName); + } + if (!clearExistingSeparators) { + string[] originalNames = this.separatorSlotNames; + foreach (string originalName in originalNames) + detectedSeparatorNames.Add(originalName); + } + + this.separatorSlotNames = detectedSeparatorNames.ToArray(); + } + + } + + public void ReapplySeparatorSlotNames () { + if (!valid) + return; + + separatorSlots.Clear(); + for (int i = 0, n = separatorSlotNames.Length; i < n; i++) { + var slot = skeleton.FindSlot(separatorSlotNames[i]); + if (slot != null) { + separatorSlots.Add(slot); + } + #if UNITY_EDITOR + else if (!string.IsNullOrEmpty(separatorSlotNames[i])) + { + Debug.LogWarning(separatorSlotNames[i] + " is not a slot in " + skeletonDataAsset.skeletonJSON.name); + } + #endif + } + } + + #if BUILT_IN_SPRITE_MASK_COMPONENT + private void AssignSpriteMaskMaterials() + { + #if UNITY_EDITOR + if (!Application.isPlaying && !UnityEditor.EditorApplication.isUpdating) { + EditorFixStencilCompParameters(); + } + #endif + + if (Application.isPlaying) { + if (maskInteraction != SpriteMaskInteraction.None && maskMaterials.materialsMaskDisabled.Length == 0) + maskMaterials.materialsMaskDisabled = meshRenderer.sharedMaterials; + } + + if (maskMaterials.materialsMaskDisabled.Length > 0 && maskMaterials.materialsMaskDisabled[0] != null && + maskInteraction == SpriteMaskInteraction.None) { + this.meshRenderer.materials = maskMaterials.materialsMaskDisabled; + } + else if (maskInteraction == SpriteMaskInteraction.VisibleInsideMask) { + if (maskMaterials.materialsInsideMask.Length == 0 || maskMaterials.materialsInsideMask[0] == null) { + if (!InitSpriteMaskMaterialsInsideMask()) + return; + } + this.meshRenderer.materials = maskMaterials.materialsInsideMask; + } + else if (maskInteraction == SpriteMaskInteraction.VisibleOutsideMask) { + if (maskMaterials.materialsOutsideMask.Length == 0 || maskMaterials.materialsOutsideMask[0] == null) { + if (!InitSpriteMaskMaterialsOutsideMask()) + return; + } + this.meshRenderer.materials = maskMaterials.materialsOutsideMask; + } + } + + private bool InitSpriteMaskMaterialsInsideMask() + { + return InitSpriteMaskMaterialsForMaskType(STENCIL_COMP_MASKINTERACTION_VISIBLE_INSIDE, ref maskMaterials.materialsInsideMask); + } + + private bool InitSpriteMaskMaterialsOutsideMask() + { + return InitSpriteMaskMaterialsForMaskType(STENCIL_COMP_MASKINTERACTION_VISIBLE_OUTSIDE, ref maskMaterials.materialsOutsideMask); + } + + private bool InitSpriteMaskMaterialsForMaskType(UnityEngine.Rendering.CompareFunction maskFunction, ref Material[] materialsToFill) + { + #if UNITY_EDITOR + if (!Application.isPlaying) { + return false; + } + #endif + + var originalMaterials = maskMaterials.materialsMaskDisabled; + materialsToFill = new Material[originalMaterials.Length]; + for (int i = 0; i < originalMaterials.Length; i++) { + Material newMaterial = new Material(originalMaterials[i]); + newMaterial.SetFloat(STENCIL_COMP_PARAM_ID, (int)maskFunction); + materialsToFill[i] = newMaterial; + } + return true; + } + + #if UNITY_EDITOR + private void EditorFixStencilCompParameters() { + if (!haveStencilParametersBeenFixed && HasAnyStencilComp0Material()) { + haveStencilParametersBeenFixed = true; + FixAllProjectMaterialsStencilCompParameters(); + } + } + + private void FixAllProjectMaterialsStencilCompParameters() { + string[] materialGUIDS = UnityEditor.AssetDatabase.FindAssets("t:material"); + foreach (var guid in materialGUIDS) { + string path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(path)) { + var mat = UnityEditor.AssetDatabase.LoadAssetAtPath(path); + if (mat.HasProperty(STENCIL_COMP_PARAM_ID) && mat.GetFloat(STENCIL_COMP_PARAM_ID) == 0) { + mat.SetFloat(STENCIL_COMP_PARAM_ID, (int)STENCIL_COMP_MASKINTERACTION_NONE); + } + } + } + UnityEditor.AssetDatabase.Refresh(); + UnityEditor.AssetDatabase.SaveAssets(); + } + + private bool HasAnyStencilComp0Material() { + if (meshRenderer == null) + return false; + + foreach (var mat in meshRenderer.sharedMaterials) { + if (mat != null && mat.HasProperty(STENCIL_COMP_PARAM_ID)) { + float currentCompValue = mat.GetFloat(STENCIL_COMP_PARAM_ID); + if (currentCompValue == 0) + return true; + } + } + return false; + } + #endif // UNITY_EDITOR + + #endif //#if BUILT_IN_SPRITE_MASK_COMPONENT + + #if PER_MATERIAL_PROPERTY_BLOCKS + private MaterialPropertyBlock reusedPropertyBlock; + public static readonly int SUBMESH_DUMMY_PARAM_ID = Shader.PropertyToID("_Submesh"); + + /// + /// This method was introduced as a workaround for too aggressive submesh draw call batching, + /// leading to incorrect draw order when 3+ materials are used at submeshes in alternating order. + /// Otherwise, e.g. when using Lightweight Render Pipeline, deliberately separated draw calls + /// "A1 B A2" are reordered to "A1A2 B", regardless of batching-related project settings. + /// + private void SetMaterialSettingsToFixDrawOrder() { + if (reusedPropertyBlock == null) reusedPropertyBlock = new MaterialPropertyBlock(); + + bool hasPerRendererBlock = meshRenderer.HasPropertyBlock(); + if (hasPerRendererBlock) { + meshRenderer.GetPropertyBlock(reusedPropertyBlock); + } + + for (int i = 0; i < meshRenderer.sharedMaterials.Length; ++i) { + if (!meshRenderer.sharedMaterials[i]) + continue; + + if (!hasPerRendererBlock) meshRenderer.GetPropertyBlock(reusedPropertyBlock, i); + // Note: this parameter shall not exist at any shader, then Unity will create separate + // material instances (not in terms of memory cost or leakage). + reusedPropertyBlock.SetFloat(SUBMESH_DUMMY_PARAM_ID, i); + meshRenderer.SetPropertyBlock(reusedPropertyBlock, i); + + meshRenderer.sharedMaterials[i].enableInstancing = false; + } + } + #endif + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs.meta new file mode 100644 index 0000000..5230098 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRenderer.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e075b9a3e08e2f74fbd651c858ab16ed +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials.meta new file mode 100644 index 0000000..16b542c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a7236dbdc6a4e5a4989483dac97aee0b +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs new file mode 100644 index 0000000..afbb84b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs @@ -0,0 +1,211 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonGraphicCustomMaterials")] + public class SkeletonGraphicCustomMaterials : MonoBehaviour { + + #region Inspector + public SkeletonGraphic skeletonGraphic; + [SerializeField] protected List customMaterialOverrides = new List(); + [SerializeField] protected List customTextureOverrides = new List(); + + #if UNITY_EDITOR + void Reset () { + skeletonGraphic = GetComponent(); + + // Populate material list + if (skeletonGraphic != null && skeletonGraphic.skeletonDataAsset != null) { + var atlasAssets = skeletonGraphic.skeletonDataAsset.atlasAssets; + + var initialAtlasMaterialOverrides = new List(); + foreach (AtlasAssetBase atlasAsset in atlasAssets) { + foreach (Material atlasMaterial in atlasAsset.Materials) { + var atlasMaterialOverride = new AtlasMaterialOverride { + overrideEnabled = false, + originalTexture = atlasMaterial.mainTexture + }; + + initialAtlasMaterialOverrides.Add(atlasMaterialOverride); + } + } + customMaterialOverrides = initialAtlasMaterialOverrides; + } + + // Populate texture list + if (skeletonGraphic != null && skeletonGraphic.skeletonDataAsset != null) { + var atlasAssets = skeletonGraphic.skeletonDataAsset.atlasAssets; + + var initialAtlasTextureOverrides = new List(); + foreach (AtlasAssetBase atlasAsset in atlasAssets) { + foreach (Material atlasMaterial in atlasAsset.Materials) { + var atlasTextureOverride = new AtlasTextureOverride { + overrideEnabled = false, + originalTexture = atlasMaterial.mainTexture + }; + + initialAtlasTextureOverrides.Add(atlasTextureOverride); + } + } + customTextureOverrides = initialAtlasTextureOverrides; + } + } + #endif + #endregion + + void SetCustomMaterialOverrides () { + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + for (int i = 0; i < customMaterialOverrides.Count; i++) { + AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; + if (atlasMaterialOverride.overrideEnabled) + skeletonGraphic.CustomMaterialOverride[atlasMaterialOverride.originalTexture] = atlasMaterialOverride.replacementMaterial; + } + } + + void RemoveCustomMaterialOverrides () { + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + for (int i = 0; i < customMaterialOverrides.Count; i++) { + AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; + Material currentMaterial; + + if (!skeletonGraphic.CustomMaterialOverride.TryGetValue(atlasMaterialOverride.originalTexture, out currentMaterial)) + continue; + + // Do not revert the material if it was changed by something else + if (currentMaterial != atlasMaterialOverride.replacementMaterial) + continue; + + skeletonGraphic.CustomMaterialOverride.Remove(atlasMaterialOverride.originalTexture); + } + } + + void SetCustomTextureOverrides () { + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + for (int i = 0; i < customTextureOverrides.Count; i++) { + AtlasTextureOverride atlasTextureOverride = customTextureOverrides[i]; + if (atlasTextureOverride.overrideEnabled) + skeletonGraphic.CustomTextureOverride[atlasTextureOverride.originalTexture] = atlasTextureOverride.replacementTexture; + } + } + + void RemoveCustomTextureOverrides () { + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + for (int i = 0; i < customTextureOverrides.Count; i++) { + AtlasTextureOverride atlasTextureOverride = customTextureOverrides[i]; + Texture currentTexture; + + if (!skeletonGraphic.CustomTextureOverride.TryGetValue(atlasTextureOverride.originalTexture, out currentTexture)) + continue; + + // Do not revert the material if it was changed by something else + if (currentTexture != atlasTextureOverride.replacementTexture) + continue; + + skeletonGraphic.CustomTextureOverride.Remove(atlasTextureOverride.originalTexture); + } + } + + // OnEnable applies the overrides at runtime, and when the editor loads. + void OnEnable () { + if (skeletonGraphic == null) + skeletonGraphic = GetComponent(); + + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + skeletonGraphic.Initialize(false); + SetCustomMaterialOverrides(); + SetCustomTextureOverrides(); + } + + // OnDisable removes the overrides at runtime, and in the editor when the component is disabled or destroyed. + void OnDisable () { + if (skeletonGraphic == null) { + Debug.LogError("skeletonGraphic == null"); + return; + } + + RemoveCustomMaterialOverrides(); + RemoveCustomTextureOverrides(); + } + + [Serializable] + public struct AtlasMaterialOverride : IEquatable { + public bool overrideEnabled; + public Texture originalTexture; + public Material replacementMaterial; + + public bool Equals (AtlasMaterialOverride other) { + return overrideEnabled == other.overrideEnabled && originalTexture == other.originalTexture && replacementMaterial == other.replacementMaterial; + } + } + + [Serializable] + public struct AtlasTextureOverride : IEquatable { + public bool overrideEnabled; + public Texture originalTexture; + public Texture replacementTexture; + + public bool Equals (AtlasTextureOverride other) { + return overrideEnabled == other.overrideEnabled && originalTexture == other.originalTexture && replacementTexture == other.replacementTexture; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs.meta new file mode 100644 index 0000000..3f0170a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonGraphicCustomMaterials.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c8717e10b272bf42b05d363ac2679a6 +timeCreated: 1588789074 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs new file mode 100644 index 0000000..c137570 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs @@ -0,0 +1,212 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif +#define SPINE_OPTIONAL_MATERIALOVERRIDE + +// Contributed by: Lost Polygon + +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Spine.Unity { + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonRendererCustomMaterials")] + public class SkeletonRendererCustomMaterials : MonoBehaviour { + + #region Inspector + public SkeletonRenderer skeletonRenderer; + [SerializeField] protected List customSlotMaterials = new List(); + [SerializeField] protected List customMaterialOverrides = new List(); + + #if UNITY_EDITOR + void Reset () { + skeletonRenderer = GetComponent(); + + // Populate atlas list + if (skeletonRenderer != null && skeletonRenderer.skeletonDataAsset != null) { + var atlasAssets = skeletonRenderer.skeletonDataAsset.atlasAssets; + + var initialAtlasMaterialOverrides = new List(); + foreach (AtlasAssetBase atlasAsset in atlasAssets) { + foreach (Material atlasMaterial in atlasAsset.Materials) { + var atlasMaterialOverride = new AtlasMaterialOverride { + overrideDisabled = true, + originalMaterial = atlasMaterial + }; + + initialAtlasMaterialOverrides.Add(atlasMaterialOverride); + } + } + + customMaterialOverrides = initialAtlasMaterialOverrides; + } + } + #endif + #endregion + + void SetCustomSlotMaterials () { + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + for (int i = 0; i < customSlotMaterials.Count; i++) { + SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i]; + if (slotMaterialOverride.overrideDisabled || string.IsNullOrEmpty(slotMaterialOverride.slotName)) + continue; + + Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName); + skeletonRenderer.CustomSlotMaterials[slotObject] = slotMaterialOverride.material; + } + } + + void RemoveCustomSlotMaterials () { + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + for (int i = 0; i < customSlotMaterials.Count; i++) { + SlotMaterialOverride slotMaterialOverride = customSlotMaterials[i]; + if (string.IsNullOrEmpty(slotMaterialOverride.slotName)) + continue; + + Slot slotObject = skeletonRenderer.skeleton.FindSlot(slotMaterialOverride.slotName); + + Material currentMaterial; + if (!skeletonRenderer.CustomSlotMaterials.TryGetValue(slotObject, out currentMaterial)) + continue; + + // Do not revert the material if it was changed by something else + if (currentMaterial != slotMaterialOverride.material) + continue; + + skeletonRenderer.CustomSlotMaterials.Remove(slotObject); + } + } + + void SetCustomMaterialOverrides () { + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + #if SPINE_OPTIONAL_MATERIALOVERRIDE + for (int i = 0; i < customMaterialOverrides.Count; i++) { + AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; + if (atlasMaterialOverride.overrideDisabled) + continue; + + skeletonRenderer.CustomMaterialOverride[atlasMaterialOverride.originalMaterial] = atlasMaterialOverride.replacementMaterial; + } + #endif + } + + void RemoveCustomMaterialOverrides () { + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + #if SPINE_OPTIONAL_MATERIALOVERRIDE + for (int i = 0; i < customMaterialOverrides.Count; i++) { + AtlasMaterialOverride atlasMaterialOverride = customMaterialOverrides[i]; + Material currentMaterial; + + if (!skeletonRenderer.CustomMaterialOverride.TryGetValue(atlasMaterialOverride.originalMaterial, out currentMaterial)) + continue; + + // Do not revert the material if it was changed by something else + if (currentMaterial != atlasMaterialOverride.replacementMaterial) + continue; + + skeletonRenderer.CustomMaterialOverride.Remove(atlasMaterialOverride.originalMaterial); + } + #endif + } + + // OnEnable applies the overrides at runtime, and when the editor loads. + void OnEnable () { + if (skeletonRenderer == null) + skeletonRenderer = GetComponent(); + + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + skeletonRenderer.Initialize(false); + SetCustomMaterialOverrides(); + SetCustomSlotMaterials(); + } + + // OnDisable removes the overrides at runtime, and in the editor when the component is disabled or destroyed. + void OnDisable () { + if (skeletonRenderer == null) { + Debug.LogError("skeletonRenderer == null"); + return; + } + + RemoveCustomMaterialOverrides(); + RemoveCustomSlotMaterials(); + } + + [Serializable] + public struct SlotMaterialOverride : IEquatable { + public bool overrideDisabled; + + [SpineSlot] + public string slotName; + public Material material; + + public bool Equals (SlotMaterialOverride other) { + return overrideDisabled == other.overrideDisabled && slotName == other.slotName && material == other.material; + } + } + + [Serializable] + public struct AtlasMaterialOverride : IEquatable { + public bool overrideDisabled; + public Material originalMaterial; + public Material replacementMaterial; + + public bool Equals (AtlasMaterialOverride other) { + return overrideDisabled == other.overrideDisabled && originalMaterial == other.originalMaterial && replacementMaterial == other.replacementMaterial; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs.meta new file mode 100644 index 0000000..eb50faf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 26947ae098a8447408d80c0c86e35b48 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt new file mode 100644 index 0000000..9170775 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt @@ -0,0 +1,11 @@ +SkeletonRendererCustomMaterials by LostPolygon +=============================== +This is a basic serialization and inspector implementation for custom material overrides for SkeletonRenderer and its derived classes (SkeletonAnimation, SkeletonAnimator). + +## How to use +Right-click on your SkeletonRenderer and select "Add Basic Serialized Custom Materials". This will add and initialize the SkeletonRendererCustomMaterials to the same object. + +You can use this to store material override settings for SkeletonRenderer instances/prefabs so they will be applied automatically when your scene starts or when the prefab is instantiated. + +This script is not intended for use with code. +To dynamically set materials for your SkeletonRenderer through code, you can directly access `SkeletonRenderer.CustomMaterialOverride` for material array overrides and `SkeletonRenderer.CustomSlotMaterials` for slot material overrides. \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt.meta new file mode 100644 index 0000000..a979106 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonRendererCustomMaterials/SkeletonRendererCustomMaterials.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3d4db6c367e463c4cb5566afc490163c +timeCreated: 1460572571 +licenseType: Free +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility.meta new file mode 100644 index 0000000..d690c94 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: f6e0caaafe294de48af468a6a9321473 +folderAsset: yes +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs new file mode 100644 index 0000000..4855fd0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs @@ -0,0 +1,92 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + + /// + /// Utility component to support flipping of 2D hinge chains (chains of HingeJoint2D objects) along + /// with the parent skeleton by activating the respective mirrored versions of the hinge chain. + /// Note: This component is automatically attached when calling "Create Hinge Chain 2D" at , + /// do not attempt to use this component for other purposes. + /// + public class ActivateBasedOnFlipDirection : MonoBehaviour { + + public SkeletonRenderer skeletonRenderer; + public SkeletonGraphic skeletonGraphic; + public GameObject activeOnNormalX; + public GameObject activeOnFlippedX; + HingeJoint2D[] jointsNormalX; + HingeJoint2D[] jointsFlippedX; + ISkeletonComponent skeletonComponent; + + bool wasFlippedXBefore = false; + + private void Start () { + jointsNormalX = activeOnNormalX.GetComponentsInChildren(); + jointsFlippedX = activeOnFlippedX.GetComponentsInChildren(); + skeletonComponent = skeletonRenderer != null ? (ISkeletonComponent)skeletonRenderer : (ISkeletonComponent)skeletonGraphic; + } + + private void FixedUpdate () { + bool isFlippedX = (skeletonComponent.Skeleton.ScaleX < 0); + if (isFlippedX != wasFlippedXBefore) { + HandleFlip(isFlippedX); + } + wasFlippedXBefore = isFlippedX; + } + + void HandleFlip (bool isFlippedX) { + GameObject gameObjectToActivate = isFlippedX ? activeOnFlippedX : activeOnNormalX; + GameObject gameObjectToDeactivate = isFlippedX ? activeOnNormalX : activeOnFlippedX; + + gameObjectToActivate.SetActive(true); + gameObjectToDeactivate.SetActive(false); + + ResetJointPositions(isFlippedX ? jointsFlippedX : jointsNormalX); + ResetJointPositions(isFlippedX ? jointsNormalX : jointsFlippedX); + CompensateMovementAfterFlipX(gameObjectToActivate.transform, gameObjectToDeactivate.transform); + } + + void ResetJointPositions (HingeJoint2D[] joints) { + for (int i = 0; i < joints.Length; ++i) { + var joint = joints[i]; + var parent = joint.connectedBody.transform; + joint.transform.position = parent.TransformPoint(joint.connectedAnchor); + } + } + + void CompensateMovementAfterFlipX (Transform toActivate, Transform toDeactivate) { + Transform targetLocation = toDeactivate.GetChild(0); + Transform currentLocation = toActivate.GetChild(0); + toActivate.position += targetLocation.position - currentLocation.position; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs.meta new file mode 100644 index 0000000..428af1b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/ActivateBasedOnFlipDirection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70ae96e4f2feb654681a2f16e4effeec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs new file mode 100644 index 0000000..f0ede08 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs @@ -0,0 +1,54 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + + /// + /// Utility component to support flipping of hinge chains (chains of HingeJoint objects) along with the parent skeleton. + /// + /// Note: This component is automatically attached when calling "Create Hinge Chain" at . + /// + [RequireComponent(typeof(Rigidbody))] + public class FollowLocationRigidbody : MonoBehaviour { + + public Transform reference; + Rigidbody ownRigidbody; + + private void Awake () { + ownRigidbody = this.GetComponent(); + } + + void FixedUpdate () { + ownRigidbody.rotation = reference.rotation; + ownRigidbody.position = reference.position; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs.meta new file mode 100644 index 0000000..4354d36 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9fc20d5e917562341a5007777a9d0db2 +timeCreated: 1571763023 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs new file mode 100644 index 0000000..76c12b9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs @@ -0,0 +1,59 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + + /// + /// Utility component to support flipping of hinge chains (chains of HingeJoint objects) along with the parent skeleton. + /// + /// Note: This component is automatically attached when calling "Create Hinge Chain" at . + /// + [RequireComponent(typeof(Rigidbody2D))] + public class FollowLocationRigidbody2D : MonoBehaviour { + + public Transform reference; + public bool followFlippedX; + Rigidbody2D ownRigidbody; + + private void Awake () { + ownRigidbody = this.GetComponent(); + } + + void FixedUpdate () { + if (followFlippedX) { + ownRigidbody.rotation = ((-reference.rotation.eulerAngles.z + 270f) % 360f) - 90f; + } + else + ownRigidbody.rotation = reference.rotation.eulerAngles.z; + ownRigidbody.position = reference.position; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs.meta new file mode 100644 index 0000000..a62ccec --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowLocationRigidbody2D.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 02aae87c39b869548a9051fbdb1975e6 +timeCreated: 1572012493 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs new file mode 100644 index 0000000..a970ae9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs @@ -0,0 +1,86 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + + /// + /// Utility component to support flipping of hinge chains (chains of HingeJoint objects) along with the parent skeleton. + /// Note that flipping needs to be performed by 180 degree rotation at , + /// by setting to true, not via negative scale. + /// + /// Note: This component is automatically attached when calling "Create Hinge Chain" at , + /// do not attempt to use this component for other purposes. + /// + public class FollowSkeletonUtilityRootRotation : MonoBehaviour { + + const float FLIP_ANGLE_THRESHOLD = 100.0f; + + public Transform reference; + Vector3 prevLocalEulerAngles; + + private void Start () { + prevLocalEulerAngles = this.transform.localEulerAngles; + } + + void FixedUpdate () { + this.transform.rotation = reference.rotation; + + bool wasFlippedAroundY = Mathf.Abs(this.transform.localEulerAngles.y - prevLocalEulerAngles.y) > FLIP_ANGLE_THRESHOLD; + bool wasFlippedAroundX = Mathf.Abs(this.transform.localEulerAngles.x - prevLocalEulerAngles.x) > FLIP_ANGLE_THRESHOLD; + if (wasFlippedAroundY) + CompensatePositionToYRotation(); + if (wasFlippedAroundX) + CompensatePositionToXRotation(); + + prevLocalEulerAngles = this.transform.localEulerAngles; + } + + /// + /// Compensates the position so that a child at the reference position remains in the same place, + /// to counter any movement that occurred by rotation. + /// + void CompensatePositionToYRotation () { + Vector3 newPosition = reference.position + (reference.position - this.transform.position); + newPosition.y = this.transform.position.y; + this.transform.position = newPosition; + } + + /// + /// Compensates the position so that a child at the reference position remains in the same place, + /// to counter any movement that occurred by rotation. + /// + void CompensatePositionToXRotation () { + Vector3 newPosition = reference.position + (reference.position - this.transform.position); + newPosition.x = this.transform.position.x; + this.transform.position = newPosition; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs.meta new file mode 100644 index 0000000..6029241 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/FollowSkeletonUtilityRootRotation.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 456a736ebb92ebf4b959fa9c4b704427 +timeCreated: 1571763206 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs new file mode 100644 index 0000000..632b85d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs @@ -0,0 +1,469 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; +using System.Collections.Generic; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [RequireComponent(typeof(ISkeletonAnimation))] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtility")] + public sealed class SkeletonUtility : MonoBehaviour { + + #region BoundingBoxAttachment + public static PolygonCollider2D AddBoundingBoxGameObject (Skeleton skeleton, string skinName, string slotName, string attachmentName, Transform parent, bool isTrigger = true) { + Skin skin = string.IsNullOrEmpty(skinName) ? skeleton.data.defaultSkin : skeleton.data.FindSkin(skinName); + if (skin == null) { + Debug.LogError("Skin " + skinName + " not found!"); + return null; + } + + var attachment = skin.GetAttachment(skeleton.FindSlotIndex(slotName), attachmentName); + if (attachment == null) { + Debug.LogFormat("Attachment in slot '{0}' named '{1}' not found in skin '{2}'.", slotName, attachmentName, skin.name); + return null; + } + + var box = attachment as BoundingBoxAttachment; + if (box != null) { + var slot = skeleton.FindSlot(slotName); + return AddBoundingBoxGameObject(box.Name, box, slot, parent, isTrigger); + } else { + Debug.LogFormat("Attachment '{0}' was not a Bounding Box.", attachmentName); + return null; + } + } + + public static PolygonCollider2D AddBoundingBoxGameObject (string name, BoundingBoxAttachment box, Slot slot, Transform parent, bool isTrigger = true) { + var go = new GameObject("[BoundingBox]" + (string.IsNullOrEmpty(name) ? box.Name : name)); +#if UNITY_EDITOR + if (!Application.isPlaying) + UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn BoundingBox"); +# endif + var got = go.transform; + got.parent = parent; + got.localPosition = Vector3.zero; + got.localRotation = Quaternion.identity; + got.localScale = Vector3.one; + return AddBoundingBoxAsComponent(box, slot, go, isTrigger); + } + + public static PolygonCollider2D AddBoundingBoxAsComponent (BoundingBoxAttachment box, Slot slot, GameObject gameObject, bool isTrigger = true) { + if (box == null) return null; + var collider = gameObject.AddComponent(); + collider.isTrigger = isTrigger; + SetColliderPointsLocal(collider, slot, box); + return collider; + } + + public static void SetColliderPointsLocal (PolygonCollider2D collider, Slot slot, BoundingBoxAttachment box, float scale = 1.0f) { + if (box == null) return; + if (box.IsWeighted()) Debug.LogWarning("UnityEngine.PolygonCollider2D does not support weighted or animated points. Collider points will not be animated and may have incorrect orientation. If you want to use it as a collider, please remove weights and animations from the bounding box in Spine editor."); + var verts = box.GetLocalVertices(slot, null); + if (scale != 1.0f) { + for (int i = 0, n = verts.Length; i < n; ++i) + verts[i] *= scale; + } + collider.SetPath(0, verts); + } + + public static Bounds GetBoundingBoxBounds (BoundingBoxAttachment boundingBox, float depth = 0) { + float[] floats = boundingBox.Vertices; + int floatCount = floats.Length; + + Bounds bounds = new Bounds(); + + bounds.center = new Vector3(floats[0], floats[1], 0); + for (int i = 2; i < floatCount; i += 2) + bounds.Encapsulate(new Vector3(floats[i], floats[i + 1], 0)); + + Vector3 size = bounds.size; + size.z = depth; + bounds.size = size; + + return bounds; + } + + public static Rigidbody2D AddBoneRigidbody2D (GameObject gameObject, bool isKinematic = true, float gravityScale = 0f) { + var rb = gameObject.GetComponent(); + if (rb == null) { + rb = gameObject.AddComponent(); + rb.isKinematic = isKinematic; + rb.gravityScale = gravityScale; + } + return rb; + } + #endregion + + public delegate void SkeletonUtilityDelegate (); + public event SkeletonUtilityDelegate OnReset; + public Transform boneRoot; + /// + /// If true, and are followed + /// by 180 degree rotation. If false, negative Transform scale is used. + /// Note that using negative scale is consistent with previous behaviour (hence the default), + /// however causes serious problems with rigidbodies and physics. Therefore, it is recommended to + /// enable this parameter where possible. When creating hinge chains for a chain of skeleton bones + /// via , it is mandatory to have flipBy180DegreeRotation enabled. + /// + public bool flipBy180DegreeRotation = false; + + void Update () { + var skeleton = skeletonComponent.Skeleton; + if (skeleton != null && boneRoot != null) { + + if (flipBy180DegreeRotation) { + boneRoot.localScale = new Vector3(Mathf.Abs(skeleton.ScaleX), Mathf.Abs(skeleton.ScaleY), 1f); + boneRoot.eulerAngles = new Vector3(skeleton.ScaleY > 0 ? 0 : 180, + skeleton.ScaleX > 0 ? 0 : 180, + 0); + } + else { + boneRoot.localScale = new Vector3(skeleton.ScaleX, skeleton.ScaleY, 1f); + } + } + + if (canvas != null) { + positionScale = canvas.referencePixelsPerUnit; + } + } + + [HideInInspector] public SkeletonRenderer skeletonRenderer; + [HideInInspector] public SkeletonGraphic skeletonGraphic; + private Canvas canvas; + [System.NonSerialized] public ISkeletonAnimation skeletonAnimation; + + private ISkeletonComponent skeletonComponent; + [System.NonSerialized] public List boneComponents = new List(); + [System.NonSerialized] public List constraintComponents = new List(); + + + public ISkeletonComponent SkeletonComponent { + get { + if (skeletonComponent == null) { + skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent() : + skeletonGraphic != null ? skeletonGraphic.GetComponent() : + GetComponent(); + } + return skeletonComponent; + } + } + public Skeleton Skeleton { + get { + if (SkeletonComponent == null) + return null; + return skeletonComponent.Skeleton; + } + } + + public bool IsValid { + get { + return (skeletonRenderer != null && skeletonRenderer.valid) || + (skeletonGraphic != null && skeletonGraphic.IsValid); + } + } + + public float PositionScale { get { return positionScale; } } + + float positionScale = 1.0f; + bool hasOverrideBones; + bool hasConstraints; + bool needToReprocessBones; + + public void ResubscribeEvents () { + OnDisable(); + OnEnable(); + } + + void OnEnable () { + if (skeletonRenderer == null) { + skeletonRenderer = GetComponent(); + } + if (skeletonGraphic == null) { + skeletonGraphic = GetComponent(); + } + if (skeletonAnimation == null) { + skeletonAnimation = skeletonRenderer != null ? skeletonRenderer.GetComponent() : + skeletonGraphic != null ? skeletonGraphic.GetComponent() : + GetComponent(); + } + if (skeletonComponent == null) { + skeletonComponent = skeletonRenderer != null ? skeletonRenderer.GetComponent() : + skeletonGraphic != null ? skeletonGraphic.GetComponent() : + GetComponent(); + } + + if (skeletonRenderer != null) { + skeletonRenderer.OnRebuild -= HandleRendererReset; + skeletonRenderer.OnRebuild += HandleRendererReset; + } + else if (skeletonGraphic != null) { + skeletonGraphic.OnRebuild -= HandleRendererReset; + skeletonGraphic.OnRebuild += HandleRendererReset; + canvas = skeletonGraphic.canvas; + if (canvas == null) + canvas = skeletonGraphic.GetComponentInParent(); + if (canvas == null) + positionScale = 100.0f; + } + + if (skeletonAnimation != null) { + skeletonAnimation.UpdateLocal -= UpdateLocal; + skeletonAnimation.UpdateLocal += UpdateLocal; + } + + CollectBones(); + } + + void Start () { + //recollect because order of operations failure when switching between game mode and edit mode... + CollectBones(); + } + + void OnDisable () { + if (skeletonRenderer != null) + skeletonRenderer.OnRebuild -= HandleRendererReset; + if (skeletonGraphic != null) + skeletonGraphic.OnRebuild -= HandleRendererReset; + + if (skeletonAnimation != null) { + skeletonAnimation.UpdateLocal -= UpdateLocal; + skeletonAnimation.UpdateWorld -= UpdateWorld; + skeletonAnimation.UpdateComplete -= UpdateComplete; + } + } + + void HandleRendererReset (SkeletonRenderer r) { + if (OnReset != null) OnReset(); + CollectBones(); + } + + void HandleRendererReset (SkeletonGraphic g) { + if (OnReset != null) OnReset(); + CollectBones(); + } + + public void RegisterBone (SkeletonUtilityBone bone) { + if (boneComponents.Contains(bone)) { + return; + } else { + boneComponents.Add(bone); + needToReprocessBones = true; + } + } + + public void UnregisterBone (SkeletonUtilityBone bone) { + boneComponents.Remove(bone); + } + + public void RegisterConstraint (SkeletonUtilityConstraint constraint) { + if (constraintComponents.Contains(constraint)) + return; + else { + constraintComponents.Add(constraint); + needToReprocessBones = true; + } + } + + public void UnregisterConstraint (SkeletonUtilityConstraint constraint) { + constraintComponents.Remove(constraint); + } + + public void CollectBones () { + var skeleton = skeletonComponent.Skeleton; + if (skeleton == null) return; + + if (boneRoot != null) { + var constraintTargets = new List(); + var ikConstraints = skeleton.IkConstraints; + for (int i = 0, n = ikConstraints.Count; i < n; i++) + constraintTargets.Add(ikConstraints.Items[i].target); + + var transformConstraints = skeleton.TransformConstraints; + for (int i = 0, n = transformConstraints.Count; i < n; i++) + constraintTargets.Add(transformConstraints.Items[i].target); + + var boneComponents = this.boneComponents; + for (int i = 0, n = boneComponents.Count; i < n; i++) { + var b = boneComponents[i]; + if (b.bone == null) { + b.DoUpdate(SkeletonUtilityBone.UpdatePhase.Local); + if (b.bone == null) continue; + } + hasOverrideBones |= (b.mode == SkeletonUtilityBone.Mode.Override); + hasConstraints |= constraintTargets.Contains(b.bone); + } + + hasConstraints |= constraintComponents.Count > 0; + + if (skeletonAnimation != null) { + skeletonAnimation.UpdateWorld -= UpdateWorld; + skeletonAnimation.UpdateComplete -= UpdateComplete; + + if (hasOverrideBones || hasConstraints) + skeletonAnimation.UpdateWorld += UpdateWorld; + + if (hasConstraints) + skeletonAnimation.UpdateComplete += UpdateComplete; + } + + needToReprocessBones = false; + } else { + boneComponents.Clear(); + constraintComponents.Clear(); + } + } + + void UpdateLocal (ISkeletonAnimation anim) { + if (needToReprocessBones) + CollectBones(); + + var boneComponents = this.boneComponents; + if (boneComponents == null) return; + for (int i = 0, n = boneComponents.Count; i < n; i++) + boneComponents[i].transformLerpComplete = false; + + UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Local); + } + + void UpdateWorld (ISkeletonAnimation anim) { + UpdateAllBones(SkeletonUtilityBone.UpdatePhase.World); + for (int i = 0, n = constraintComponents.Count; i < n; i++) + constraintComponents[i].DoUpdate(); + } + + void UpdateComplete (ISkeletonAnimation anim) { + UpdateAllBones(SkeletonUtilityBone.UpdatePhase.Complete); + } + + void UpdateAllBones (SkeletonUtilityBone.UpdatePhase phase) { + if (boneRoot == null) + CollectBones(); + + var boneComponents = this.boneComponents; + if (boneComponents == null) return; + for (int i = 0, n = boneComponents.Count; i < n; i++) + boneComponents[i].DoUpdate(phase); + } + + public Transform GetBoneRoot () { + if (boneRoot != null) + return boneRoot; + + var boneRootObject = new GameObject("SkeletonUtility-SkeletonRoot"); +#if UNITY_EDITOR + if (!Application.isPlaying) + UnityEditor.Undo.RegisterCreatedObjectUndo(boneRootObject, "Spawn Bone"); +#endif + if (skeletonGraphic != null) + boneRootObject.AddComponent(); + + boneRoot = boneRootObject.transform; + boneRoot.SetParent(transform); + boneRoot.localPosition = Vector3.zero; + boneRoot.localRotation = Quaternion.identity; + boneRoot.localScale = Vector3.one; + + return boneRoot; + } + + public GameObject SpawnRoot (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) { + GetBoneRoot(); + Skeleton skeleton = this.skeletonComponent.Skeleton; + + GameObject go = SpawnBone(skeleton.RootBone, boneRoot, mode, pos, rot, sca); + CollectBones(); + return go; + } + + public GameObject SpawnHierarchy (SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) { + GetBoneRoot(); + Skeleton skeleton = this.skeletonComponent.Skeleton; + GameObject go = SpawnBoneRecursively(skeleton.RootBone, boneRoot, mode, pos, rot, sca); + CollectBones(); + return go; + } + + public GameObject SpawnBoneRecursively (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) { + GameObject go = SpawnBone(bone, parent, mode, pos, rot, sca); + + ExposedList childrenBones = bone.Children; + for (int i = 0, n = childrenBones.Count; i < n; i++) { + Bone child = childrenBones.Items[i]; + SpawnBoneRecursively(child, go.transform, mode, pos, rot, sca); + } + + return go; + } + + public GameObject SpawnBone (Bone bone, Transform parent, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca) { + GameObject go = new GameObject(bone.Data.Name); + #if UNITY_EDITOR + if (!Application.isPlaying) + UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Spawn Bone"); + #endif + if (skeletonGraphic != null) + go.AddComponent(); + + var goTransform = go.transform; + goTransform.SetParent(parent); + + SkeletonUtilityBone b = go.AddComponent(); + b.hierarchy = this; + b.position = pos; + b.rotation = rot; + b.scale = sca; + b.mode = mode; + b.zPosition = true; + b.Reset(); + b.bone = bone; + b.boneName = bone.Data.Name; + b.valid = true; + + if (mode == SkeletonUtilityBone.Mode.Override) { + if (rot) goTransform.localRotation = Quaternion.Euler(0, 0, b.bone.AppliedRotation); + if (pos) goTransform.localPosition = new Vector3(b.bone.X * positionScale, b.bone.Y * positionScale, 0); + goTransform.localScale = new Vector3(b.bone.scaleX, b.bone.scaleY, 0); + } + + return go; + } + + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs.meta new file mode 100644 index 0000000..29f2fd7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtility.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7f726fb798ad621458c431cb9966d91d +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs new file mode 100644 index 0000000..c3e16f2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs @@ -0,0 +1,243 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; + +namespace Spine.Unity { + /// Sets a GameObject's transform to match a bone on a Spine skeleton. + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [AddComponentMenu("Spine/SkeletonUtilityBone")] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtilityBone")] + public class SkeletonUtilityBone : MonoBehaviour { + public enum Mode { + Follow, + Override + } + + public enum UpdatePhase { + Local, + World, + Complete + } + + #region Inspector + /// If a bone isn't set, boneName is used to find the bone. + public string boneName; + public Transform parentReference; + public Mode mode; + public bool position, rotation, scale, zPosition = true; + [Range(0f, 1f)] + public float overrideAlpha = 1; + #endregion + + public SkeletonUtility hierarchy; + [System.NonSerialized] public Bone bone; + [System.NonSerialized] public bool transformLerpComplete; + [System.NonSerialized] public bool valid; + Transform cachedTransform; + Transform skeletonTransform; + bool incompatibleTransformMode; + public bool IncompatibleTransformMode { get { return incompatibleTransformMode; } } + + public void Reset () { + bone = null; + cachedTransform = transform; + valid = hierarchy != null && hierarchy.IsValid; + if (!valid) + return; + skeletonTransform = hierarchy.transform; + hierarchy.OnReset -= HandleOnReset; + hierarchy.OnReset += HandleOnReset; + DoUpdate(UpdatePhase.Local); + } + + void OnEnable () { + if (hierarchy == null) hierarchy = transform.GetComponentInParent(); + if (hierarchy == null) return; + + hierarchy.RegisterBone(this); + hierarchy.OnReset += HandleOnReset; + } + + void HandleOnReset () { + Reset(); + } + + void OnDisable () { + if (hierarchy != null) { + hierarchy.OnReset -= HandleOnReset; + hierarchy.UnregisterBone(this); + } + } + + public void DoUpdate (UpdatePhase phase) { + if (!valid) { + Reset(); + return; + } + + var skeleton = hierarchy.Skeleton; + + if (bone == null) { + if (string.IsNullOrEmpty(boneName)) return; + bone = skeleton.FindBone(boneName); + if (bone == null) { + Debug.LogError("Bone not found: " + boneName, this); + return; + } + } + if (!bone.Active) return; + + float positionScale = hierarchy.PositionScale; + + var thisTransform = cachedTransform; + float skeletonFlipRotation = Mathf.Sign(skeleton.ScaleX * skeleton.ScaleY); + if (mode == Mode.Follow) { + switch (phase) { + case UpdatePhase.Local: + if (position) + thisTransform.localPosition = new Vector3(bone.x * positionScale, bone.y * positionScale, 0); + + if (rotation) { + if (bone.data.transformMode.InheritsRotation()) { + thisTransform.localRotation = Quaternion.Euler(0, 0, bone.rotation); + } else { + Vector3 euler = skeletonTransform.rotation.eulerAngles; + thisTransform.rotation = Quaternion.Euler(euler.x, euler.y, euler.z + (bone.WorldRotationX * skeletonFlipRotation)); + } + } + + if (scale) { + thisTransform.localScale = new Vector3(bone.scaleX, bone.scaleY, 1f); + incompatibleTransformMode = BoneTransformModeIncompatible(bone); + } + break; + case UpdatePhase.World: + case UpdatePhase.Complete: + // Use Applied transform values (ax, ay, AppliedRotation, ascale) if world values were modified by constraints. + if (!bone.appliedValid) { + bone.UpdateAppliedTransform(); + } + + if (position) + thisTransform.localPosition = new Vector3(bone.ax * positionScale, bone.ay * positionScale, 0); + + if (rotation) { + if (bone.data.transformMode.InheritsRotation()) { + thisTransform.localRotation = Quaternion.Euler(0, 0, bone.AppliedRotation); + } else { + Vector3 euler = skeletonTransform.rotation.eulerAngles; + thisTransform.rotation = Quaternion.Euler(euler.x, euler.y, euler.z + (bone.WorldRotationX * skeletonFlipRotation)); + } + } + + if (scale) { + thisTransform.localScale = new Vector3(bone.ascaleX, bone.ascaleY, 1f); + incompatibleTransformMode = BoneTransformModeIncompatible(bone); + } + break; + } + + } else if (mode == Mode.Override) { + if (transformLerpComplete) + return; + + if (parentReference == null) { + if (position) { + Vector3 clp = thisTransform.localPosition / positionScale; + bone.x = Mathf.Lerp(bone.x, clp.x, overrideAlpha); + bone.y = Mathf.Lerp(bone.y, clp.y, overrideAlpha); + } + + if (rotation) { + float angle = Mathf.LerpAngle(bone.Rotation, thisTransform.localRotation.eulerAngles.z, overrideAlpha); + bone.Rotation = angle; + bone.AppliedRotation = angle; + } + + if (scale) { + Vector3 cls = thisTransform.localScale; + bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha); + bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha); + } + + } else { + if (transformLerpComplete) + return; + + if (position) { + Vector3 pos = parentReference.InverseTransformPoint(thisTransform.position) / positionScale; + bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha); + bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha); + } + + if (rotation) { + float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(Vector3.forward, parentReference.InverseTransformDirection(thisTransform.up)).eulerAngles.z, overrideAlpha); + bone.Rotation = angle; + bone.AppliedRotation = angle; + } + + if (scale) { + Vector3 cls = thisTransform.localScale; + bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha); + bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha); + } + + incompatibleTransformMode = BoneTransformModeIncompatible(bone); + } + + transformLerpComplete = true; + } + } + + public static bool BoneTransformModeIncompatible (Bone bone) { + return !bone.data.transformMode.InheritsScale(); + } + + public void AddBoundingBox (string skinName, string slotName, string attachmentName) { + SkeletonUtility.AddBoneRigidbody2D(transform.gameObject); + SkeletonUtility.AddBoundingBoxGameObject(bone.skeleton, skinName, slotName, attachmentName, transform); + } + +#if UNITY_EDITOR + void OnDrawGizmos () { + if (IncompatibleTransformMode) + Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning"); + } + #endif + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs.meta new file mode 100644 index 0000000..51537b4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityBone.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b238dfcde8209044b97d23f62bcaadf6 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs new file mode 100644 index 0000000..f549afa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs @@ -0,0 +1,62 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER +#define NEW_PREFAB_SYSTEM +#endif + +using UnityEngine; + +namespace Spine.Unity { + + #if NEW_PREFAB_SYSTEM + [ExecuteAlways] + #else + [ExecuteInEditMode] + #endif + [RequireComponent(typeof(SkeletonUtilityBone))] + [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonUtilityConstraint")] + public abstract class SkeletonUtilityConstraint : MonoBehaviour { + + protected SkeletonUtilityBone bone; + protected SkeletonUtility hierarchy; + + protected virtual void OnEnable () { + bone = GetComponent(); + hierarchy = transform.GetComponentInParent(); + hierarchy.RegisterConstraint(this); + } + + protected virtual void OnDisable () { + hierarchy.UnregisterConstraint(this); + } + + public abstract void DoUpdate (); + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs.meta new file mode 100644 index 0000000..b78abdc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Components/SkeletonUtility/SkeletonUtilityConstraint.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 522dbfcc6c916df4396f14f35048d185 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated.meta new file mode 100644 index 0000000..099ea4a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 04817e31b917de6489f349dd332d7468 +folderAsset: yes +timeCreated: 1563295668 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes.meta new file mode 100644 index 0000000..c3ef039 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: dfdd78a071ca1a04bb64c6cc41e14aa0 +folderAsset: yes +timeCreated: 1496447038 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs new file mode 100644 index 0000000..69b01b6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs @@ -0,0 +1,230 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections.Generic; +using UnityEngine; +using System; + +namespace Spine.Unity.Deprecated { + + /// + /// Deprecated. The spine-unity 3.7 runtime introduced SkeletonDataModifierAssets BlendModeMaterials which replaced SlotBlendModes. See the + /// SkeletonDataModifierAssets BlendModeMaterials documentation page and + /// this forum thread for further information. + /// This class will be removed in the spine-unity 3.9 runtime. + /// + [Obsolete("The spine-unity 3.7 runtime introduced SkeletonDataModifierAssets BlendModeMaterials which replaced SlotBlendModes. Will be removed in spine-unity 3.9.", false)] + [DisallowMultipleComponent] + public class SlotBlendModes : MonoBehaviour { + + #region Internal Material Dictionary + public struct MaterialTexturePair { + public Texture2D texture2D; + public Material material; + } + + internal class MaterialWithRefcount { + public Material materialClone; + public int refcount = 1; + + public MaterialWithRefcount(Material mat) { + this.materialClone = mat; + } + } + static Dictionary materialTable; + internal static Dictionary MaterialTable { + get { + if (materialTable == null) materialTable = new Dictionary(); + return materialTable; + } + } + + internal struct SlotMaterialTextureTuple { + public Slot slot; + public Texture2D texture2D; + public Material material; + + public SlotMaterialTextureTuple(Slot slot, Material material, Texture2D texture) { + this.slot = slot; + this.material = material; + this.texture2D = texture; + } + } + + internal static Material GetOrAddMaterialFor(Material materialSource, Texture2D texture) { + if (materialSource == null || texture == null) return null; + + var mt = SlotBlendModes.MaterialTable; + MaterialWithRefcount matWithRefcount; + var key = new MaterialTexturePair { material = materialSource, texture2D = texture }; + if (!mt.TryGetValue(key, out matWithRefcount)) { + matWithRefcount = new MaterialWithRefcount(new Material(materialSource)); + var m = matWithRefcount.materialClone; + m.name = "(Clone)" + texture.name + "-" + materialSource.name; + m.mainTexture = texture; + mt[key] = matWithRefcount; + } + else { + matWithRefcount.refcount++; + } + return matWithRefcount.materialClone; + } + + internal static MaterialWithRefcount GetExistingMaterialFor(Material materialSource, Texture2D texture) + { + if (materialSource == null || texture == null) return null; + + var mt = SlotBlendModes.MaterialTable; + MaterialWithRefcount matWithRefcount; + var key = new MaterialTexturePair { material = materialSource, texture2D = texture }; + if (!mt.TryGetValue(key, out matWithRefcount)) { + return null; + } + return matWithRefcount; + } + + internal static void RemoveMaterialFromTable(Material materialSource, Texture2D texture) { + var mt = SlotBlendModes.MaterialTable; + var key = new MaterialTexturePair { material = materialSource, texture2D = texture }; + mt.Remove(key); + } + #endregion + + #region Inspector + public Material multiplyMaterialSource; + public Material screenMaterialSource; + + Texture2D texture; + #endregion + + SlotMaterialTextureTuple[] slotsWithCustomMaterial = new SlotMaterialTextureTuple[0]; + + public bool Applied { get; private set; } + + void Start() { + if (!Applied) Apply(); + } + + void OnDestroy() { + if (Applied) Remove(); + } + + public void Apply() { + GetTexture(); + if (texture == null) return; + + var skeletonRenderer = GetComponent(); + if (skeletonRenderer == null) return; + + var slotMaterials = skeletonRenderer.CustomSlotMaterials; + + int numSlotsWithCustomMaterial = 0; + foreach (var s in skeletonRenderer.Skeleton.Slots) { + switch (s.data.blendMode) { + case BlendMode.Multiply: + if (multiplyMaterialSource != null) { + slotMaterials[s] = GetOrAddMaterialFor(multiplyMaterialSource, texture); + ++numSlotsWithCustomMaterial; + } + break; + case BlendMode.Screen: + if (screenMaterialSource != null) { + slotMaterials[s] = GetOrAddMaterialFor(screenMaterialSource, texture); + ++numSlotsWithCustomMaterial; + } + break; + } + } + slotsWithCustomMaterial = new SlotMaterialTextureTuple[numSlotsWithCustomMaterial]; + int storedSlotIndex = 0; + foreach (var s in skeletonRenderer.Skeleton.Slots) { + switch (s.data.blendMode) { + case BlendMode.Multiply: + if (multiplyMaterialSource != null) { + slotsWithCustomMaterial[storedSlotIndex++] = new SlotMaterialTextureTuple(s, multiplyMaterialSource, texture); + } + break; + case BlendMode.Screen: + if (screenMaterialSource != null) { + slotsWithCustomMaterial[storedSlotIndex++] = new SlotMaterialTextureTuple(s, screenMaterialSource, texture); + } + break; + } + } + + Applied = true; + skeletonRenderer.LateUpdate(); + } + + public void Remove() { + GetTexture(); + if (texture == null) return; + + var skeletonRenderer = GetComponent(); + if (skeletonRenderer == null) return; + + var slotMaterials = skeletonRenderer.CustomSlotMaterials; + + foreach (var slotWithCustomMat in slotsWithCustomMaterial) { + + Slot s = slotWithCustomMat.slot; + Material storedMaterialSource = slotWithCustomMat.material; + Texture2D storedTexture = slotWithCustomMat.texture2D; + + var matWithRefcount = GetExistingMaterialFor(storedMaterialSource, storedTexture); + if (--matWithRefcount.refcount == 0) { + RemoveMaterialFromTable(storedMaterialSource, storedTexture); + } + // we don't want to remove slotMaterials[s] if it has been changed in the meantime. + Material m; + if (slotMaterials.TryGetValue(s, out m)) { + var existingMat = matWithRefcount == null ? null : matWithRefcount.materialClone; + if (Material.ReferenceEquals(m, existingMat)) { + slotMaterials.Remove(s); + } + } + } + slotsWithCustomMaterial = null; + + Applied = false; + if (skeletonRenderer.valid) skeletonRenderer.LateUpdate(); + } + + public void GetTexture() { + if (texture == null) { + var sr = GetComponent(); if (sr == null) return; + var sda = sr.skeletonDataAsset; if (sda == null) return; + var aa = sda.atlasAssets[0]; if (aa == null) return; + var am = aa.PrimaryMaterial; if (am == null) return; + texture = am.mainTexture as Texture2D; + } + } + + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs.meta new file mode 100644 index 0000000..6750f11 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Deprecated/SlotBlendModes/SlotBlendModes.cs.meta @@ -0,0 +1,16 @@ +fileFormatVersion: 2 +guid: f1f8243645ba2e74aa3564bd956eed89 +timeCreated: 1496794038 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: + - multiplyMaterialSource: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df, + type: 2} + - screenMaterialSource: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be, + type: 2} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs new file mode 100644 index 0000000..90486e3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs @@ -0,0 +1,81 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine.Unity { + public enum UpdateMode { + Nothing = 0, + OnlyAnimationStatus, + OnlyEventTimelines = 4, // added as index 4 to keep scene behavior unchanged. + EverythingExceptMesh = 2, + FullUpdate, + //Reserved 4 for OnlyEventTimelines + }; + + public delegate void UpdateBonesDelegate (ISkeletonAnimation animated); + + /// A Spine-Unity Component that animates a Skeleton but not necessarily with a Spine.AnimationState. + public interface ISkeletonAnimation { + event UpdateBonesDelegate UpdateLocal; + event UpdateBonesDelegate UpdateWorld; + event UpdateBonesDelegate UpdateComplete; + Skeleton Skeleton { get; } + } + + /// Holds a reference to a SkeletonDataAsset. + public interface IHasSkeletonDataAsset { + /// Gets the SkeletonDataAsset of the Spine Component. + SkeletonDataAsset SkeletonDataAsset { get; } + } + + /// A Spine-Unity Component that manages a Spine.Skeleton instance, instantiated from a SkeletonDataAsset. + public interface ISkeletonComponent { + /// Gets the SkeletonDataAsset of the Spine Component. + //[System.Obsolete] + SkeletonDataAsset SkeletonDataAsset { get; } + + /// Gets the Spine.Skeleton instance of the Spine Component. This is equivalent to SkeletonRenderer's .skeleton. + Skeleton Skeleton { get; } + } + + /// A Spine-Unity Component that uses a Spine.AnimationState to animate its skeleton. + public interface IAnimationStateComponent { + /// Gets the Spine.AnimationState of the animated Spine Component. This is equivalent to SkeletonAnimation.state. + AnimationState AnimationState { get; } + } + + /// A Spine-Unity Component that holds a reference to a SkeletonRenderer. + public interface IHasSkeletonRenderer { + SkeletonRenderer SkeletonRenderer { get; } + } + + /// A Spine-Unity Component that holds a reference to an ISkeletonComponent. + public interface IHasSkeletonComponent { + ISkeletonComponent SkeletonComponent { get; } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs.meta new file mode 100644 index 0000000..68e421f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/ISkeletonAnimation.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a7b480b941568134891f411137bfbf55 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials.meta new file mode 100644 index 0000000..da6d0a2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 43897010c7e77c54897cb98c1ddf84f1 +folderAsset: yes +timeCreated: 1455128695 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat new file mode 100644 index 0000000..08d7764 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat @@ -0,0 +1,87 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonGraphicDefault + m_Shader: {fileID: 4800000, guid: fa95b0fb6983c0f40a152e6f9aa82bfb, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 5 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _AlphaTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - PixelSnap: 0 + - _BumpScale: 1 + - _ColorMask: 15 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _EnableExternalAlpha: 0 + - _Glossiness: 0.5 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SrcBlend: 1 + - _Stencil: 0 + - _StencilComp: 8 + - _StencilOp: 0 + - _StencilReadMask: 255 + - _StencilWriteMask: 255 + - _UVSec: 0 + - _UseUIAlphaClip: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + - _Flip: {r: 1, g: 1, b: 1, a: 1} + - _RendererColor: {r: 1, g: 1, b: 1, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat.meta new file mode 100644 index 0000000..aaa80ff --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefault.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b66cf7a186d13054989b33a5c90044e4 +timeCreated: 1455140322 +licenseType: Free +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat new file mode 100644 index 0000000..7082bbf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat @@ -0,0 +1,95 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonGraphicDefaultOutline + m_Shader: {fileID: 4800000, guid: 8f5d14d2a7fedb84998c50eb96c8b748, type: 3} + m_ShaderKeywords: _USE8NEIGHBOURHOOD_ON + m_LightmapFlags: 5 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _AlphaTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - PixelSnap: 0 + - _BumpScale: 1 + - _ColorMask: 15 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _EnableExternalAlpha: 0 + - _Glossiness: 0.5 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _OutlineMipLevel: 0 + - _OutlineReferenceTexWidth: 1024 + - _OutlineSmoothness: 1 + - _OutlineWidth: 3 + - _Parallax: 0.02 + - _SrcBlend: 1 + - _Stencil: 0 + - _StencilComp: 8 + - _StencilOp: 0 + - _StencilReadMask: 255 + - _StencilWriteMask: 255 + - _StraightAlphaInput: 0 + - _ThresholdEnd: 0.25 + - _UVSec: 0 + - _Use8Neighbourhood: 1 + - _UseUIAlphaClip: 0 + - _ZWrite: 1 + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + - _Flip: {r: 1, g: 1, b: 1, a: 1} + - _OutlineColor: {r: 1, g: 1, b: 0, a: 1} + - _RendererColor: {r: 1, g: 1, b: 1, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat.meta new file mode 100644 index 0000000..beaf12d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicDefaultOutline.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c4ee0f8f4be17434aa3df5774a03b366 +timeCreated: 1455140322 +licenseType: Free +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat new file mode 100644 index 0000000..d78d415 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat @@ -0,0 +1,79 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonGraphicTintBlack + m_Shader: {fileID: 4800000, guid: f64c7bc238bb2c246b8ca1912b2b6b9c, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 5 + m_EnableInstancingVariants: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - _BumpScale: 1 + - _ColorMask: 15 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _Glossiness: 0.5 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _Parallax: 0.02 + - _SrcBlend: 1 + - _Stencil: 0 + - _StencilComp: 8 + - _StencilOp: 0 + - _StencilReadMask: 255 + - _StencilWriteMask: 255 + - _UVSec: 0 + - _UseUIAlphaClip: 0 + - _ZWrite: 1 + m_Colors: + - _Black: {r: 0, g: 0, b: 0, a: 0} + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat.meta new file mode 100644 index 0000000..0d83b23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlack.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cfcea0e11aa80bb4b8d05790b905fc31 +timeCreated: 1455140322 +licenseType: Free +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat new file mode 100644 index 0000000..30d42c7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat @@ -0,0 +1,88 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonGraphicTintBlackOutline + m_Shader: {fileID: 4800000, guid: d55d64dd09c46af40a319933a62fa1b2, type: 3} + m_ShaderKeywords: _USE8NEIGHBOURHOOD_ON + m_LightmapFlags: 5 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailAlbedoMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailMask: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _DetailNormalMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _EmissionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MetallicGlossMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _OcclusionMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _ParallaxMap: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - _BumpScale: 1 + - _ColorMask: 15 + - _Cutoff: 0.5 + - _DetailNormalMapScale: 1 + - _DstBlend: 0 + - _Glossiness: 0.5 + - _Metallic: 0 + - _Mode: 0 + - _OcclusionStrength: 1 + - _OutlineMipLevel: 0 + - _OutlineReferenceTexWidth: 1024 + - _OutlineSmoothness: 1 + - _OutlineWidth: 3 + - _Parallax: 0.02 + - _SrcBlend: 1 + - _Stencil: 0 + - _StencilComp: 8 + - _StencilOp: 0 + - _StencilReadMask: 255 + - _StencilWriteMask: 255 + - _StraightAlphaInput: 0 + - _ThresholdEnd: 0.25 + - _UVSec: 0 + - _Use8Neighbourhood: 1 + - _UseUIAlphaClip: 0 + - _ZWrite: 1 + m_Colors: + - _Black: {r: 0, g: 0, b: 0, a: 0} + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} + - _OutlineColor: {r: 1, g: 1, b: 0, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat.meta new file mode 100644 index 0000000..a884c7e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Materials/SkeletonGraphicTintBlackOutline.mat.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 94fe565c79b0aeb418cd05e4f1f8343c +timeCreated: 1455140322 +licenseType: Free +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation.meta new file mode 100644 index 0000000..ae63350 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c5d065c4fe677ad4495a852580ec32fa +folderAsset: yes +timeCreated: 1455493477 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs new file mode 100644 index 0000000..9b2c8d9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs @@ -0,0 +1,45 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +namespace Spine.Unity { + public class DoubleBuffered where T : new() { + readonly T a = new T(); + readonly T b = new T(); + bool usingA; + + public T GetCurrent () { + return usingA ? a : b; + } + + public T GetNext () { + usingA = !usingA; + return usingA ? a : b; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs.meta new file mode 100644 index 0000000..2e570e4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/DoubleBuffered.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 08b76da7751523448a87e528c48a5399 +timeCreated: 1457396939 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs new file mode 100644 index 0000000..6827dc7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs @@ -0,0 +1,1387 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2019_3_OR_NEWER +#define MESH_SET_TRIANGLES_PROVIDES_LENGTH_PARAM +#endif + +// Not for optimization. Do not disable. +#define SPINE_TRIANGLECHECK // Avoid calling SetTriangles at the cost of checking for mesh differences (vertex counts, memberwise attachment list compare) every frame. +//#define SPINE_DEBUG + +using UnityEngine; +using System; +using System.Collections.Generic; + +namespace Spine.Unity { + public delegate void MeshGeneratorDelegate (MeshGeneratorBuffers buffers); + public struct MeshGeneratorBuffers { + /// The vertex count that will actually be used for the mesh. The Lengths of the buffer arrays may be larger than this number. + public int vertexCount; + + /// Vertex positions. To be used for UnityEngine.Mesh.vertices. + public Vector3[] vertexBuffer; + + /// Vertex UVs. To be used for UnityEngine.Mesh.uvs. + public Vector2[] uvBuffer; + + /// Vertex colors. To be used for UnityEngine.Mesh.colors32. + public Color32[] colorBuffer; + + /// The Spine rendering component's MeshGenerator. + public MeshGenerator meshGenerator; + } + + /// Holds several methods to prepare and generate a UnityEngine mesh based on a skeleton. Contains buffers needed to perform the operation, and serializes settings for mesh generation. + [System.Serializable] + public class MeshGenerator { + public Settings settings = Settings.Default; + + [System.Serializable] + public struct Settings { + public bool useClipping; + [Space] + [Range(-0.1f, 0f)] public float zSpacing; + [Space] + [Header("Vertex Data")] + public bool pmaVertexColors; + public bool tintBlack; + [Tooltip("Enable when using Additive blend mode at SkeletonGraphic under a CanvasGroup. " + + "When enabled, Additive alpha value is stored at uv2.g instead of color.a to capture CanvasGroup modifying color.a.")] + public bool canvasGroupTintBlack; + public bool calculateTangents; + public bool addNormals; + public bool immutableTriangles; + + static public Settings Default { + get { + return new Settings { + pmaVertexColors = true, + zSpacing = 0f, + useClipping = true, + tintBlack = false, + calculateTangents = false, + //renderMeshes = true, + addNormals = false, + immutableTriangles = false + }; + } + } + } + + const float BoundsMinDefault = float.PositiveInfinity; + const float BoundsMaxDefault = float.NegativeInfinity; + + [NonSerialized] readonly ExposedList vertexBuffer = new ExposedList(4); + [NonSerialized] readonly ExposedList uvBuffer = new ExposedList(4); + [NonSerialized] readonly ExposedList colorBuffer = new ExposedList(4); + [NonSerialized] readonly ExposedList> submeshes = new ExposedList> { new ExposedList(6) }; // start with 1 submesh. + + [NonSerialized] Vector2 meshBoundsMin, meshBoundsMax; + [NonSerialized] float meshBoundsThickness; + [NonSerialized] int submeshIndex = 0; + + [NonSerialized] SkeletonClipping clipper = new SkeletonClipping(); + [NonSerialized] float[] tempVerts = new float[8]; + [NonSerialized] int[] regionTriangles = { 0, 1, 2, 2, 3, 0 }; + + #region Optional Buffers + // These optional buffers are lazy-instantiated when the feature is used. + [NonSerialized] Vector3[] normals; + [NonSerialized] Vector4[] tangents; + [NonSerialized] Vector2[] tempTanBuffer; + [NonSerialized] ExposedList uv2; + [NonSerialized] ExposedList uv3; + #endregion + + public int VertexCount { get { return vertexBuffer.Count; } } + + /// A set of mesh arrays whose values are modifiable by the user. Modify these values before they are passed to the UnityEngine mesh object in order to see the effect. + public MeshGeneratorBuffers Buffers { + get { + return new MeshGeneratorBuffers { + vertexCount = this.VertexCount, + vertexBuffer = this.vertexBuffer.Items, + uvBuffer = this.uvBuffer.Items, + colorBuffer = this.colorBuffer.Items, + meshGenerator = this + }; + } + } + + public MeshGenerator () { + submeshes.TrimExcess(); + } + + #region Step 1 : Generate Instructions + /// + /// A specialized variant of . + /// Generates renderer instructions using a single submesh, using only a single material and texture. + /// + /// The resulting instructions. + /// The skeleton to generate renderer instructions for. + /// Material to be set at the renderer instruction. When null, the last attachment + /// in the draw order list is assigned as the instruction's material. + public static void GenerateSingleSubmeshInstruction (SkeletonRendererInstruction instructionOutput, Skeleton skeleton, Material material) { + ExposedList drawOrder = skeleton.drawOrder; + int drawOrderCount = drawOrder.Count; + + // Clear last state of attachments and submeshes + instructionOutput.Clear(); // submeshInstructions.Clear(); attachments.Clear(); + var workingSubmeshInstructions = instructionOutput.submeshInstructions; + + #if SPINE_TRIANGLECHECK + instructionOutput.attachments.Resize(drawOrderCount); + var workingAttachmentsItems = instructionOutput.attachments.Items; + int totalRawVertexCount = 0; + #endif + + var current = new SubmeshInstruction { + skeleton = skeleton, + preActiveClippingSlotSource = -1, + startSlot = 0, + #if SPINE_TRIANGLECHECK + rawFirstVertexIndex = 0, + #endif + material = material, + forceSeparate = false, + endSlot = drawOrderCount + }; + + #if SPINE_TRIANGLECHECK + object rendererObject = null; + bool skeletonHasClipping = false; + var drawOrderItems = drawOrder.Items; + for (int i = 0; i < drawOrderCount; i++) { + Slot slot = drawOrderItems[i]; + if (!slot.bone.active) { + workingAttachmentsItems[i] = null; + continue; + } + Attachment attachment = slot.attachment; + + workingAttachmentsItems[i] = attachment; + int attachmentTriangleCount; + int attachmentVertexCount; + + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) { + rendererObject = regionAttachment.RendererObject; + attachmentVertexCount = 4; + attachmentTriangleCount = 6; + } else { + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + rendererObject = meshAttachment.RendererObject; + attachmentVertexCount = meshAttachment.worldVerticesLength >> 1; + attachmentTriangleCount = meshAttachment.triangles.Length; + } else { + var clippingAttachment = attachment as ClippingAttachment; + if (clippingAttachment != null) { + current.hasClipping = true; + skeletonHasClipping = true; + } + attachmentVertexCount = 0; + attachmentTriangleCount = 0; + } + } + current.rawTriangleCount += attachmentTriangleCount; + current.rawVertexCount += attachmentVertexCount; + totalRawVertexCount += attachmentVertexCount; + } + + #if !SPINE_TK2D + if (material == null && rendererObject != null) + current.material = (Material)((AtlasRegion)rendererObject).page.rendererObject; + #else + if (material == null && rendererObject != null) + current.material = (rendererObject is Material) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; + #endif + + instructionOutput.hasActiveClipping = skeletonHasClipping; + instructionOutput.rawVertexCount = totalRawVertexCount; + #endif + + if (totalRawVertexCount > 0) { + workingSubmeshInstructions.Resize(1); + workingSubmeshInstructions.Items[0] = current; + } + else { + workingSubmeshInstructions.Resize(0); + } + } + + public static bool RequiresMultipleSubmeshesByDrawOrder (Skeleton skeleton) { + + #if SPINE_TK2D + return false; + #endif + ExposedList drawOrder = skeleton.drawOrder; + int drawOrderCount = drawOrder.Count; + var drawOrderItems = drawOrder.Items; + + Material lastRendererMaterial = null; + for (int i = 0; i < drawOrderCount; i++) { + Slot slot = drawOrderItems[i]; + if (!slot.bone.active) continue; + Attachment attachment = slot.attachment; + var rendererAttachment = attachment as IHasRendererObject; + if (rendererAttachment != null) { + AtlasRegion atlasRegion = (AtlasRegion)rendererAttachment.RendererObject; + Material material = (Material)atlasRegion.page.rendererObject; + if (lastRendererMaterial != material) { + if (lastRendererMaterial != null) + return true; + else + lastRendererMaterial = material; + } + } + } + return false; + } + + public static void GenerateSkeletonRendererInstruction (SkeletonRendererInstruction instructionOutput, Skeleton skeleton, Dictionary customSlotMaterials, List separatorSlots, bool generateMeshOverride, bool immutableTriangles = false) { + // if (skeleton == null) throw new ArgumentNullException("skeleton"); + // if (instructionOutput == null) throw new ArgumentNullException("instructionOutput"); + + ExposedList drawOrder = skeleton.drawOrder; + int drawOrderCount = drawOrder.Count; + + // Clear last state of attachments and submeshes + instructionOutput.Clear(); // submeshInstructions.Clear(); attachments.Clear(); + var workingSubmeshInstructions = instructionOutput.submeshInstructions; + #if SPINE_TRIANGLECHECK + instructionOutput.attachments.Resize(drawOrderCount); + var workingAttachmentsItems = instructionOutput.attachments.Items; + int totalRawVertexCount = 0; + bool skeletonHasClipping = false; + #endif + + var current = new SubmeshInstruction { + skeleton = skeleton, + preActiveClippingSlotSource = -1 + }; + + #if !SPINE_TK2D + bool isCustomSlotMaterialsPopulated = customSlotMaterials != null && customSlotMaterials.Count > 0; + #endif + + int separatorCount = separatorSlots == null ? 0 : separatorSlots.Count; + bool hasSeparators = separatorCount > 0; + + int clippingAttachmentSource = -1; + int lastPreActiveClipping = -1; // The index of the last slot that had an active ClippingAttachment. + SlotData clippingEndSlot = null; + int submeshIndex = 0; + var drawOrderItems = drawOrder.Items; + for (int i = 0; i < drawOrderCount; i++) { + Slot slot = drawOrderItems[i]; + if (!slot.bone.active) { + workingAttachmentsItems[i] = null; + continue; + } + Attachment attachment = slot.attachment; + #if SPINE_TRIANGLECHECK + workingAttachmentsItems[i] = attachment; + int attachmentVertexCount = 0, attachmentTriangleCount = 0; + #endif + + object rendererObject = null; // An AtlasRegion in plain Spine-Unity. Spine-TK2D hooks into TK2D's system. eventual source of Material object. + bool noRender = false; // Using this allows empty slots as separators, and keeps separated parts more stable despite slots being reordered + + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) { + rendererObject = regionAttachment.RendererObject; + #if SPINE_TRIANGLECHECK + attachmentVertexCount = 4; + attachmentTriangleCount = 6; + #endif + } else { + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + rendererObject = meshAttachment.RendererObject; + #if SPINE_TRIANGLECHECK + attachmentVertexCount = meshAttachment.worldVerticesLength >> 1; + attachmentTriangleCount = meshAttachment.triangles.Length; + #endif + } else { + #if SPINE_TRIANGLECHECK + var clippingAttachment = attachment as ClippingAttachment; + if (clippingAttachment != null) { + clippingEndSlot = clippingAttachment.endSlot; + clippingAttachmentSource = i; + current.hasClipping = true; + skeletonHasClipping = true; + } + #endif + noRender = true; + } + } + + // Create a new SubmeshInstruction when material changes. (or when forced to separate by a submeshSeparator) + // Slot with a separator/new material will become the starting slot of the next new instruction. + if (hasSeparators) { //current.forceSeparate = hasSeparators && separatorSlots.Contains(slot); + current.forceSeparate = false; + for (int s = 0; s < separatorCount; s++) { + if (Slot.ReferenceEquals(slot, separatorSlots[s])) { + current.forceSeparate = true; + break; + } + } + } + + if (noRender) { + if (current.forceSeparate && generateMeshOverride) { // && current.rawVertexCount > 0) { + { // Add + current.endSlot = i; + current.preActiveClippingSlotSource = lastPreActiveClipping; + + workingSubmeshInstructions.Resize(submeshIndex + 1); + workingSubmeshInstructions.Items[submeshIndex] = current; + + submeshIndex++; + } + + current.startSlot = i; + lastPreActiveClipping = clippingAttachmentSource; + #if SPINE_TRIANGLECHECK + current.rawTriangleCount = 0; + current.rawVertexCount = 0; + current.rawFirstVertexIndex = totalRawVertexCount; + current.hasClipping = clippingAttachmentSource >= 0; + #endif + } + } else { + #if !SPINE_TK2D + Material material; + if (isCustomSlotMaterialsPopulated) { + if (!customSlotMaterials.TryGetValue(slot, out material)) + material = (Material)((AtlasRegion)rendererObject).page.rendererObject; + } else { + material = (Material)((AtlasRegion)rendererObject).page.rendererObject; + } + #else + Material material = (rendererObject is Material) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; + #endif + + if (current.forceSeparate || (current.rawVertexCount > 0 && !System.Object.ReferenceEquals(current.material, material))) { // Material changed. Add the previous submesh. + { // Add + current.endSlot = i; + current.preActiveClippingSlotSource = lastPreActiveClipping; + + workingSubmeshInstructions.Resize(submeshIndex + 1); + workingSubmeshInstructions.Items[submeshIndex] = current; + submeshIndex++; + } + current.startSlot = i; + lastPreActiveClipping = clippingAttachmentSource; + #if SPINE_TRIANGLECHECK + current.rawTriangleCount = 0; + current.rawVertexCount = 0; + current.rawFirstVertexIndex = totalRawVertexCount; + current.hasClipping = clippingAttachmentSource >= 0; + #endif + } + + // Update state for the next Attachment. + current.material = material; + #if SPINE_TRIANGLECHECK + current.rawTriangleCount += attachmentTriangleCount; + current.rawVertexCount += attachmentVertexCount; + current.rawFirstVertexIndex = totalRawVertexCount; + totalRawVertexCount += attachmentVertexCount; + #endif + } + + if (clippingEndSlot != null && slot.data == clippingEndSlot && i != clippingAttachmentSource) { + clippingEndSlot = null; + clippingAttachmentSource = -1; + } + } + + if (current.rawVertexCount > 0) { + { // Add last or only submesh. + current.endSlot = drawOrderCount; + current.preActiveClippingSlotSource = lastPreActiveClipping; + current.forceSeparate = false; + + workingSubmeshInstructions.Resize(submeshIndex + 1); + workingSubmeshInstructions.Items[submeshIndex] = current; + //submeshIndex++; + } + } + + #if SPINE_TRIANGLECHECK + instructionOutput.hasActiveClipping = skeletonHasClipping; + instructionOutput.rawVertexCount = totalRawVertexCount; + #endif + instructionOutput.immutableTriangles = immutableTriangles; + } + + public static void TryReplaceMaterials (ExposedList workingSubmeshInstructions, Dictionary customMaterialOverride) { + // Material overrides are done here so they can be applied per submesh instead of per slot + // but they will still be passed through the GenerateMeshOverride delegate, + // and will still go through the normal material match check step in STEP 3. + var wsii = workingSubmeshInstructions.Items; + for (int i = 0; i < workingSubmeshInstructions.Count; i++) { + var m = wsii[i].material; + Material mo; + if (customMaterialOverride.TryGetValue(m, out mo)) + wsii[i].material = mo; + } + } + #endregion + + #region Step 2 : Populate vertex data and triangle index buffers. + public void Begin () { + vertexBuffer.Clear(false); + colorBuffer.Clear(false); + uvBuffer.Clear(false); + clipper.ClipEnd(); + + { + meshBoundsMin.x = BoundsMinDefault; + meshBoundsMin.y = BoundsMinDefault; + meshBoundsMax.x = BoundsMaxDefault; + meshBoundsMax.y = BoundsMaxDefault; + meshBoundsThickness = 0f; + } + + submeshIndex = 0; + submeshes.Count = 1; + //submeshes.Items[0].Clear(false); + } + + public void AddSubmesh (SubmeshInstruction instruction, bool updateTriangles = true) { + var settings = this.settings; + + int newSubmeshCount = submeshIndex + 1; + if (submeshes.Items.Length < newSubmeshCount) + submeshes.Resize(newSubmeshCount); + submeshes.Count = newSubmeshCount; + var submesh = submeshes.Items[submeshIndex]; + if (submesh == null) + submeshes.Items[submeshIndex] = submesh = new ExposedList(); + submesh.Clear(false); + + var skeleton = instruction.skeleton; + var drawOrderItems = skeleton.drawOrder.Items; + + Color32 color = default(Color32); + float skeletonA = skeleton.a, skeletonR = skeleton.r, skeletonG = skeleton.g, skeletonB = skeleton.b; + Vector2 meshBoundsMin = this.meshBoundsMin, meshBoundsMax = this.meshBoundsMax; + + // Settings + float zSpacing = settings.zSpacing; + bool pmaVertexColors = settings.pmaVertexColors; + bool tintBlack = settings.tintBlack; + #if SPINE_TRIANGLECHECK + bool useClipping = settings.useClipping && instruction.hasClipping; + #else + bool useClipping = settings.useClipping; + #endif + bool canvasGroupTintBlack = settings.tintBlack && settings.canvasGroupTintBlack; + + if (useClipping) { + if (instruction.preActiveClippingSlotSource >= 0) { + var slot = drawOrderItems[instruction.preActiveClippingSlotSource]; + clipper.ClipStart(slot, slot.attachment as ClippingAttachment); + } + } + + for (int slotIndex = instruction.startSlot; slotIndex < instruction.endSlot; slotIndex++) { + var slot = drawOrderItems[slotIndex]; + if (!slot.bone.active) { + clipper.ClipEnd(slot); + continue; + } + var attachment = slot.attachment; + float z = zSpacing * slotIndex; + + var workingVerts = this.tempVerts; + float[] uvs; + int[] attachmentTriangleIndices; + int attachmentVertexCount; + int attachmentIndexCount; + + Color c = default(Color); + + // Identify and prepare values. + var region = attachment as RegionAttachment; + if (region != null) { + region.ComputeWorldVertices(slot.bone, workingVerts, 0); + uvs = region.uvs; + attachmentTriangleIndices = regionTriangles; + c.r = region.r; c.g = region.g; c.b = region.b; c.a = region.a; + attachmentVertexCount = 4; + attachmentIndexCount = 6; + } else { + var mesh = attachment as MeshAttachment; + if (mesh != null) { + int meshVerticesLength = mesh.worldVerticesLength; + if (workingVerts.Length < meshVerticesLength) { + workingVerts = new float[meshVerticesLength]; + this.tempVerts = workingVerts; + } + mesh.ComputeWorldVertices(slot, 0, meshVerticesLength, workingVerts, 0); //meshAttachment.ComputeWorldVertices(slot, tempVerts); + uvs = mesh.uvs; + attachmentTriangleIndices = mesh.triangles; + c.r = mesh.r; c.g = mesh.g; c.b = mesh.b; c.a = mesh.a; + attachmentVertexCount = meshVerticesLength >> 1; // meshVertexCount / 2; + attachmentIndexCount = mesh.triangles.Length; + } else { + if (useClipping) { + var clippingAttachment = attachment as ClippingAttachment; + if (clippingAttachment != null) { + clipper.ClipStart(slot, clippingAttachment); + continue; + } + } + + // If not any renderable attachment. + clipper.ClipEnd(slot); + continue; + } + } + + float tintBlackAlpha = 1.0f; + if (pmaVertexColors) { + color.a = (byte)(skeletonA * slot.a * c.a * 255); + color.r = (byte)(skeletonR * slot.r * c.r * color.a); + color.g = (byte)(skeletonG * slot.g * c.g * color.a); + color.b = (byte)(skeletonB * slot.b * c.b * color.a); + if (slot.data.blendMode == BlendMode.Additive) { + if (canvasGroupTintBlack) + tintBlackAlpha = 0; + else + color.a = 0; + } + } else { + color.a = (byte)(skeletonA * slot.a * c.a * 255); + color.r = (byte)(skeletonR * slot.r * c.r * 255); + color.g = (byte)(skeletonG * slot.g * c.g * 255); + color.b = (byte)(skeletonB * slot.b * c.b * 255); + } + + if (useClipping && clipper.IsClipping) { + clipper.ClipTriangles(workingVerts, attachmentVertexCount << 1, attachmentTriangleIndices, attachmentIndexCount, uvs); + workingVerts = clipper.clippedVertices.Items; + attachmentVertexCount = clipper.clippedVertices.Count >> 1; + attachmentTriangleIndices = clipper.clippedTriangles.Items; + attachmentIndexCount = clipper.clippedTriangles.Count; + uvs = clipper.clippedUVs.Items; + } + + // Actually add slot/attachment data into buffers. + if (attachmentVertexCount != 0 && attachmentIndexCount != 0) { + if (tintBlack) { + float r2 = slot.r2; + float g2 = slot.g2; + float b2 = slot.b2; + if (pmaVertexColors) { + float alpha = skeletonA * slot.a * c.a; + r2 *= alpha; + g2 *= alpha; + b2 *= alpha; + } + AddAttachmentTintBlack(r2, g2, b2, tintBlackAlpha, attachmentVertexCount); + } + + //AddAttachment(workingVerts, uvs, color, attachmentTriangleIndices, attachmentVertexCount, attachmentIndexCount, ref meshBoundsMin, ref meshBoundsMax, z); + int ovc = vertexBuffer.Count; + // Add data to vertex buffers + { + int newVertexCount = ovc + attachmentVertexCount; + int oldArraySize = vertexBuffer.Items.Length; + if (newVertexCount > oldArraySize) { + int newArraySize = (int)(oldArraySize * 1.3f); + if (newArraySize < newVertexCount) newArraySize = newVertexCount; + Array.Resize(ref vertexBuffer.Items, newArraySize); + Array.Resize(ref uvBuffer.Items, newArraySize); + Array.Resize(ref colorBuffer.Items, newArraySize); + } + vertexBuffer.Count = uvBuffer.Count = colorBuffer.Count = newVertexCount; + } + + var vbi = vertexBuffer.Items; + var ubi = uvBuffer.Items; + var cbi = colorBuffer.Items; + if (ovc == 0) { + for (int i = 0; i < attachmentVertexCount; i++) { + int vi = ovc + i; + int i2 = i << 1; // i * 2 + float x = workingVerts[i2]; + float y = workingVerts[i2 + 1]; + + vbi[vi].x = x; + vbi[vi].y = y; + vbi[vi].z = z; + ubi[vi].x = uvs[i2]; + ubi[vi].y = uvs[i2 + 1]; + cbi[vi] = color; + + // Calculate bounds. + if (x < meshBoundsMin.x) meshBoundsMin.x = x; + if (x > meshBoundsMax.x) meshBoundsMax.x = x; + if (y < meshBoundsMin.y) meshBoundsMin.y = y; + if (y > meshBoundsMax.y) meshBoundsMax.y = y; + } + } else { + for (int i = 0; i < attachmentVertexCount; i++) { + int vi = ovc + i; + int i2 = i << 1; // i * 2 + float x = workingVerts[i2]; + float y = workingVerts[i2 + 1]; + + vbi[vi].x = x; + vbi[vi].y = y; + vbi[vi].z = z; + ubi[vi].x = uvs[i2]; + ubi[vi].y = uvs[i2 + 1]; + cbi[vi] = color; + + // Calculate bounds. + if (x < meshBoundsMin.x) meshBoundsMin.x = x; + else if (x > meshBoundsMax.x) meshBoundsMax.x = x; + if (y < meshBoundsMin.y) meshBoundsMin.y = y; + else if (y > meshBoundsMax.y) meshBoundsMax.y = y; + } + } + + + // Add data to triangle buffer + if (updateTriangles) { + int oldTriangleCount = submesh.Count; + { //submesh.Resize(oldTriangleCount + attachmentIndexCount); + int newTriangleCount = oldTriangleCount + attachmentIndexCount; + if (newTriangleCount > submesh.Items.Length) Array.Resize(ref submesh.Items, newTriangleCount); + submesh.Count = newTriangleCount; + } + var submeshItems = submesh.Items; + for (int i = 0; i < attachmentIndexCount; i++) + submeshItems[oldTriangleCount + i] = attachmentTriangleIndices[i] + ovc; + } + } + + clipper.ClipEnd(slot); + } + clipper.ClipEnd(); + + this.meshBoundsMin = meshBoundsMin; + this.meshBoundsMax = meshBoundsMax; + meshBoundsThickness = instruction.endSlot * zSpacing; + + // Trim or zero submesh triangles. + var currentSubmeshItems = submesh.Items; + for (int i = submesh.Count, n = currentSubmeshItems.Length; i < n; i++) + currentSubmeshItems[i] = 0; + + submeshIndex++; // Next AddSubmesh will use a new submeshIndex value. + } + + public void BuildMesh (SkeletonRendererInstruction instruction, bool updateTriangles) { + var wsii = instruction.submeshInstructions.Items; + for (int i = 0, n = instruction.submeshInstructions.Count; i < n; i++) + this.AddSubmesh(wsii[i], updateTriangles); + } + + // Use this faster method when no clipping is involved. + public void BuildMeshWithArrays (SkeletonRendererInstruction instruction, bool updateTriangles) { + var settings = this.settings; + bool canvasGroupTintBlack = settings.tintBlack && settings.canvasGroupTintBlack; + int totalVertexCount = instruction.rawVertexCount; + + // Add data to vertex buffers + { + if (totalVertexCount > vertexBuffer.Items.Length) { // Manual ExposedList.Resize() + Array.Resize(ref vertexBuffer.Items, totalVertexCount); + Array.Resize(ref uvBuffer.Items, totalVertexCount); + Array.Resize(ref colorBuffer.Items, totalVertexCount); + } + vertexBuffer.Count = uvBuffer.Count = colorBuffer.Count = totalVertexCount; + } + + // Populate Verts + Color32 color = default(Color32); + + int vertexIndex = 0; + var tempVerts = this.tempVerts; + Vector2 bmin = this.meshBoundsMin; + Vector2 bmax = this.meshBoundsMax; + + var vbi = vertexBuffer.Items; + var ubi = uvBuffer.Items; + var cbi = colorBuffer.Items; + int lastSlotIndex = 0; + + // drawOrder[endSlot] is excluded + for (int si = 0, n = instruction.submeshInstructions.Count; si < n; si++) { + var submesh = instruction.submeshInstructions.Items[si]; + var skeleton = submesh.skeleton; + var drawOrderItems = skeleton.drawOrder.Items; + float a = skeleton.a, r = skeleton.r, g = skeleton.g, b = skeleton.b; + + int endSlot = submesh.endSlot; + int startSlot = submesh.startSlot; + lastSlotIndex = endSlot; + + if (settings.tintBlack) { + Vector2 rg, b2; + int vi = vertexIndex; + b2.y = 1f; + + { + if (uv2 == null) { + uv2 = new ExposedList(); + uv3 = new ExposedList(); + } + if (totalVertexCount > uv2.Items.Length) { // Manual ExposedList.Resize() + Array.Resize(ref uv2.Items, totalVertexCount); + Array.Resize(ref uv3.Items, totalVertexCount); + } + uv2.Count = uv3.Count = totalVertexCount; + } + + var uv2i = uv2.Items; + var uv3i = uv3.Items; + + for (int slotIndex = startSlot; slotIndex < endSlot; slotIndex++) { + var slot = drawOrderItems[slotIndex]; + if (!slot.bone.active) continue; + var attachment = slot.attachment; + + rg.x = slot.r2; //r + rg.y = slot.g2; //g + b2.x = slot.b2; //b + b2.y = 1.0f; + + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) { + if (settings.pmaVertexColors) { + float alpha = a * slot.a * regionAttachment.a; + rg.x *= alpha; + rg.y *= alpha; + b2.x *= alpha; + b2.y = slot.data.blendMode == BlendMode.Additive ? 0 : alpha; + } + uv2i[vi] = rg; uv2i[vi + 1] = rg; uv2i[vi + 2] = rg; uv2i[vi + 3] = rg; + uv3i[vi] = b2; uv3i[vi + 1] = b2; uv3i[vi + 2] = b2; uv3i[vi + 3] = b2; + vi += 4; + } else { //} if (settings.renderMeshes) { + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + if (settings.pmaVertexColors) { + float alpha = a * slot.a * meshAttachment.a; + rg.x *= alpha; + rg.y *= alpha; + b2.x *= alpha; + b2.y = slot.data.blendMode == BlendMode.Additive ? 0 : alpha; + } + int meshVertexCount = meshAttachment.worldVerticesLength; + for (int iii = 0; iii < meshVertexCount; iii += 2) { + uv2i[vi] = rg; + uv3i[vi] = b2; + vi++; + } + } + } + } + } + + for (int slotIndex = startSlot; slotIndex < endSlot; slotIndex++) { + var slot = drawOrderItems[slotIndex]; + if (!slot.bone.active) continue; + var attachment = slot.attachment; + float z = slotIndex * settings.zSpacing; + + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) { + regionAttachment.ComputeWorldVertices(slot.bone, tempVerts, 0); + + float x1 = tempVerts[RegionAttachment.BLX], y1 = tempVerts[RegionAttachment.BLY]; + float x2 = tempVerts[RegionAttachment.ULX], y2 = tempVerts[RegionAttachment.ULY]; + float x3 = tempVerts[RegionAttachment.URX], y3 = tempVerts[RegionAttachment.URY]; + float x4 = tempVerts[RegionAttachment.BRX], y4 = tempVerts[RegionAttachment.BRY]; + vbi[vertexIndex].x = x1; vbi[vertexIndex].y = y1; vbi[vertexIndex].z = z; + vbi[vertexIndex + 1].x = x4; vbi[vertexIndex + 1].y = y4; vbi[vertexIndex + 1].z = z; + vbi[vertexIndex + 2].x = x2; vbi[vertexIndex + 2].y = y2; vbi[vertexIndex + 2].z = z; + vbi[vertexIndex + 3].x = x3; vbi[vertexIndex + 3].y = y3; vbi[vertexIndex + 3].z = z; + + if (settings.pmaVertexColors) { + color.a = (byte)(a * slot.a * regionAttachment.a * 255); + color.r = (byte)(r * slot.r * regionAttachment.r * color.a); + color.g = (byte)(g * slot.g * regionAttachment.g * color.a); + color.b = (byte)(b * slot.b * regionAttachment.b * color.a); + if (slot.data.blendMode == BlendMode.Additive && !canvasGroupTintBlack) color.a = 0; + } else { + color.a = (byte)(a * slot.a * regionAttachment.a * 255); + color.r = (byte)(r * slot.r * regionAttachment.r * 255); + color.g = (byte)(g * slot.g * regionAttachment.g * 255); + color.b = (byte)(b * slot.b * regionAttachment.b * 255); + } + + cbi[vertexIndex] = color; cbi[vertexIndex + 1] = color; cbi[vertexIndex + 2] = color; cbi[vertexIndex + 3] = color; + + float[] regionUVs = regionAttachment.uvs; + ubi[vertexIndex].x = regionUVs[RegionAttachment.BLX]; ubi[vertexIndex].y = regionUVs[RegionAttachment.BLY]; + ubi[vertexIndex + 1].x = regionUVs[RegionAttachment.BRX]; ubi[vertexIndex + 1].y = regionUVs[RegionAttachment.BRY]; + ubi[vertexIndex + 2].x = regionUVs[RegionAttachment.ULX]; ubi[vertexIndex + 2].y = regionUVs[RegionAttachment.ULY]; + ubi[vertexIndex + 3].x = regionUVs[RegionAttachment.URX]; ubi[vertexIndex + 3].y = regionUVs[RegionAttachment.URY]; + + if (x1 < bmin.x) bmin.x = x1; // Potential first attachment bounds initialization. Initial min should not block initial max. Same for Y below. + if (x1 > bmax.x) bmax.x = x1; + if (x2 < bmin.x) bmin.x = x2; + else if (x2 > bmax.x) bmax.x = x2; + if (x3 < bmin.x) bmin.x = x3; + else if (x3 > bmax.x) bmax.x = x3; + if (x4 < bmin.x) bmin.x = x4; + else if (x4 > bmax.x) bmax.x = x4; + + if (y1 < bmin.y) bmin.y = y1; + if (y1 > bmax.y) bmax.y = y1; + if (y2 < bmin.y) bmin.y = y2; + else if (y2 > bmax.y) bmax.y = y2; + if (y3 < bmin.y) bmin.y = y3; + else if (y3 > bmax.y) bmax.y = y3; + if (y4 < bmin.y) bmin.y = y4; + else if (y4 > bmax.y) bmax.y = y4; + + vertexIndex += 4; + } else { //if (settings.renderMeshes) { + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + int meshVertexCount = meshAttachment.worldVerticesLength; + if (tempVerts.Length < meshVertexCount) this.tempVerts = tempVerts = new float[meshVertexCount]; + meshAttachment.ComputeWorldVertices(slot, tempVerts); + + if (settings.pmaVertexColors) { + color.a = (byte)(a * slot.a * meshAttachment.a * 255); + color.r = (byte)(r * slot.r * meshAttachment.r * color.a); + color.g = (byte)(g * slot.g * meshAttachment.g * color.a); + color.b = (byte)(b * slot.b * meshAttachment.b * color.a); + if (slot.data.blendMode == BlendMode.Additive && !canvasGroupTintBlack) color.a = 0; + } else { + color.a = (byte)(a * slot.a * meshAttachment.a * 255); + color.r = (byte)(r * slot.r * meshAttachment.r * 255); + color.g = (byte)(g * slot.g * meshAttachment.g * 255); + color.b = (byte)(b * slot.b * meshAttachment.b * 255); + } + + float[] attachmentUVs = meshAttachment.uvs; + + // Potential first attachment bounds initialization. See conditions in RegionAttachment logic. + if (vertexIndex == 0) { + // Initial min should not block initial max. + // vi == vertexIndex does not always mean the bounds are fresh. It could be a submesh. Do not nuke old values by omitting the check. + // Should know that this is the first attachment in the submesh. slotIndex == startSlot could be an empty slot. + float fx = tempVerts[0], fy = tempVerts[1]; + if (fx < bmin.x) bmin.x = fx; + if (fx > bmax.x) bmax.x = fx; + if (fy < bmin.y) bmin.y = fy; + if (fy > bmax.y) bmax.y = fy; + } + + for (int iii = 0; iii < meshVertexCount; iii += 2) { + float x = tempVerts[iii], y = tempVerts[iii + 1]; + vbi[vertexIndex].x = x; vbi[vertexIndex].y = y; vbi[vertexIndex].z = z; + cbi[vertexIndex] = color; ubi[vertexIndex].x = attachmentUVs[iii]; ubi[vertexIndex].y = attachmentUVs[iii + 1]; + + if (x < bmin.x) bmin.x = x; + else if (x > bmax.x) bmax.x = x; + + if (y < bmin.y) bmin.y = y; + else if (y > bmax.y) bmax.y = y; + + vertexIndex++; + } + } + } + } + } + + this.meshBoundsMin = bmin; + this.meshBoundsMax = bmax; + this.meshBoundsThickness = lastSlotIndex * settings.zSpacing; + + int submeshInstructionCount = instruction.submeshInstructions.Count; + submeshes.Count = submeshInstructionCount; + + // Add triangles + if (updateTriangles) { + // Match submesh buffers count with submeshInstruction count. + if (this.submeshes.Items.Length < submeshInstructionCount) { + this.submeshes.Resize(submeshInstructionCount); + for (int i = 0, n = submeshInstructionCount; i < n; i++) { + var submeshBuffer = this.submeshes.Items[i]; + if (submeshBuffer == null) + this.submeshes.Items[i] = new ExposedList(); + else + submeshBuffer.Clear(false); + } + } + + var submeshInstructionsItems = instruction.submeshInstructions.Items; // This relies on the resize above. + + // Fill the buffers. + int attachmentFirstVertex = 0; + for (int smbi = 0; smbi < submeshInstructionCount; smbi++) { + var submeshInstruction = submeshInstructionsItems[smbi]; + var currentSubmeshBuffer = this.submeshes.Items[smbi]; + { //submesh.Resize(submesh.rawTriangleCount); + int newTriangleCount = submeshInstruction.rawTriangleCount; + if (newTriangleCount > currentSubmeshBuffer.Items.Length) + Array.Resize(ref currentSubmeshBuffer.Items, newTriangleCount); + else if (newTriangleCount < currentSubmeshBuffer.Items.Length) { + // Zero the extra. + var sbi = currentSubmeshBuffer.Items; + for (int ei = newTriangleCount, nn = sbi.Length; ei < nn; ei++) + sbi[ei] = 0; + } + currentSubmeshBuffer.Count = newTriangleCount; + } + + var tris = currentSubmeshBuffer.Items; + int triangleIndex = 0; + var skeleton = submeshInstruction.skeleton; + var drawOrderItems = skeleton.drawOrder.Items; + for (int slotIndex = submeshInstruction.startSlot, endSlot = submeshInstruction.endSlot; slotIndex < endSlot; slotIndex++) { + var slot = drawOrderItems[slotIndex]; + if (!slot.bone.active) continue; + + var attachment = drawOrderItems[slotIndex].attachment; + if (attachment is RegionAttachment) { + tris[triangleIndex] = attachmentFirstVertex; + tris[triangleIndex + 1] = attachmentFirstVertex + 2; + tris[triangleIndex + 2] = attachmentFirstVertex + 1; + tris[triangleIndex + 3] = attachmentFirstVertex + 2; + tris[triangleIndex + 4] = attachmentFirstVertex + 3; + tris[triangleIndex + 5] = attachmentFirstVertex + 1; + triangleIndex += 6; + attachmentFirstVertex += 4; + continue; + } + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) { + int[] attachmentTriangles = meshAttachment.triangles; + for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) + tris[triangleIndex] = attachmentFirstVertex + attachmentTriangles[ii]; + attachmentFirstVertex += meshAttachment.worldVerticesLength >> 1; // length/2; + } + } + } + } + } + + public void ScaleVertexData (float scale) { + var vbi = vertexBuffer.Items; + for (int i = 0, n = vertexBuffer.Count; i < n; i++) { + vbi[i] *= scale; // vbi[i].x *= scale; vbi[i].y *= scale; + } + + meshBoundsMin *= scale; + meshBoundsMax *= scale; + meshBoundsThickness *= scale; + } + + void AddAttachmentTintBlack (float r2, float g2, float b2, float a, int vertexCount) { + var rg = new Vector2(r2, g2); + var bo = new Vector2(b2, a); + + int ovc = vertexBuffer.Count; + int newVertexCount = ovc + vertexCount; + { + if (uv2 == null) { + uv2 = new ExposedList(); + uv3 = new ExposedList(); + } + if (newVertexCount > uv2.Items.Length) { // Manual ExposedList.Resize() + Array.Resize(ref uv2.Items, newVertexCount); + Array.Resize(ref uv3.Items, newVertexCount); + } + uv2.Count = uv3.Count = newVertexCount; + } + + var uv2i = uv2.Items; + var uv3i = uv3.Items; + for (int i = 0; i < vertexCount; i++) { + uv2i[ovc + i] = rg; + uv3i[ovc + i] = bo; + } + } + #endregion + + #region Step 3 : Transfer vertex and triangle data to UnityEngine.Mesh + public void FillVertexData (Mesh mesh) { + var vbi = vertexBuffer.Items; + var ubi = uvBuffer.Items; + var cbi = colorBuffer.Items; + int vbiLength = vbi.Length; + + // Zero the extra. + { + int listCount = vertexBuffer.Count; + var vector3zero = Vector3.zero; + for (int i = listCount; i < vbiLength; i++) + vbi[i] = vector3zero; + } + + // Set the vertex buffer. + { + mesh.vertices = vbi; + mesh.uv = ubi; + mesh.colors32 = cbi; + + if (float.IsInfinity(meshBoundsMin.x)) { // meshBoundsMin.x == BoundsMinDefault // == doesn't work on float Infinity constants. + mesh.bounds = new Bounds(); + } else { + //mesh.bounds = ArraysMeshGenerator.ToBounds(meshBoundsMin, meshBoundsMax); + float halfWidth = (meshBoundsMax.x - meshBoundsMin.x) * 0.5f; + float halfHeight = (meshBoundsMax.y - meshBoundsMin.y) * 0.5f; + mesh.bounds = new Bounds { + center = new Vector3(meshBoundsMin.x + halfWidth, meshBoundsMin.y + halfHeight), + extents = new Vector3(halfWidth, halfHeight, meshBoundsThickness * 0.5f) + }; + } + } + + { + if (settings.addNormals) { + int oldLength = 0; + + if (normals == null) + normals = new Vector3[vbiLength]; + else + oldLength = normals.Length; + + if (oldLength != vbiLength) { + Array.Resize(ref this.normals, vbiLength); + var localNormals = this.normals; + for (int i = oldLength; i < vbiLength; i++) localNormals[i] = Vector3.back; + } + mesh.normals = this.normals; + } + + if (settings.tintBlack) { + if (uv2 != null) { + // Sometimes, the vertex buffer becomes smaller. We need to trim the size of the tint black buffers to match. + if (vbiLength != uv2.Items.Length) { + Array.Resize(ref uv2.Items, vbiLength); + Array.Resize(ref uv3.Items, vbiLength); + uv2.Count = uv3.Count = vbiLength; + } + mesh.uv2 = this.uv2.Items; + mesh.uv3 = this.uv3.Items; + } + } + } + } + + public void FillLateVertexData (Mesh mesh) { + if (settings.calculateTangents) { + int vertexCount = this.vertexBuffer.Count; + var sbi = submeshes.Items; + int submeshCount = submeshes.Count; + var vbi = vertexBuffer.Items; + var ubi = uvBuffer.Items; + + MeshGenerator.SolveTangents2DEnsureSize(ref this.tangents, ref this.tempTanBuffer, vertexCount, vbi.Length); + for (int i = 0; i < submeshCount; i++) { + var submesh = sbi[i].Items; + int triangleCount = sbi[i].Count; + MeshGenerator.SolveTangents2DTriangles(this.tempTanBuffer, submesh, triangleCount, vbi, ubi, vertexCount); + } + MeshGenerator.SolveTangents2DBuffer(this.tangents, this.tempTanBuffer, vertexCount); + mesh.tangents = this.tangents; + } + } + + public void FillTriangles (Mesh mesh) { + int submeshCount = submeshes.Count; + var submeshesItems = submeshes.Items; + mesh.subMeshCount = submeshCount; + + for (int i = 0; i < submeshCount; i++) +#if MESH_SET_TRIANGLES_PROVIDES_LENGTH_PARAM + mesh.SetTriangles(submeshesItems[i].Items, 0, submeshesItems[i].Count, i, false); +#else + mesh.SetTriangles(submeshesItems[i].Items, i, false); +#endif + } + #endregion + + public void EnsureVertexCapacity (int minimumVertexCount, bool inlcudeTintBlack = false, bool includeTangents = false, bool includeNormals = false) { + if (minimumVertexCount > vertexBuffer.Items.Length) { + Array.Resize(ref vertexBuffer.Items, minimumVertexCount); + Array.Resize(ref uvBuffer.Items, minimumVertexCount); + Array.Resize(ref colorBuffer.Items, minimumVertexCount); + + if (inlcudeTintBlack) { + if (uv2 == null) { + uv2 = new ExposedList(minimumVertexCount); + uv3 = new ExposedList(minimumVertexCount); + } + uv2.Resize(minimumVertexCount); + uv3.Resize(minimumVertexCount); + } + + if (includeNormals) { + if (normals == null) + normals = new Vector3[minimumVertexCount]; + else + Array.Resize(ref normals, minimumVertexCount); + + } + + if (includeTangents) { + if (tangents == null) + tangents = new Vector4[minimumVertexCount]; + else + Array.Resize(ref tangents, minimumVertexCount); + } + } + } + + /// Trims internal buffers to reduce the resulting mesh data stream size. + public void TrimExcess () { + vertexBuffer.TrimExcess(); + uvBuffer.TrimExcess(); + colorBuffer.TrimExcess(); + + if (uv2 != null) uv2.TrimExcess(); + if (uv3 != null) uv3.TrimExcess(); + + int vbiLength = vertexBuffer.Items.Length; + if (normals != null) Array.Resize(ref normals, vbiLength); + if (tangents != null) Array.Resize(ref tangents, vbiLength); + } + + #region TangentSolver2D + // Thanks to contributions from forum user ToddRivers + + /// Step 1 of solving tangents. Ensure you have buffers of the correct size. + /// Eventual Vector4[] tangent buffer to assign to Mesh.tangents. + /// Temporary Vector2 buffer for calculating directions. + /// Number of vertices that require tangents (or the size of the vertex array) + internal static void SolveTangents2DEnsureSize (ref Vector4[] tangentBuffer, ref Vector2[] tempTanBuffer, int vertexCount, int vertexBufferLength) { + if (tangentBuffer == null || tangentBuffer.Length != vertexBufferLength) + tangentBuffer = new Vector4[vertexBufferLength]; + + if (tempTanBuffer == null || tempTanBuffer.Length < vertexCount * 2) + tempTanBuffer = new Vector2[vertexCount * 2]; // two arrays in one. + } + + /// Step 2 of solving tangents. Fills (part of) a temporary tangent-solution buffer based on the vertices and uvs defined by a submesh's triangle buffer. Only needs to be called once for single-submesh meshes. + /// A temporary Vector3[] for calculating tangents. + /// The mesh's current vertex position buffer. + /// The mesh's current triangles buffer. + /// The mesh's current uvs buffer. + /// Number of vertices that require tangents (or the size of the vertex array) + /// The number of triangle indexes in the triangle array to be used. + internal static void SolveTangents2DTriangles (Vector2[] tempTanBuffer, int[] triangles, int triangleCount, Vector3[] vertices, Vector2[] uvs, int vertexCount) { + Vector2 sdir; + Vector2 tdir; + for (int t = 0; t < triangleCount; t += 3) { + int i1 = triangles[t + 0]; + int i2 = triangles[t + 1]; + int i3 = triangles[t + 2]; + + Vector3 v1 = vertices[i1]; + Vector3 v2 = vertices[i2]; + Vector3 v3 = vertices[i3]; + + Vector2 w1 = uvs[i1]; + Vector2 w2 = uvs[i2]; + Vector2 w3 = uvs[i3]; + + float x1 = v2.x - v1.x; + float x2 = v3.x - v1.x; + float y1 = v2.y - v1.y; + float y2 = v3.y - v1.y; + + float s1 = w2.x - w1.x; + float s2 = w3.x - w1.x; + float t1 = w2.y - w1.y; + float t2 = w3.y - w1.y; + + float div = s1 * t2 - s2 * t1; + float r = (div == 0f) ? 0f : 1f / div; + + sdir.x = (t2 * x1 - t1 * x2) * r; + sdir.y = (t2 * y1 - t1 * y2) * r; + tempTanBuffer[i1] = tempTanBuffer[i2] = tempTanBuffer[i3] = sdir; + + tdir.x = (s1 * x2 - s2 * x1) * r; + tdir.y = (s1 * y2 - s2 * y1) * r; + tempTanBuffer[vertexCount + i1] = tempTanBuffer[vertexCount + i2] = tempTanBuffer[vertexCount + i3] = tdir; + } + } + + /// Step 3 of solving tangents. Fills a Vector4[] tangents array according to values calculated in step 2. + /// A Vector4[] that will eventually be used to set Mesh.tangents + /// A temporary Vector3[] for calculating tangents. + /// Number of vertices that require tangents (or the size of the vertex array) + internal static void SolveTangents2DBuffer (Vector4[] tangents, Vector2[] tempTanBuffer, int vertexCount) { + Vector4 tangent; + tangent.z = 0; + for (int i = 0; i < vertexCount; ++i) { + Vector2 t = tempTanBuffer[i]; + + // t.Normalize() (aggressively inlined). Even better if offloaded to GPU via vertex shader. + float magnitude = Mathf.Sqrt(t.x * t.x + t.y * t.y); + if (magnitude > 1E-05) { + float reciprocalMagnitude = 1f/magnitude; + t.x *= reciprocalMagnitude; + t.y *= reciprocalMagnitude; + } + + Vector2 t2 = tempTanBuffer[vertexCount + i]; + tangent.x = t.x; + tangent.y = t.y; + //tangent.z = 0; + tangent.w = (t.y * t2.x > t.x * t2.y) ? 1 : -1; // 2D direction calculation. Used for binormals. + tangents[i] = tangent; + } + } + #endregion + + #region AttachmentRendering + static List AttachmentVerts = new List(); + static List AttachmentUVs = new List(); + static List AttachmentColors32 = new List(); + static List AttachmentIndices = new List(); + + /// Fills mesh vertex data to render a RegionAttachment. + public static void FillMeshLocal (Mesh mesh, RegionAttachment regionAttachment) { + if (mesh == null) return; + if (regionAttachment == null) return; + + AttachmentVerts.Clear(); + var offsets = regionAttachment.Offset; + AttachmentVerts.Add(new Vector3(offsets[RegionAttachment.BLX], offsets[RegionAttachment.BLY])); + AttachmentVerts.Add(new Vector3(offsets[RegionAttachment.ULX], offsets[RegionAttachment.ULY])); + AttachmentVerts.Add(new Vector3(offsets[RegionAttachment.URX], offsets[RegionAttachment.URY])); + AttachmentVerts.Add(new Vector3(offsets[RegionAttachment.BRX], offsets[RegionAttachment.BRY])); + + AttachmentUVs.Clear(); + var uvs = regionAttachment.UVs; + AttachmentUVs.Add(new Vector2(uvs[RegionAttachment.ULX], uvs[RegionAttachment.ULY])); + AttachmentUVs.Add(new Vector2(uvs[RegionAttachment.URX], uvs[RegionAttachment.URY])); + AttachmentUVs.Add(new Vector2(uvs[RegionAttachment.BRX], uvs[RegionAttachment.BRY])); + AttachmentUVs.Add(new Vector2(uvs[RegionAttachment.BLX], uvs[RegionAttachment.BLY])); + + AttachmentColors32.Clear(); + Color32 c = (Color32)(new Color(regionAttachment.r, regionAttachment.g, regionAttachment.b, regionAttachment.a)); + for (int i = 0; i < 4; i++) + AttachmentColors32.Add(c); + + AttachmentIndices.Clear(); + AttachmentIndices.AddRange(new[] { 0, 2, 1, 0, 3, 2 }); + + mesh.Clear(); + mesh.name = regionAttachment.Name; + mesh.SetVertices(AttachmentVerts); + mesh.SetUVs(0, AttachmentUVs); + mesh.SetColors(AttachmentColors32); + mesh.SetTriangles(AttachmentIndices, 0); + mesh.RecalculateBounds(); + + AttachmentVerts.Clear(); + AttachmentUVs.Clear(); + AttachmentColors32.Clear(); + AttachmentIndices.Clear(); + } + + public static void FillMeshLocal (Mesh mesh, MeshAttachment meshAttachment, SkeletonData skeletonData) { + if (mesh == null) return; + if (meshAttachment == null) return; + int vertexCount = meshAttachment.WorldVerticesLength / 2; + + AttachmentVerts.Clear(); + if (meshAttachment.IsWeighted()) { + int count = meshAttachment.WorldVerticesLength; + int[] meshAttachmentBones = meshAttachment.bones; + int v = 0; + + float[] vertices = meshAttachment.vertices; + for (int w = 0, b = 0; w < count; w += 2) { + float wx = 0, wy = 0; + int n = meshAttachmentBones[v++]; + n += v; + for (; v < n; v++, b += 3) { + BoneMatrix bm = BoneMatrix.CalculateSetupWorld(skeletonData.bones.Items[meshAttachmentBones[v]]); + float vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; + wx += (vx * bm.a + vy * bm.b + bm.x) * weight; + wy += (vx * bm.c + vy * bm.d + bm.y) * weight; + } + AttachmentVerts.Add(new Vector3(wx, wy)); + } + } else { + var localVerts = meshAttachment.Vertices; + Vector3 pos = default(Vector3); + for (int i = 0; i < vertexCount; i++) { + int ii = i * 2; + pos.x = localVerts[ii]; + pos.y = localVerts[ii + 1]; + AttachmentVerts.Add(pos); + } + } + + var uvs = meshAttachment.uvs; + Vector2 uv = default(Vector2); + Color32 c = (Color32)(new Color(meshAttachment.r, meshAttachment.g, meshAttachment.b, meshAttachment.a)); + AttachmentUVs.Clear(); + AttachmentColors32.Clear(); + for (int i = 0; i < vertexCount; i++) { + int ii = i * 2; + uv.x = uvs[ii]; + uv.y = uvs[ii + 1]; + AttachmentUVs.Add(uv); + + AttachmentColors32.Add(c); + } + + AttachmentIndices.Clear(); + AttachmentIndices.AddRange(meshAttachment.triangles); + + mesh.Clear(); + mesh.name = meshAttachment.Name; + mesh.SetVertices(AttachmentVerts); + mesh.SetUVs(0, AttachmentUVs); + mesh.SetColors(AttachmentColors32); + mesh.SetTriangles(AttachmentIndices, 0); + mesh.RecalculateBounds(); + + AttachmentVerts.Clear(); + AttachmentUVs.Clear(); + AttachmentColors32.Clear(); + AttachmentIndices.Clear(); + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs.meta new file mode 100644 index 0000000..712b492 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshGenerator.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 311447d6e56727c4dad7611d5fa5afbf +timeCreated: 1563322425 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs new file mode 100644 index 0000000..e108bbd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs @@ -0,0 +1,135 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Not for optimization. Do not disable. +#define SPINE_TRIANGLECHECK // Avoid calling SetTriangles at the cost of checking for mesh differences (vertex counts, memberwise attachment list compare) every frame. +//#define SPINE_DEBUG + +using UnityEngine; +using System; +using System.Collections.Generic; + +namespace Spine.Unity { + /// A double-buffered Mesh, and a shared material array, bundled for use by Spine components that need to push a Mesh and materials to a Unity MeshRenderer and MeshFilter. + public class MeshRendererBuffers : IDisposable { + DoubleBuffered doubleBufferedMesh; + internal readonly ExposedList submeshMaterials = new ExposedList(); + internal Material[] sharedMaterials = new Material[0]; + + public void Initialize () { + if (doubleBufferedMesh != null) { + doubleBufferedMesh.GetNext().Clear(); + doubleBufferedMesh.GetNext().Clear(); + submeshMaterials.Clear(); + } else { + doubleBufferedMesh = new DoubleBuffered(); + } + } + + /// Returns a sharedMaterials array for use on a MeshRenderer. + /// + public Material[] GetUpdatedSharedMaterialsArray () { + if (submeshMaterials.Count == sharedMaterials.Length) + submeshMaterials.CopyTo(sharedMaterials); + else + sharedMaterials = submeshMaterials.ToArray(); + + return sharedMaterials; + } + + /// Returns true if the materials were modified since the buffers were last updated. + public bool MaterialsChangedInLastUpdate () { + int newSubmeshMaterials = submeshMaterials.Count; + var sharedMaterials = this.sharedMaterials; + if (newSubmeshMaterials != sharedMaterials.Length) return true; + + var submeshMaterialsItems = submeshMaterials.Items; + for (int i = 0; i < newSubmeshMaterials; i++) + if (!Material.ReferenceEquals(submeshMaterialsItems[i], sharedMaterials[i])) return true; //if (submeshMaterialsItems[i].GetInstanceID() != sharedMaterials[i].GetInstanceID()) return true; + + return false; + } + + /// Updates the internal shared materials array with the given instruction list. + public void UpdateSharedMaterials (ExposedList instructions) { + int newSize = instructions.Count; + { //submeshMaterials.Resize(instructions.Count); + if (newSize > submeshMaterials.Items.Length) + Array.Resize(ref submeshMaterials.Items, newSize); + submeshMaterials.Count = newSize; + } + + var submeshMaterialsItems = submeshMaterials.Items; + var instructionsItems = instructions.Items; + for (int i = 0; i < newSize; i++) + submeshMaterialsItems[i] = instructionsItems[i].material; + } + + public SmartMesh GetNextMesh () { + return doubleBufferedMesh.GetNext(); + } + + public void Clear () { + sharedMaterials = new Material[0]; + submeshMaterials.Clear(); + } + + public void Dispose () { + if (doubleBufferedMesh == null) return; + doubleBufferedMesh.GetNext().Dispose(); + doubleBufferedMesh.GetNext().Dispose(); + doubleBufferedMesh = null; + } + + ///This is a Mesh that also stores the instructions SkeletonRenderer generated for it. + public class SmartMesh : IDisposable { + public Mesh mesh = SpineMesh.NewSkeletonMesh(); + public SkeletonRendererInstruction instructionUsed = new SkeletonRendererInstruction(); + + public void Clear () { + mesh.Clear(); + instructionUsed.Clear(); + } + + public void Dispose () { + if (mesh != null) { + #if UNITY_EDITOR + if (Application.isEditor && !Application.isPlaying) + UnityEngine.Object.DestroyImmediate(mesh); + else + UnityEngine.Object.Destroy(mesh); + #else + UnityEngine.Object.Destroy(mesh); + #endif + } + mesh = null; + } + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs.meta new file mode 100644 index 0000000..3e4c8a1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/MeshRendererBuffers.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b1ab80744ac17724dbc0d15fdb6f4727 +timeCreated: 1563322425 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs new file mode 100644 index 0000000..54821fa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs @@ -0,0 +1,178 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Not for optimization. Do not disable. +#define SPINE_TRIANGLECHECK // Avoid calling SetTriangles at the cost of checking for mesh differences (vertex counts, memberwise attachment list compare) every frame. +//#define SPINE_DEBUG + +using UnityEngine; +using System; +using System.Collections.Generic; + +namespace Spine.Unity { + /// Instructions used by a SkeletonRenderer to render a mesh. + public class SkeletonRendererInstruction { + public readonly ExposedList submeshInstructions = new ExposedList(); + + public bool immutableTriangles; + #if SPINE_TRIANGLECHECK + public bool hasActiveClipping; + public int rawVertexCount = -1; + public readonly ExposedList attachments = new ExposedList(); + #endif + + public void Clear () { + #if SPINE_TRIANGLECHECK + this.attachments.Clear(false); + rawVertexCount = -1; + hasActiveClipping = false; + #endif + this.submeshInstructions.Clear(false); + } + + public void Dispose () { + attachments.Clear(true); + } + + public void SetWithSubset (ExposedList instructions, int startSubmesh, int endSubmesh) { + #if SPINE_TRIANGLECHECK + int runningVertexCount = 0; + #endif + + var submeshes = this.submeshInstructions; + submeshes.Clear(false); + int submeshCount = endSubmesh - startSubmesh; + submeshes.Resize(submeshCount); + var submeshesItems = submeshes.Items; + var instructionsItems = instructions.Items; + for (int i = 0; i < submeshCount; i++) { + var instruction = instructionsItems[startSubmesh + i]; + submeshesItems[i] = instruction; + #if SPINE_TRIANGLECHECK + this.hasActiveClipping |= instruction.hasClipping; + submeshesItems[i].rawFirstVertexIndex = runningVertexCount; // Ensure current instructions have correct cached values. + runningVertexCount += instruction.rawVertexCount; // vertexCount will also be used for the rest of this method. + #endif + } + #if SPINE_TRIANGLECHECK + this.rawVertexCount = runningVertexCount; + + // assumption: instructions are contiguous. start and end are valid within instructions. + + int startSlot = instructionsItems[startSubmesh].startSlot; + int endSlot = instructionsItems[endSubmesh - 1].endSlot; + attachments.Clear(false); + int attachmentCount = endSlot - startSlot; + attachments.Resize(attachmentCount); + var attachmentsItems = attachments.Items; + + var drawOrderItems = instructionsItems[0].skeleton.drawOrder.Items; + for (int i = 0; i < attachmentCount; i++) { + Slot slot = drawOrderItems[startSlot + i]; + if (!slot.bone.active) continue; + attachmentsItems[i] = slot.attachment; + } + + #endif + } + + public void Set (SkeletonRendererInstruction other) { + this.immutableTriangles = other.immutableTriangles; + + #if SPINE_TRIANGLECHECK + this.hasActiveClipping = other.hasActiveClipping; + this.rawVertexCount = other.rawVertexCount; + this.attachments.Clear(false); + this.attachments.EnsureCapacity(other.attachments.Capacity); + this.attachments.Count = other.attachments.Count; + other.attachments.CopyTo(this.attachments.Items); + #endif + + this.submeshInstructions.Clear(false); + this.submeshInstructions.EnsureCapacity(other.submeshInstructions.Capacity); + this.submeshInstructions.Count = other.submeshInstructions.Count; + other.submeshInstructions.CopyTo(this.submeshInstructions.Items); + } + + public static bool GeometryNotEqual (SkeletonRendererInstruction a, SkeletonRendererInstruction b) { + #if SPINE_TRIANGLECHECK + #if UNITY_EDITOR + if (!Application.isPlaying) + return true; + #endif + + if (a.hasActiveClipping || b.hasActiveClipping) return true; // Triangles are unpredictable when clipping is active. + + // Everything below assumes the raw vertex and triangle counts were used. (ie, no clipping was done) + if (a.rawVertexCount != b.rawVertexCount) return true; + + if (a.immutableTriangles != b.immutableTriangles) return true; + + int attachmentCountB = b.attachments.Count; + if (a.attachments.Count != attachmentCountB) return true; // Bounds check for the looped storedAttachments count below. + + // Submesh count changed + int submeshCountA = a.submeshInstructions.Count; + int submeshCountB = b.submeshInstructions.Count; + if (submeshCountA != submeshCountB) return true; + + // Submesh Instruction mismatch + var submeshInstructionsItemsA = a.submeshInstructions.Items; + var submeshInstructionsItemsB = b.submeshInstructions.Items; + + var attachmentsA = a.attachments.Items; + var attachmentsB = b.attachments.Items; + for (int i = 0; i < attachmentCountB; i++) + if (!System.Object.ReferenceEquals(attachmentsA[i], attachmentsB[i])) return true; + + for (int i = 0; i < submeshCountB; i++) { + var submeshA = submeshInstructionsItemsA[i]; + var submeshB = submeshInstructionsItemsB[i]; + + if (!( + submeshA.rawVertexCount == submeshB.rawVertexCount && + submeshA.startSlot == submeshB.startSlot && + submeshA.endSlot == submeshB.endSlot + && submeshA.rawTriangleCount == submeshB.rawTriangleCount && + submeshA.rawFirstVertexIndex == submeshB.rawFirstVertexIndex + )) + return true; + } + + return false; + #else + // In normal immutable triangle use, immutableTriangles will be initially false, forcing the smartmesh to update the first time but never again after that, unless there was an immutableTriangles flag mismatch.. + if (a.immutableTriangles || b.immutableTriangles) + return (a.immutableTriangles != b.immutableTriangles); + + return true; + #endif + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs.meta new file mode 100644 index 0000000..50a8a97 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SkeletonRendererInstruction.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d07866ade25bd0b44a7bb1d59bacf4cb +timeCreated: 1563322425 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs new file mode 100644 index 0000000..31a25e1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs @@ -0,0 +1,84 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +// Not for optimization. Do not disable. +#define SPINE_TRIANGLECHECK // Avoid calling SetTriangles at the cost of checking for mesh differences (vertex counts, memberwise attachment list compare) every frame. +//#define SPINE_DEBUG + +using UnityEngine; +using System; +using System.Collections.Generic; + +namespace Spine.Unity { + public static class SpineMesh { + internal const HideFlags MeshHideflags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor; + + /// Factory method for creating a new mesh for use in Spine components. This can be called in field initializers. + public static Mesh NewSkeletonMesh () { + var m = new Mesh(); + m.MarkDynamic(); + m.name = "Skeleton Mesh"; + m.hideFlags = SpineMesh.MeshHideflags; + return m; + } + } + + /// Instructions for how to generate a mesh or submesh: "Render this skeleton's slots: start slot, up to but not including endSlot, using this material." + public struct SubmeshInstruction { + public Skeleton skeleton; + public int startSlot; + public int endSlot; + public Material material; + + public bool forceSeparate; + public int preActiveClippingSlotSource; + + #if SPINE_TRIANGLECHECK + // Cached values because they are determined in the process of generating instructions, + // but could otherwise be pulled from accessing attachments, checking materials and counting tris and verts. + public int rawTriangleCount; + public int rawVertexCount; + public int rawFirstVertexIndex; + public bool hasClipping; + #endif + + /// The number of slots in this SubmeshInstruction's range. Not necessarily the number of attachments. + public int SlotCount { get { return endSlot - startSlot; } } + + public override string ToString () { + return + string.Format("[SubmeshInstruction: slots {0} to {1}. (Material){2}. preActiveClippingSlotSource:{3}]", + startSlot, + endSlot - 1, + material == null ? "" : material.name, + preActiveClippingSlotSource + ); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs.meta new file mode 100644 index 0000000..b30649a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Mesh Generation/SpineMesh.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f834c8746034db645a52a9506ff1de89 +timeCreated: 1455416715 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules.meta new file mode 100644 index 0000000..2dc106c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a7935399edad9a14bb5708cf59c94b67 +folderAsset: yes +timeCreated: 1455489260 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D.meta new file mode 100644 index 0000000..bd32abb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e70d3026a0242e5418232b2015be29f7 +folderAsset: yes +timeCreated: 1456509301 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs new file mode 100644 index 0000000..a3ce3de --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs @@ -0,0 +1,156 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if SPINE_TK2D +using System; +using UnityEngine; +using Spine; + +// MITCH: handle TPackerCW flip mode (probably not swap uv horizontaly) +namespace Spine.Unity.TK2D { + public class SpriteCollectionAttachmentLoader : AttachmentLoader { + private tk2dSpriteCollectionData sprites; + private float u, v, u2, v2; + private bool regionRotated; + private float regionOriginalWidth, regionOriginalHeight; + private float regionWidth, regionHeight; + private float regionOffsetX, regionOffsetY; + private Material material; + + public SpriteCollectionAttachmentLoader (tk2dSpriteCollectionData sprites) { + if (sprites == null) + throw new ArgumentNullException("sprites cannot be null."); + this.sprites = sprites; + } + + private void ProcessSpriteDefinition (String name) { + // Strip folder names. + int index = name.LastIndexOfAny(new char[] {'/', '\\'}); + if (index != -1) + name = name.Substring(index + 1); + + tk2dSpriteDefinition def = sprites.inst.GetSpriteDefinition(name); + + if (def == null) { + Debug.Log("Sprite not found in atlas: " + name, sprites); + throw new Exception("Sprite not found in atlas: " + name); + } + if (def.complexGeometry) + throw new NotImplementedException("Complex geometry is not supported: " + name); + if (def.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW) + throw new NotImplementedException("Only 2D Toolkit atlases are supported: " + name); + + Vector2 minTexCoords = Vector2.one, maxTexCoords = Vector2.zero; + for (int i = 0; i < def.uvs.Length; ++i) { + Vector2 uv = def.uvs[i]; + minTexCoords = Vector2.Min(minTexCoords, uv); + maxTexCoords = Vector2.Max(maxTexCoords, uv); + } + regionRotated = def.flipped == tk2dSpriteDefinition.FlipMode.Tk2d; + if (regionRotated) { + float temp = minTexCoords.x; + minTexCoords.x = maxTexCoords.x; + maxTexCoords.x = temp; + } + u = minTexCoords.x; + v = maxTexCoords.y; + u2 = maxTexCoords.x; + v2 = minTexCoords.y; + + regionOriginalWidth = (int)(def.untrimmedBoundsData[1].x / def.texelSize.x); + regionOriginalHeight = (int)(def.untrimmedBoundsData[1].y / def.texelSize.y); + + regionWidth = (int)(def.boundsData[1].x / def.texelSize.x); + regionHeight = (int)(def.boundsData[1].y / def.texelSize.y); + + float x0 = def.untrimmedBoundsData[0].x - def.untrimmedBoundsData[1].x / 2; + float x1 = def.boundsData[0].x - def.boundsData[1].x / 2; + regionOffsetX = (int)((x1 - x0) / def.texelSize.x); + + float y0 = def.untrimmedBoundsData[0].y - def.untrimmedBoundsData[1].y / 2; + float y1 = def.boundsData[0].y - def.boundsData[1].y / 2; + regionOffsetY = (int)((y1 - y0) / def.texelSize.y); + + material = def.materialInst; + } + + public RegionAttachment NewRegionAttachment (Skin skin, String name, String path) { + ProcessSpriteDefinition(path); + + RegionAttachment region = new RegionAttachment(name); + region.Path = path; + region.RendererObject = material; + region.SetUVs(u, v, u2, v2, regionRotated); + region.RegionOriginalWidth = regionOriginalWidth; + region.RegionOriginalHeight = regionOriginalHeight; + region.RegionWidth = regionWidth; + region.RegionHeight = regionHeight; + region.RegionOffsetX = regionOffsetX; + region.RegionOffsetY = regionOffsetY; + return region; + } + + public MeshAttachment NewMeshAttachment (Skin skin, String name, String path) { + ProcessSpriteDefinition(path); + + MeshAttachment mesh = new MeshAttachment(name); + mesh.Path = path; + mesh.RendererObject = material; + mesh.RegionU = u; + mesh.RegionV = v; + mesh.RegionU2 = u2; + mesh.RegionV2 = v2; + mesh.RegionRotate = regionRotated; + mesh.RegionOriginalWidth = regionOriginalWidth; + mesh.RegionOriginalHeight = regionOriginalHeight; + mesh.RegionWidth = regionWidth; + mesh.RegionHeight = regionHeight; + mesh.RegionOffsetX = regionOffsetX; + mesh.RegionOffsetY = regionOffsetY; + return mesh; + } + + public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, String name) { + return new BoundingBoxAttachment(name); + } + + public PathAttachment NewPathAttachment (Skin skin, string name) { + return new PathAttachment(name); + } + + public PointAttachment NewPointAttachment (Skin skin, string name) { + return new PointAttachment(name); + } + + public ClippingAttachment NewClippingAttachment (Skin skin, string name) { + return new ClippingAttachment(name); + } + } +} +#endif diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs.meta new file mode 100644 index 0000000..671d5c7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Modules/TK2D/SpriteCollectionAttachmentLoader.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 03238e4a73953c045a6cb289162532f3 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders.meta new file mode 100644 index 0000000..96c6a80 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: ef8189a68a74bec4eba582e65fb98dbd +DefaultImporter: + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes.meta new file mode 100644 index 0000000..5fd19df --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: baf1d09e18b500d41a714f6207ddda2d +folderAsset: yes +timeCreated: 1536402197 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader new file mode 100644 index 0000000..322c9a4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader @@ -0,0 +1,128 @@ +// Spine/Skeleton PMA Screen +// - single color multiply tint +// - unlit +// - Premultiplied alpha Multiply blending +// - No depth, no backface culling, no fog. +// - ShadowCaster pass + +Shader "Spine/Blend Modes/Skeleton PMA Additive" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One One + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + uniform sampler2D _MainTex; + uniform float4 _Color; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + ZWrite On + ZTest LEqual + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + struct v2f { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + uniform float4 _MainTex_ST; + + v2f vert (appdata_base v, float4 vertexColor : COLOR) { + v2f o; + TRANSFER_SHADOW_CASTER(o) + o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex); + o.uvAndAlpha.z = 0; + o.uvAndAlpha.a = vertexColor.a; + return o; + } + + uniform sampler2D _MainTex; + uniform fixed _Cutoff; + + float4 frag (v2f i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader.meta new file mode 100644 index 0000000..1204d94 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Additive.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 53efa1d97f5d9f74285d4330cda14e36 +timeCreated: 1496446742 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader new file mode 100644 index 0000000..7b35130 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader @@ -0,0 +1,128 @@ +// Spine/Skeleton PMA Multiply +// - single color multiply tint +// - unlit +// - Premultiplied alpha Multiply blending +// - No depth, no backface culling, no fog. +// - ShadowCaster pass + +Shader "Spine/Blend Modes/Skeleton PMA Multiply" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend DstColor OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + uniform sampler2D _MainTex; + uniform float4 _Color; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + ZWrite On + ZTest LEqual + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + struct v2f { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + uniform float4 _MainTex_ST; + + v2f vert (appdata_base v, float4 vertexColor : COLOR) { + v2f o; + TRANSFER_SHADOW_CASTER(o) + o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex); + o.uvAndAlpha.z = 0; + o.uvAndAlpha.a = vertexColor.a; + return o; + } + + uniform sampler2D _MainTex; + uniform fixed _Cutoff; + + float4 frag (v2f i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader.meta new file mode 100644 index 0000000..f311988 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Multiply.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 8bdcdc7ee298e594a9c20c61d25c33b6 +timeCreated: 1496446742 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader new file mode 100644 index 0000000..3f0220c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader @@ -0,0 +1,128 @@ +// Spine/Skeleton PMA Screen +// - single color multiply tint +// - unlit +// - Premultiplied alpha Multiply blending +// - No depth, no backface culling, no fog. +// - ShadowCaster pass + +Shader "Spine/Blend Modes/Skeleton PMA Screen" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcColor + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + uniform sampler2D _MainTex; + uniform float4 _Color; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + ZWrite On + ZTest LEqual + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + struct v2f { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + uniform float4 _MainTex_ST; + + v2f vert (appdata_base v, float4 vertexColor : COLOR) { + v2f o; + TRANSFER_SHADOW_CASTER(o) + o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex); + o.uvAndAlpha.z = 0; + o.uvAndAlpha.a = vertexColor.a; + return o; + } + + uniform sampler2D _MainTex; + uniform fixed _Cutoff; + + float4 frag (v2f i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader.meta new file mode 100644 index 0000000..173ff6a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/BlendModes/Spine-Skeleton-PMA-Screen.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4e8caa36c07aacf4ab270da00784e4d9 +timeCreated: 1496448787 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes.meta new file mode 100644 index 0000000..c880450 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 511f90ee1fe01c146836d5ed23f2e70f +folderAsset: yes +timeCreated: 1564083752 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc new file mode 100644 index 0000000..f5150ab --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc @@ -0,0 +1,30 @@ +#ifndef SKELETON_LIT_COMMON_SHADOW_INCLUDED +#define SKELETON_LIT_COMMON_SHADOW_INCLUDED + +#include "UnityCG.cginc" +struct v2f { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; +}; + +uniform float4 _MainTex_ST; + +v2f vertShadow(appdata_base v, float4 vertexColor : COLOR) { + v2f o; + TRANSFER_SHADOW_CASTER(o) + o.uvAndAlpha.xy = TRANSFORM_TEX(v.texcoord, _MainTex); + o.uvAndAlpha.z = 0; + o.uvAndAlpha.a = vertexColor.a; + return o; +} + +uniform sampler2D _MainTex; +uniform fixed SHADOW_CUTOFF; + +float4 fragShadow (v2f i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - SHADOW_CUTOFF); + SHADOW_CASTER_FRAGMENT(i) +} + +#endif diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc.meta new file mode 100644 index 0000000..b325e23 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c7297b25c81d2494e8e73b742e3c7345 +timeCreated: 1564083752 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc new file mode 100644 index 0000000..9dc1709 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc @@ -0,0 +1,119 @@ +#ifndef SKELETON_LIT_COMMON_INCLUDED +#define SKELETON_LIT_COMMON_INCLUDED + +#include "UnityCG.cginc" + +// ES2.0/WebGL/3DS can not do loops with non-constant-expression iteration counts :( +#if defined(SHADER_API_GLES) +#define LIGHT_LOOP_LIMIT 8 +#elif defined(SHADER_API_N3DS) +#define LIGHT_LOOP_LIMIT 4 +#else +#define LIGHT_LOOP_LIMIT unity_VertexLightParams.x +#endif + + +//////////////////////////////////////// +// Alpha Clipping +// + +#if defined(_ALPHA_CLIP) + uniform fixed _Cutoff; + #define ALPHA_CLIP(pixel, color) clip((pixel.a * color.a) - _Cutoff); +#else + #define ALPHA_CLIP(pixel, color) +#endif + +half3 computeLighting (int idx, half3 dirToLight, half3 eyeNormal, half4 diffuseColor, half atten) { + half NdotL = max(dot(eyeNormal, dirToLight), 0.0); + // diffuse + half3 color = NdotL * diffuseColor.rgb * unity_LightColor[idx].rgb; + return color * atten; +} + +half3 computeOneLight (int idx, float3 eyePosition, half3 eyeNormal, half4 diffuseColor) { + float3 dirToLight = unity_LightPosition[idx].xyz; + half att = 1.0; + + #if defined(POINT) || defined(SPOT) + dirToLight -= eyePosition * unity_LightPosition[idx].w; + + // distance attenuation + float distSqr = dot(dirToLight, dirToLight); + att /= (1.0 + unity_LightAtten[idx].z * distSqr); + if (unity_LightPosition[idx].w != 0 && distSqr > unity_LightAtten[idx].w) att = 0.0; // set to 0 if outside of range + distSqr = max(distSqr, 0.000001); // don't produce NaNs if some vertex position overlaps with the light + dirToLight *= rsqrt(distSqr); + #if defined(SPOT) + + // spot angle attenuation + half rho = max(dot(dirToLight, unity_SpotDirection[idx].xyz), 0.0); + half spotAtt = (rho - unity_LightAtten[idx].x) * unity_LightAtten[idx].y; + att *= saturate(spotAtt); + #endif + #endif + + att *= 0.5; // passed in light colors are 2x brighter than what used to be in FFP + return min (computeLighting (idx, dirToLight, eyeNormal, diffuseColor, att), 1.0); +} + +int4 unity_VertexLightParams; // x: light count, y: zero, z: one (y/z needed by d3d9 vs loop instruction) + +struct appdata { + float3 pos : POSITION; + float3 normal : NORMAL; + half4 color : COLOR; + float2 uv0 : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct VertexOutput { + fixed4 color : COLOR0; + float2 uv0 : TEXCOORD0; + float4 pos : SV_POSITION; + UNITY_VERTEX_OUTPUT_STEREO +}; + +VertexOutput vert (appdata v) { + VertexOutput o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + + half4 color = v.color; + float3 eyePos = UnityObjectToViewPos(float4(v.pos, 1)).xyz; //mul(UNITY_MATRIX_MV, float4(v.pos,1)).xyz; + half3 fixedNormal = half3(0,0,-1); + half3 eyeNormal = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, fixedNormal)); + //half3 eyeNormal = half3(0,0,1); + + // Lights + half3 lcolor = half4(0,0,0,1).rgb + color.rgb * glstate_lightmodel_ambient.rgb; + for (int il = 0; il < LIGHT_LOOP_LIMIT; ++il) { + lcolor += computeOneLight(il, eyePos, eyeNormal, color); + } + + color.rgb = lcolor.rgb; + o.color = saturate(color); + o.uv0 = v.uv0; + o.pos = UnityObjectToClipPos(v.pos); + return o; +} + +sampler2D _MainTex; + +fixed4 frag (VertexOutput i) : SV_Target { + fixed4 tex = tex2D(_MainTex, i.uv0); + ALPHA_CLIP(tex, i.color); + + fixed4 col; + #if defined(_STRAIGHT_ALPHA_INPUT) + col.rgb = tex * i.color * tex.a; + #else + col.rgb = tex * i.color; + #endif + + col *= 2; + col.a = tex.a * i.color.a; + return col; +} + +#endif diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc.meta new file mode 100644 index 0000000..ee34810 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/CGIncludes/Spine-Skeleton-Lit-Common.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 70c77c02aabd5e44f94aab48dd0be7b2 +timeCreated: 1564083752 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline.meta new file mode 100644 index 0000000..a058eeb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e8c87a44b93daed4383ca2ca5dfb3c43 +folderAsset: yes +timeCreated: 1573827942 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes.meta new file mode 100644 index 0000000..cf3eaf4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6a7bd28c2cf2e41499693d9f8f9e2e1a +folderAsset: yes +timeCreated: 1573829102 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader new file mode 100644 index 0000000..ded84bb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader @@ -0,0 +1,46 @@ +// Outline shader variant of "Spine/Blend Modes/Skeleton PMA Additive" + +Shader "Spine/Outline/Blend Modes/Skeleton PMA Additive" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One One + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Blend Modes/Skeleton PMA Additive/NORMAL" + + UsePass "Spine/Blend Modes/Skeleton PMA Additive/CASTER" + } + FallBack "Spine/Blend Modes/Skeleton PMA Additive" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader.meta new file mode 100644 index 0000000..4e5f97b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Additive-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0299ffae826705448b6c80ccc6a53b75 +timeCreated: 1573829476 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader new file mode 100644 index 0000000..3ef828f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader @@ -0,0 +1,46 @@ +// Outline shader variant of "Spine/Blend Modes/Skeleton PMA Multiply" + +Shader "Spine/Outline/Blend Modes/Skeleton PMA Multiply" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend DstColor OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Blend Modes/Skeleton PMA Multiply/NORMAL" + + UsePass "Spine/Blend Modes/Skeleton PMA Multiply/CASTER" + } + FallBack "Spine/Blend Modes/Skeleton PMA Multiply" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader.meta new file mode 100644 index 0000000..741a24e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Multiply-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4b3566a937643b8498d1ec6df5880b77 +timeCreated: 1573829476 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader new file mode 100644 index 0000000..9a93560 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader @@ -0,0 +1,46 @@ +// Outline shader variant of "Spine/Blend Modes/Skeleton PMA Screen" + +Shader "Spine/Outline/Blend Modes/Skeleton PMA Screen" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcColor + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Blend Modes/Skeleton PMA Screen/NORMAL" + + UsePass "Spine/Blend Modes/Skeleton PMA Screen/CASTER" + } + FallBack "Spine/Blend Modes/Skeleton PMA Screen" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader.meta new file mode 100644 index 0000000..bfb5ad6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/BlendModes/Spine-Skeleton-PMA-Screen-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e61a8d94e453ff641a7e39c4b11cac95 +timeCreated: 1573829476 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes.meta new file mode 100644 index 0000000..42c9786 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 329bda94bce571446a1a149b53ccf45c +folderAsset: yes +timeCreated: 1574096529 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc new file mode 100644 index 0000000..7ed2a28 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc @@ -0,0 +1,119 @@ +#ifndef SPINE_OUTLINE_PASS_INCLUDED +#define SPINE_OUTLINE_PASS_INCLUDED + +#include "UnityCG.cginc" + +#ifdef SKELETON_GRAPHIC +#include "UnityUI.cginc" +#endif + +sampler2D _MainTex; + +float _OutlineWidth; +float4 _OutlineColor; +float4 _MainTex_TexelSize; +float _ThresholdEnd; +float _OutlineSmoothness; +float _OutlineMipLevel; +int _OutlineReferenceTexWidth; + +#ifdef SKELETON_GRAPHIC +float4 _ClipRect; +#endif + +struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float vertexColorAlpha : COLOR; +#ifdef SKELETON_GRAPHIC + float4 worldPosition : TEXCOORD1; +#endif + UNITY_VERTEX_OUTPUT_STEREO +}; + + +#ifdef SKELETON_GRAPHIC + +VertexOutput vertOutlineGraphic(VertexInput v) { + VertexOutput o; + + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + + o.worldPosition = v.vertex; + o.pos = UnityObjectToClipPos(o.worldPosition); + o.uv = v.uv; + +#ifdef UNITY_HALF_TEXEL_OFFSET + o.pos.xy += (_ScreenParams.zw - 1.0) * float2(-1, 1); +#endif + + o.vertexColorAlpha = v.vertexColor.a; + return o; +} + +#else // !SKELETON_GRAPHIC + +VertexOutput vertOutline(VertexInput v) { + VertexOutput o; + + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColorAlpha = v.vertexColor.a; + return o; +} +#endif + +float4 fragOutline(VertexOutput i) : SV_Target { + + float4 texColor = fixed4(0,0,0,0); + + float outlineWidthCompensated = _OutlineWidth / (_OutlineReferenceTexWidth * _MainTex_TexelSize.x); + float xOffset = _MainTex_TexelSize.x * outlineWidthCompensated; + float yOffset = _MainTex_TexelSize.y * outlineWidthCompensated; + float xOffsetDiagonal = _MainTex_TexelSize.x * outlineWidthCompensated * 0.7; + float yOffsetDiagonal = _MainTex_TexelSize.y * outlineWidthCompensated * 0.7; + + float pixelCenter = tex2D(_MainTex, i.uv).a; + + float4 uvCenterWithLod = float4(i.uv, 0, _OutlineMipLevel); + float pixelTop = tex2Dlod(_MainTex, uvCenterWithLod + float4(0, yOffset, 0, 0)).a; + float pixelBottom = tex2Dlod(_MainTex, uvCenterWithLod + float4(0, -yOffset, 0, 0)).a; + float pixelLeft = tex2Dlod(_MainTex, uvCenterWithLod + float4(-xOffset, 0, 0, 0)).a; + float pixelRight = tex2Dlod(_MainTex, uvCenterWithLod + float4(xOffset, 0, 0, 0)).a; +#if _USE8NEIGHBOURHOOD_ON + float numSamples = 8; + float pixelTopLeft = tex2Dlod(_MainTex, uvCenterWithLod + float4(-xOffsetDiagonal, yOffsetDiagonal, 0, 0)).a; + float pixelTopRight = tex2Dlod(_MainTex, uvCenterWithLod + float4(xOffsetDiagonal, yOffsetDiagonal, 0, 0)).a; + float pixelBottomLeft = tex2Dlod(_MainTex, uvCenterWithLod + float4(-xOffsetDiagonal, -yOffsetDiagonal, 0, 0)).a; + float pixelBottomRight = tex2Dlod(_MainTex, uvCenterWithLod + float4(xOffsetDiagonal, -yOffsetDiagonal, 0, 0)).a; + float average = (pixelTop + pixelBottom + pixelLeft + pixelRight + + pixelTopLeft + pixelTopRight + pixelBottomLeft + pixelBottomRight) + * i.vertexColorAlpha / numSamples; +#else // 4 neighbourhood + float numSamples = 1; + float average = (pixelTop + pixelBottom + pixelLeft + pixelRight) * i.vertexColorAlpha / numSamples; +#endif + + float thresholdStart = _ThresholdEnd * (1.0 - _OutlineSmoothness); + float outlineAlpha = saturate((average - thresholdStart) / (_ThresholdEnd - thresholdStart)) - pixelCenter; + texColor.rgba = lerp(texColor, _OutlineColor, outlineAlpha); + +#ifdef SKELETON_GRAPHIC + texColor *= UnityGet2DClipping(i.worldPosition.xy, _ClipRect); +#endif + + return texColor; +} + +#endif // SPINE_OUTLINE_PASS_INCLUDED diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc.meta new file mode 100644 index 0000000..f67e757 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/CGIncludes/Spine-Outline-Pass.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2ec781e799f97504c8a418e168759f70 +timeCreated: 1574096529 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic.meta new file mode 100644 index 0000000..230f170 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6e8ed065898e65f4d9303492725fb912 +folderAsset: yes +timeCreated: 1573829873 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader new file mode 100644 index 0000000..05f279e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader @@ -0,0 +1,75 @@ +// Outline shader variant of "Spine/SkeletonGraphic" + +Shader "Spine/Outline/SkeletonGraphic" +{ + Properties + { + [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [Toggle(_CANVAS_GROUP_COMPATIBLE)] _CanvasGroupCompatible("CanvasGroup Compatible", Int) = 0 + _Color ("Tint", Color) = (1,1,1,1) + + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Float) = 8 + [HideInInspector] _Stencil ("Stencil ID", Float) = 0 + [HideInInspector][Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Float) = 0 + [HideInInspector] _StencilWriteMask ("Stencil Write Mask", Float) = 255 + [HideInInspector] _StencilReadMask ("Stencil Read Mask", Float) = 255 + + [HideInInspector] _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + "CanUseSpriteAtlas"="True" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Fog { Mode Off } + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass { + Name "Outline" + CGPROGRAM + #pragma vertex vertOutlineGraphic + #pragma fragment fragOutline + #define SKELETON_GRAPHIC + #pragma shader_feature _ _USE8NEIGHBOURHOOD_ON + #include "../CGIncludes/Spine-Outline-Pass.cginc" + ENDCG + } + + UsePass "Spine/SkeletonGraphic/NORMAL" + } + FallBack "Spine/SkeletonGraphic" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader.meta new file mode 100644 index 0000000..2968808 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 8f5d14d2a7fedb84998c50eb96c8b748 +timeCreated: 1573829873 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader new file mode 100644 index 0000000..f739f11 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader @@ -0,0 +1,68 @@ +// Outline shader variant of "Spine/SkeletonGraphic Tint Black" + +Shader "Spine/Outline/SkeletonGraphic Tint Black" +{ + Properties + { + [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [Toggle(_CANVAS_GROUP_COMPATIBLE)] _CanvasGroupCompatible("CanvasGroup Compatible", Int) = 0 + + _Color ("Tint", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Float) = 8 + [HideInInspector] _Stencil ("Stencil ID", Float) = 0 + [HideInInspector][Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Float) = 0 + [HideInInspector] _StencilWriteMask ("Stencil Write Mask", Float) = 255 + [HideInInspector] _StencilReadMask ("Stencil Read Mask", Float) = 255 + + [HideInInspector] _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + "CanUseSpriteAtlas"="True" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Fog { Mode Off } + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + UsePass "Spine/Outline/SkeletonGraphic/OUTLINE" + + UsePass "Spine/SkeletonGraphic Tint Black/NORMAL" + } + FallBack "Spine/SkeletonGraphic Tint Black" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader.meta new file mode 100644 index 0000000..a35c5b2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: d55d64dd09c46af40a319933a62fa1b2 +timeCreated: 1573830121 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader new file mode 100644 index 0000000..fc25451 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader @@ -0,0 +1,43 @@ +// Outline shader variant of "Spine/Skeleton Fill" + +Shader "Spine/Outline/Skeleton Fill" { + Properties { + _FillColor ("FillColor", Color) = (1,1,1,1) + _FillPhase ("FillPhase", Range(0, 1)) = 0 + [NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {} + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + Blend One OneMinusSrcAlpha + Cull Off + ZWrite Off + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Skeleton Fill/NORMAL" + + UsePass "Spine/Skeleton Fill/CASTER" + } + FallBack "Spine/Skeleton Fill" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader.meta new file mode 100644 index 0000000..3793896 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Fill-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e158cbe58baa093438feb3d691f3daba +timeCreated: 1573817434 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader new file mode 100644 index 0000000..411036f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader @@ -0,0 +1,39 @@ +// Outline shader variant of "Spine/Skeleton Lit" + +Shader "Spine/Outline/Skeleton Lit" { + Properties { + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Skeleton Lit/NORMAL" + + UsePass "Spine/Skeleton Lit/CASTER" + } + FallBack "Spine/Skeleton Lit" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader.meta new file mode 100644 index 0000000..4dd9501 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 10fab3f69a099be4391fe8a1ad880c65 +timeCreated: 1573828963 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader new file mode 100644 index 0000000..4cdf0e7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader @@ -0,0 +1,40 @@ +// Outline shader variant of "Spine/Skeleton Lit ZWrite" + +Shader "Spine/Outline/Skeleton Lit ZWrite" { + Properties { + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.1 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Skeleton Lit ZWrite/NORMAL" + + UsePass "Spine/Skeleton Lit ZWrite/CASTER" + } + FallBack "Spine/Skeleton Lit ZWrite" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader.meta new file mode 100644 index 0000000..e772ed4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Lit-ZWrite-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 756be4f2f738f6c4583bb1c90e16bf0b +timeCreated: 1573828964 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader new file mode 100644 index 0000000..e60ef06 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader @@ -0,0 +1,52 @@ +// Outline shader variant of "Spine/Skeleton" + +Shader "Spine/Outline/Skeleton" { + Properties { + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Outline" + CGPROGRAM + #pragma vertex vertOutline + #pragma fragment fragOutline + #pragma shader_feature _ _USE8NEIGHBOURHOOD_ON + #include "CGIncludes/Spine-Outline-Pass.cginc" + ENDCG + } + + UsePass "Spine/Skeleton/NORMAL" + + UsePass "Spine/Skeleton/CASTER" + } + FallBack "Spine/Skeleton" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader.meta new file mode 100644 index 0000000..e7dcd76 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 28b5cf4804845fe4b868531fd0bb81d5 +timeCreated: 1573817434 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader new file mode 100644 index 0000000..2b385f8 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader @@ -0,0 +1,46 @@ +// Outline shader variant of "Spine/Skeleton Tint" + +Shader "Spine/Outline/Skeleton Tint" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Skeleton Tint/NORMAL" + + UsePass "Spine/Skeleton Tint/CASTER" + } + FallBack "Spine/Skeleton Tint" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader.meta new file mode 100644 index 0000000..e5d5456 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-Tint-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4f1fdc166fed03649835949d3b79cba3 +timeCreated: 1573817434 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader new file mode 100644 index 0000000..64afad4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader @@ -0,0 +1,47 @@ +// Outline shader variant of "Spine/Skeleton Tint Black" + +Shader "Spine/Outline/Skeleton Tint Black" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Skeleton Tint Black/NORMAL" + + UsePass "Spine/Skeleton Tint Black/CASTER" + } + FallBack "Spine/Special/Skeleton Grayscale" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader.meta new file mode 100644 index 0000000..8bbce16 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Skeleton-TintBlack-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 49cf725a1e40e7742be92917f83946c3 +timeCreated: 1573828963 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader new file mode 100644 index 0000000..722ed75 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader @@ -0,0 +1,43 @@ +// Outline shader variant of "Spine/Special/Skeleton Grayscale" + +Shader "Spine/Outline/Special/Skeleton Grayscale" { + Properties { + _GrayPhase ("Phase", Range(0, 1)) = 1 + [NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {} + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + Blend One OneMinusSrcAlpha + Cull Off + ZWrite Off + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Special/Skeleton Grayscale/NORMAL" + + UsePass "Spine/Special/Skeleton Grayscale/CASTER" + } + FallBack "Spine/Special/Skeleton Grayscale" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader.meta new file mode 100644 index 0000000..5f17b0b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Spine-Special-Skeleton-Grayscale-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1d3e1518ae643a749b086bc7972893d2 +timeCreated: 1573828963 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite.meta new file mode 100644 index 0000000..fff5fc6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 615182d5e489bf3478299e5bbf15dc23 +folderAsset: yes +timeCreated: 1573830740 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader new file mode 100644 index 0000000..1cb3e01 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader @@ -0,0 +1,83 @@ +// Outline shader variant of "Spine/Sprite/Pixel Lit" + +Shader "Spine/Outline/Sprite/Pixel Lit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + _BumpScale("Scale", Float) = 1.0 + _BumpMap ("Normal Map", 2D) = "bump" {} + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _EmissionColor("Color", Color) = (0,0,0,0) + _EmissionMap("Emission", 2D) = "white" {} + _EmissionPower("Emission Power", Float) = 2.0 + + _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5 + _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0 + [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0 + _MetallicGlossMap("Metallic", 2D) = "white" {} + + _DiffuseRamp ("Diffuse Ramp Texture", 2D) = "gray" {} + + _FixedNormal ("Fixed Normal", Vector) = (0,0,1,1) + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.5 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _RimPower("Rim Power", Float) = 2.0 + _RimColor ("Rim Color", Color) = (1,1,1,1) + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 200 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Sprite/Pixel Lit/FORWARD" + + UsePass "Spine/Sprite/Pixel Lit/FORWARD_DELTA" + + UsePass "Spine/Sprite/Pixel Lit/SHADOWCASTER" + } + + FallBack "Spine/Sprite/Pixel Lit" + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader.meta new file mode 100644 index 0000000..963554e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesPixelLit-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a27d4b27c8ecd9840a03558ccc5ad8a3 +timeCreated: 1573830741 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader new file mode 100644 index 0000000..b687e01 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader @@ -0,0 +1,63 @@ +// Outline shader variant of "Spine/Sprite/Unlit" + +Shader "Spine/Outline/Sprite/Unlit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _ZWrite ("Depth Write", Float) = 0.0 + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.0 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Sprite/Unlit/NORMAL" + + UsePass "Spine/Sprite/Unlit/SHADOWCASTER" + } + FallBack "Spine/Sprite/Unlit" + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader.meta new file mode 100644 index 0000000..0ab7534 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesUnlit-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 276c07e3bdd5719458187a5823e9d96a +timeCreated: 1573830740 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader new file mode 100644 index 0000000..3611d79 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader @@ -0,0 +1,82 @@ +// Outline shader variant of "Spine/Sprite/Vertex Lit" + +Shader "Spine/Outline/Sprite/Vertex Lit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + _BumpScale("Scale", Float) = 1.0 + _BumpMap ("Normal Map", 2D) = "bump" {} + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _EmissionColor("Color", Color) = (0,0,0,0) + _EmissionMap("Emission", 2D) = "white" {} + _EmissionPower("Emission Power", Float) = 2.0 + + _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5 + _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0 + [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0 + _MetallicGlossMap("Metallic", 2D) = "white" {} + + _DiffuseRamp ("Diffuse Ramp Texture", 2D) = "gray" {} + + _FixedNormal ("Fixed Normal", Vector) = (0,0,1,1) + _ZWrite ("Depth Write", Float) = 0.0 + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.0 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _RimPower("Rim Power", Float) = 2.0 + _RimColor ("Rim Color", Color) = (1,1,1,1) + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 150 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + UsePass "Spine/Outline/Skeleton/OUTLINE" + + UsePass "Spine/Sprite/Vertex Lit/VERTEX" + + UsePass "Spine/Sprite/Vertex Lit/SHADOWCASTER" + } + + FallBack "Spine/Sprite/Vertex Lit" + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader.meta new file mode 100644 index 0000000..baa2bcf --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Outline/Sprite/SpritesVertexLit-Outline.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 30ef5dd318033004588a6481c092416a +timeCreated: 1573830740 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic.meta new file mode 100644 index 0000000..0314067 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 7a42d52714848d64f8ff99dddb93500e +folderAsset: yes +timeCreated: 1563289150 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader new file mode 100644 index 0000000..0e731a7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader @@ -0,0 +1,144 @@ +// This is a premultiply-alpha adaptation of the built-in Unity shader "UI/Default" to allow Unity UI stencil masking. + +Shader "Spine/SkeletonGraphic Tint Black" +{ + Properties + { + [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [Toggle(_CANVAS_GROUP_COMPATIBLE)] _CanvasGroupCompatible("CanvasGroup Compatible", Int) = 0 + + _Color ("Tint", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Float) = 8 + [HideInInspector] _Stencil ("Stencil ID", Float) = 0 + [HideInInspector][Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Float) = 0 + [HideInInspector] _StencilWriteMask ("Stencil Write Mask", Float) = 255 + [HideInInspector] _StencilReadMask ("Stencil Read Mask", Float) = 255 + + [HideInInspector] _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + "CanUseSpriteAtlas"="True" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Fog { Mode Off } + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma shader_feature _ _CANVAS_GROUP_COMPATIBLE + #pragma vertex vert + #pragma fragment frag + + #include "UnityCG.cginc" + #include "UnityUI.cginc" + + #pragma multi_compile __ UNITY_UI_ALPHACLIP + + struct VertexInput { + float4 vertex : POSITION; + float4 color : COLOR; + float2 texcoord : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct VertexOutput { + float4 vertex : SV_POSITION; + fixed4 color : COLOR; + half2 texcoord : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; + float4 worldPosition : TEXCOORD3; + UNITY_VERTEX_OUTPUT_STEREO + }; + + fixed4 _Color; + fixed4 _Black; + fixed4 _TextureSampleAdd; + float4 _ClipRect; + + VertexOutput vert (VertexInput IN) { + VertexOutput OUT; + + UNITY_SETUP_INSTANCE_ID(IN); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT); + + OUT.worldPosition = IN.vertex; + OUT.vertex = UnityObjectToClipPos(OUT.worldPosition); + OUT.texcoord = IN.texcoord; + + OUT.color = IN.color * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + OUT.uv1 = IN.uv1; + OUT.uv2 = IN.uv2; + return OUT; + } + + sampler2D _MainTex; + + fixed4 frag (VertexOutput IN) : SV_Target + { + half4 texColor = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + texColor *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect); + + #ifdef UNITY_UI_ALPHACLIP + clip (texColor.a - 0.001); + #endif + + half4 color = (texColor * IN.color) + float4(((1-texColor.rgb) * (_Black.rgb + float3(IN.uv1.r, IN.uv1.g, IN.uv2.r)) * texColor.a * _Color.a * IN.color.a), 0); + #ifdef _CANVAS_GROUP_COMPATIBLE + // CanvasGroup alpha sets vertex color alpha, but does not premultiply it to rgb components. + color.rgb *= IN.color.a; + #endif + return color; + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader.meta new file mode 100644 index 0000000..5193a26 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic-TintBlack.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f64c7bc238bb2c246b8ca1912b2b6b9c +timeCreated: 1455080068 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader new file mode 100644 index 0000000..d01657b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader @@ -0,0 +1,141 @@ +// This is a premultiply-alpha adaptation of the built-in Unity shader "UI/Default" in Unity 5.6.2 to allow Unity UI stencil masking. + +Shader "Spine/SkeletonGraphic" +{ + Properties + { + [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [Toggle(_CANVAS_GROUP_COMPATIBLE)] _CanvasGroupCompatible("CanvasGroup Compatible", Int) = 0 + _Color ("Tint", Color) = (1,1,1,1) + + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Float) = 8 + [HideInInspector] _Stencil ("Stencil ID", Float) = 0 + [HideInInspector][Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Float) = 0 + [HideInInspector] _StencilWriteMask ("Stencil Write Mask", Float) = 255 + [HideInInspector] _StencilReadMask ("Stencil Read Mask", Float) = 255 + + [HideInInspector] _ColorMask ("Color Mask", Float) = 15 + + [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0 + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags + { + "Queue"="Transparent" + "IgnoreProjector"="True" + "RenderType"="Transparent" + "PreviewType"="Plane" + "CanUseSpriteAtlas"="True" + } + + Stencil + { + Ref [_Stencil] + Comp [_StencilComp] + Pass [_StencilOp] + ReadMask [_StencilReadMask] + WriteMask [_StencilWriteMask] + } + + Cull Off + Lighting Off + ZWrite Off + ZTest [unity_GUIZTestMode] + Fog { Mode Off } + Blend One OneMinusSrcAlpha + ColorMask [_ColorMask] + + Pass + { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma shader_feature _ _CANVAS_GROUP_COMPATIBLE + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + + #include "UnityCG.cginc" + #include "UnityUI.cginc" + + #pragma multi_compile __ UNITY_UI_ALPHACLIP + + struct VertexInput { + float4 vertex : POSITION; + float4 color : COLOR; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct VertexOutput { + float4 vertex : SV_POSITION; + fixed4 color : COLOR; + half2 texcoord : TEXCOORD0; + float4 worldPosition : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO + }; + + fixed4 _Color; + fixed4 _TextureSampleAdd; + float4 _ClipRect; + + VertexOutput vert (VertexInput IN) { + VertexOutput OUT; + + UNITY_SETUP_INSTANCE_ID(IN); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT); + + OUT.worldPosition = IN.vertex; + OUT.vertex = UnityObjectToClipPos(OUT.worldPosition); + OUT.texcoord = IN.texcoord; + + #ifdef UNITY_HALF_TEXEL_OFFSET + OUT.vertex.xy += (_ScreenParams.zw-1.0) * float2(-1,1); + #endif + + OUT.color = IN.color * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + return OUT; + } + + sampler2D _MainTex; + + fixed4 frag (VertexOutput IN) : SV_Target + { + half4 texColor = tex2D(_MainTex, IN.texcoord); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + half4 color = (texColor + _TextureSampleAdd) * IN.color; + #ifdef _CANVAS_GROUP_COMPATIBLE + // CanvasGroup alpha sets vertex color alpha, but does not premultiply it to rgb components. + color.rgb *= IN.color.a; + #endif + + color *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect); + + #ifdef UNITY_UI_ALPHACLIP + clip (color.a - 0.001); + #endif + + return color; + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader.meta new file mode 100644 index 0000000..167123f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/SkeletonGraphic/Spine-SkeletonGraphic.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: fa95b0fb6983c0f40a152e6f9aa82bfb +timeCreated: 1455080068 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader new file mode 100644 index 0000000..a02553f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader @@ -0,0 +1,126 @@ +// - Unlit +// - Premultiplied Alpha Blending (Optional straight alpha input) +// - Double-sided, no depth + +Shader "Spine/Skeleton Fill" { + Properties { + _FillColor ("FillColor", Color) = (1,1,1,1) + _FillPhase ("FillPhase", Range(0, 1)) = 0 + [NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {} + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + Blend One OneMinusSrcAlpha + Cull Off + ZWrite Off + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + float4 _FillColor; + float _FillPhase; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o = (VertexOutput)0; + o.uv = v.uv; + o.vertexColor = v.vertexColor; + o.pos = UnityObjectToClipPos(v.vertex); + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 rawColor = tex2D(_MainTex,i.uv); + float finalAlpha = (rawColor.a * i.vertexColor.a); + + #if defined(_STRAIGHT_ALPHA_INPUT) + rawColor.rgb *= rawColor.a; + #endif + + float3 finalColor = lerp((rawColor.rgb * i.vertexColor.rgb), (_FillColor.rgb * finalAlpha), _FillPhase); // make sure to PMA _FillColor. + return fixed4(finalColor, finalAlpha); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + ZWrite On + ZTest LEqual + + Fog { Mode Off } + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + sampler2D _MainTex; + fixed _Cutoff; + + struct VertexOutput { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + VertexOutput vert (appdata_base v, float4 vertexColor : COLOR) { + VertexOutput o; + o.uvAndAlpha = v.texcoord; + o.uvAndAlpha.a = vertexColor.a; + TRANSFER_SHADOW_CASTER(o) + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + FallBack "Diffuse" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader.meta new file mode 100644 index 0000000..c71933e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Fill.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 45495790b394f894a967dbf44489b57b +timeCreated: 1492385797 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader new file mode 100644 index 0000000..c8f43fd --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader @@ -0,0 +1,80 @@ +// - Vertex Lit + ShadowCaster +// - Premultiplied Alpha Blending (Optional straight alpha input) +// - Double-sided, ZWrite + +Shader "Spine/Skeleton Lit ZWrite" { + Properties { + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.1 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + Tags { "LightMode"="Vertex" "Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent" } + + ZWrite On + Cull Off + Blend One OneMinusSrcAlpha + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + + #define _ALPHA_CLIP + #pragma multi_compile __ POINT SPOT + #include "CGIncludes/Spine-Skeleton-Lit-Common.cginc" + ENDCG + + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + Fog { Mode Off } + ZWrite On + ZTest LEqual + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vertShadow + #pragma fragment fragShadow + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + + #define SHADOW_CUTOFF _ShadowAlphaCutoff + #include "CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc" + + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader.meta new file mode 100644 index 0000000..28243a0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit-ZWrite.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: fde05abf1f7be4b4da1caf8c8de1823a +timeCreated: 1564082883 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader new file mode 100644 index 0000000..b2e90b0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader @@ -0,0 +1,78 @@ +// - Vertex Lit + ShadowCaster +// - Premultiplied Alpha Blending (Optional straight alpha input) +// - Double-sided, no depth + +Shader "Spine/Skeleton Lit" { + Properties { + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + Tags { "LightMode"="Vertex" "Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent" } + + ZWrite Off + Cull Off + Blend One OneMinusSrcAlpha + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + + #pragma multi_compile __ POINT SPOT + #include "CGIncludes/Spine-Skeleton-Lit-Common.cginc" + ENDCG + + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + Fog { Mode Off } + ZWrite On + ZTest LEqual + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vertShadow + #pragma fragment fragShadow + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + + #define SHADOW_CUTOFF _Cutoff + #include "CGIncludes/Spine-Skeleton-Lit-Common-Shadow.cginc" + + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader.meta new file mode 100644 index 0000000..1d0a386 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Lit.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: bd83c75f51f5e23498ae22ffcdfe92c3 +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader new file mode 100644 index 0000000..367ea37 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader @@ -0,0 +1,128 @@ +// Spine/Skeleton Tint +// - Two color tint +// - unlit +// - Premultiplied alpha blending (Optional straight alpha input) +// - No depth, no backface culling, no fog. + +Shader "Spine/Skeleton Tint" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + float4 _Color; + float4 _Black; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor) + float4(((1-texColor.rgb) * _Black.rgb * texColor.a*_Color.a*i.vertexColor.a), 0); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + ZWrite On + ZTest LEqual + + Fog { Mode Off } + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + sampler2D _MainTex; + fixed _Cutoff; + + struct VertexOutput { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + VertexOutput vert (appdata_base v, float4 vertexColor : COLOR) { + VertexOutput o; + o.uvAndAlpha = v.texcoord; + o.uvAndAlpha.a = vertexColor.a; + TRANSFER_SHADOW_CASTER(o) + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader.meta new file mode 100644 index 0000000..1efeec6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-Tint.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 522f03282fd79be47b306e2ef4b593fd +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader new file mode 100644 index 0000000..a596a7e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader @@ -0,0 +1,134 @@ +// Spine/Skeleton Tint Black +// - Two color tint +// - UV2 and UV3 as Black Tint color. +// - Final black tint is (UV black data and _Black/"Black Point") +// - unlit +// - Premultiplied alpha blending (optional straight alpha input) +// - No depth, no backface culling, no fog. + +Shader "Spine/Skeleton Tint Black" { + Properties { + _Color ("Tint Color", Color) = (1,1,1,1) + _Black ("Black Point", Color) = (0,0,0,0) + [NoScaleOffset] _MainTex ("MainTex", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + LOD 100 + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + float4 _Color; + float4 _Black; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' + o.uv = v.uv; + o.vertexColor = v.vertexColor * float4(_Color.rgb * _Color.a, _Color.a); // Combine a PMA version of _Color with vertexColor. + o.uv1 = v.uv1; + o.uv2 = v.uv2; + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor) + float4(((1-texColor.rgb) * (_Black.rgb + float3(i.uv1.r, i.uv1.g, i.uv2.r)) * texColor.a*_Color.a*i.vertexColor.a), 0); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + ZWrite On + ZTest LEqual + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + sampler2D _MainTex; + fixed _Cutoff; + + struct v2f { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + v2f vert (appdata_base v, float4 vertexColor : COLOR) { + v2f o; + TRANSFER_SHADOW_CASTER(o) + o.uvAndAlpha = v.texcoord; + o.uvAndAlpha.a = vertexColor.a; + return o; + } + + float4 frag (v2f i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader.meta new file mode 100644 index 0000000..2801fe0 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton-TintBlack.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: deee23ab4aa38564ead2ac05e112c169 +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader new file mode 100644 index 0000000..10edd6c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader @@ -0,0 +1,118 @@ +Shader "Spine/Skeleton" { + Properties { + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [NoScaleOffset] _MainTex ("Main Texture", 2D) = "black" {} + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + + Fog { Mode Off } + Cull Off + ZWrite Off + Blend One OneMinusSrcAlpha + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.uv; + o.vertexColor = v.vertexColor; + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 texColor = tex2D(_MainTex, i.uv); + + #if defined(_STRAIGHT_ALPHA_INPUT) + texColor.rgb *= texColor.a; + #endif + + return (texColor * i.vertexColor); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + ZWrite On + ZTest LEqual + + Fog { Mode Off } + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + sampler2D _MainTex; + fixed _Cutoff; + + struct VertexOutput { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + VertexOutput vert (appdata_base v, float4 vertexColor : COLOR) { + VertexOutput o; + o.uvAndAlpha = v.texcoord; + o.uvAndAlpha.a = vertexColor.a; + TRANSFER_SHADOW_CASTER(o) + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader.meta new file mode 100644 index 0000000..06c4b0c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Skeleton.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1e8a610c9e01c3648bac42585e5fc676 +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader new file mode 100644 index 0000000..75c1d49 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader @@ -0,0 +1,127 @@ +// - Unlit +// - Premultiplied Alpha Blending (Optional straight alpha input) +// - Double-sided, no depth + +Shader "Spine/Special/Skeleton Grayscale" { + Properties { + _GrayPhase ("Phase", Range(0, 1)) = 1 + [NoScaleOffset] _MainTex ("MainTex", 2D) = "white" {} + _Cutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + [Toggle(_STRAIGHT_ALPHA_INPUT)] _StraightAlphaInput("Straight Alpha Texture", Int) = 0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" } + Blend One OneMinusSrcAlpha + Cull Off + ZWrite Off + Lighting Off + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass { + Name "Normal" + + CGPROGRAM + #pragma shader_feature _ _STRAIGHT_ALPHA_INPUT + #pragma vertex vert + #pragma fragment frag + #include "UnityCG.cginc" + sampler2D _MainTex; + float _GrayPhase; + + struct VertexInput { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + struct VertexOutput { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 vertexColor : COLOR; + }; + + VertexOutput vert (VertexInput v) { + VertexOutput o = (VertexOutput)0; + o.uv = v.uv; + o.vertexColor = v.vertexColor; + o.pos = UnityObjectToClipPos(v.vertex); + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + float4 rawColor = tex2D(_MainTex,i.uv); + float finalAlpha = (rawColor.a * i.vertexColor.a); + + #if defined(_STRAIGHT_ALPHA_INPUT) + rawColor.rgb *= rawColor.a; + #endif + + rawColor.rgb *= i.vertexColor.rgb; + + float3 finalColor = lerp(rawColor.rgb, dot(rawColor.rgb, float3(0.3, 0.59, 0.11)), _GrayPhase); + return fixed4(finalColor, finalAlpha); + } + ENDCG + } + + Pass { + Name "Caster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + ZWrite On + ZTest LEqual + + Fog { Mode Off } + Cull Off + Lighting Off + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma multi_compile_shadowcaster + #pragma fragmentoption ARB_precision_hint_fastest + #include "UnityCG.cginc" + sampler2D _MainTex; + fixed _Cutoff; + + struct VertexOutput { + V2F_SHADOW_CASTER; + float4 uvAndAlpha : TEXCOORD1; + }; + + VertexOutput vert (appdata_base v, float4 vertexColor : COLOR) { + VertexOutput o; + o.uvAndAlpha = v.texcoord; + o.uvAndAlpha.a = vertexColor.a; + TRANSFER_SHADOW_CASTER(o) + return o; + } + + float4 frag (VertexOutput i) : SV_Target { + fixed4 texcol = tex2D(_MainTex, i.uvAndAlpha.xy); + clip(texcol.a * i.uvAndAlpha.a - _Cutoff); + SHADOW_CASTER_FRAGMENT(i) + } + ENDCG + } + } + FallBack "Diffuse" + CustomEditor "SpineShaderWithOutlineGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader.meta new file mode 100644 index 0000000..6db4577 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Spine-Special-Skeleton-Grayscale.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ea7e7c05f36541b4bb280f98ebda8ba1 +timeCreated: 1492385797 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite.meta new file mode 100644 index 0000000..f997503 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a831a8ed72a588a48b2fb892e7f37371 +folderAsset: yes +timeCreated: 1479419399 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes.meta new file mode 100644 index 0000000..009f684 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4b6fb48f295cd8248a7566315212a3c2 +folderAsset: yes +timeCreated: 1494092464 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc new file mode 100644 index 0000000..1ae731e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc @@ -0,0 +1,76 @@ +#ifndef SHADER_MATHS_INCLUDED +#define SHADER_MATHS_INCLUDED + +#if defined(USE_LWRP) +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" +#elif defined(USE_URP) +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" +#else +#include "UnityCG.cginc" +#endif + +//////////////////////////////////////// +// Maths functions +// + +inline half3 safeNormalize(half3 inVec) +{ + half dp3 = max(0.001f, dot(inVec, inVec)); + return inVec * rsqrt(dp3); +} + +inline float dotClamped(float3 a, float3 b) +{ + #if (SHADER_TARGET < 30 || defined(SHADER_API_PS3)) + return saturate(dot(a, b)); + #else + return max(0.0h, dot(a, b)); + #endif +} + +inline float oneDividedBy(float value) +{ + //Catches NANs + float sign_value = sign(value); + float sign_value_squared = sign_value*sign_value; + return sign_value_squared / ( value + sign_value_squared - 1.0); +} + +inline half pow5 (half x) +{ + return x*x*x*x*x; +} + +inline float4 quat_from_axis_angle(float3 axis, float angleRadians) +{ + float4 qr; + float half_angle = (angleRadians * 0.5); + qr.x = axis.x * sin(half_angle); + qr.y = axis.y * sin(half_angle); + qr.z = axis.z * sin(half_angle); + qr.w = cos(half_angle); + return qr; +} + +inline float3 rotate_vertex_position(float3 position, float3 axis, float angleRadians) +{ + float4 q = quat_from_axis_angle(axis, angleRadians); + float3 v = position.xyz; + return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v); +} + +float3 EncodeFloatRGB(float value) +{ + const float max24int = 256*256*256-1; + float3 decomp = floor( value * float3( max24int/(256*256), max24int/256, max24int ) ) / 255.0; + decomp.z -= decomp.y * 256.0; + decomp.y -= decomp.x * 256.0; + return decomp; +} + +float DecodeFloatRGB(float3 decomp) +{ + return dot( decomp.xyz, float3( 255.0/256, 255.0/(256*256), 255.0/(256*256*256) ) ); +} + +#endif // SHADER_MATHS_INCLUDED diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc.meta new file mode 100644 index 0000000..348f3ac --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderMaths.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e1de23de2025abe4a84ff2edd3f24491 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc new file mode 100644 index 0000000..c891895 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc @@ -0,0 +1,423 @@ +// Upgrade NOTE: upgraded instancing buffer 'PerDrawSprite' to new syntax. + +// Upgrade NOTE: upgraded instancing buffer 'PerDrawSprite' to new syntax. + +#ifndef SHADER_SHARED_INCLUDED +#define SHADER_SHARED_INCLUDED + +#if defined(USE_LWRP) +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" +#elif defined(USE_URP) +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" +#else +#include "UnityCG.cginc" +#endif + +#ifdef UNITY_INSTANCING_ENABLED + + UNITY_INSTANCING_BUFFER_START(PerDrawSprite) + // SpriteRenderer.Color while Non-Batched/Instanced. + fixed4 unity_SpriteRendererColorArray[UNITY_INSTANCED_ARRAY_SIZE]; + // this could be smaller but that's how bit each entry is regardless of type + float4 unity_SpriteFlipArray[UNITY_INSTANCED_ARRAY_SIZE]; + UNITY_INSTANCING_BUFFER_END(PerDrawSprite) + + #define _RendererColor unity_SpriteRendererColorArray[unity_InstanceID] + #define _Flip unity_SpriteFlipArray[unity_InstanceID] + +#endif // instancing + +CBUFFER_START(UnityPerDrawSprite) +#ifndef UNITY_INSTANCING_ENABLED + fixed4 _RendererColor; + float4 _Flip; +#endif + float _EnableExternalAlpha; +CBUFFER_END + +//////////////////////////////////////// +// Space functions +// + +inline float4 calculateWorldPos(float4 vertex) +{ + return mul(unity_ObjectToWorld, vertex); +} + +#if defined(USE_LWRP) || defined(USE_URP) +// snaps post-transformed position to screen pixels +inline float4 UnityPixelSnap(float4 pos) +{ + float2 hpc = _ScreenParams.xy * 0.5f; +#if SHADER_API_PSSL + // sdk 4.5 splits round into v_floor_f32(x+0.5) ... sdk 5.0 uses v_rndne_f32, for compatabilty we use the 4.5 version + float2 temp = ((pos.xy / pos.w) * hpc) + float2(0.5f, 0.5f); + float2 pixelPos = float2(__v_floor_f32(temp.x), __v_floor_f32(temp.y)); +#else + float2 pixelPos = round((pos.xy / pos.w) * hpc); +#endif + pos.xy = pixelPos / hpc * pos.w; + return pos; +} +#endif + +inline float4 calculateLocalPos(float4 vertex) +{ +#if !defined(USE_LWRP) && !defined(USE_URP) +#ifdef UNITY_INSTANCING_ENABLED + vertex.xy *= _Flip.xy; +#endif +#endif + +#if defined(USE_LWRP) || defined(USE_URP) + float4 pos = TransformObjectToHClip(vertex.xyz); +#else + float4 pos = UnityObjectToClipPos(vertex); +#endif + +#ifdef PIXELSNAP_ON + pos = UnityPixelSnap(pos); +#endif + + return pos; +} + +inline half3 calculateWorldNormal(float3 normal) +{ +#if defined(USE_LWRP) || defined(USE_URP) + return TransformObjectToWorldNormal(normal); +#else + return UnityObjectToWorldNormal(normal); +#endif +} + +//////////////////////////////////////// +// Normal map functions +// + +#if defined(_NORMALMAP) + +uniform sampler2D _BumpMap; +uniform half _BumpScale; + +half3 UnpackScaleNormal(half4 packednormal, half bumpScale) +{ + #if defined(UNITY_NO_DXT5nm) + return packednormal.xyz * 2 - 1; + #else + half3 normal; + normal.xy = (packednormal.wy * 2 - 1); + // Note: we allow scaled normals in LWRP since we might be using fewer instructions. + #if (SHADER_TARGET >= 30) || defined(USE_LWRP) || defined(USE_URP) + // SM2.0: instruction count limitation + // SM2.0: normal scaler is not supported + normal.xy *= bumpScale; + #endif + normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy))); + return normal; + #endif +} + + +inline half3 calculateWorldTangent(float4 tangent) +{ +#if defined(USE_LWRP) || defined(USE_URP) + return TransformObjectToWorldDir(tangent.xyz); +#else + return UnityObjectToWorldDir(tangent); +#endif +} + +inline half3 calculateWorldBinormal(half3 normalWorld, half3 tangentWorld, float tangentSign) +{ + //When calculating the binormal we have to flip it when the mesh is scaled negatively. + //Normally this would just be unity_WorldTransformParams.w but this isn't set correctly by Unity for its SpriteRenderer meshes so get from objectToWorld matrix scale instead. + half worldTransformSign = sign(unity_ObjectToWorld[0][0] * unity_ObjectToWorld[1][1] * unity_ObjectToWorld[2][2]); + half sign = tangentSign * worldTransformSign; + return cross(normalWorld, tangentWorld) * sign; +} + +inline half3 calculateNormalFromBumpMap(float2 texUV, half3 tangentWorld, half3 binormalWorld, half3 normalWorld) +{ + half3 localNormal = UnpackScaleNormal(tex2D(_BumpMap, texUV), _BumpScale); + half3x3 rotation = half3x3(tangentWorld, binormalWorld, normalWorld); + half3 normal = normalize(mul(localNormal, rotation)); + return normal; +} + +#endif // _NORMALMAP + +//////////////////////////////////////// +// Blending functions +// + +inline fixed4 prepareLitPixelForOutput(fixed4 finalPixel, fixed4 color) : SV_Target +{ +#if defined(_ALPHABLEND_ON) + //Normal Alpha + finalPixel.rgb *= finalPixel.a; +#elif defined(_ALPHAPREMULTIPLY_ON) + //Pre multiplied alpha + finalPixel.rgb *= color.a; +#elif defined(_MULTIPLYBLEND) + //Multiply + finalPixel = lerp(fixed4(1,1,1,1), finalPixel, finalPixel.a); +#elif defined(_MULTIPLYBLEND_X2) + //Multiply x2 + finalPixel.rgb *= 2.0f; + finalPixel = lerp(fixed4(0.5f,0.5f,0.5f,0.5f), finalPixel, finalPixel.a); +#elif defined(_ADDITIVEBLEND) + //Additive + finalPixel *= 2.0f; + finalPixel.rgb *= color.a; +#elif defined(_ADDITIVEBLEND_SOFT) + //Additive soft + finalPixel.rgb *= finalPixel.a; +#else + //Opaque + finalPixel.a = 1; +#endif + return finalPixel; +} + +inline fixed4 calculateLitPixel(fixed4 texureColor, fixed4 color, fixed3 lighting) : SV_Target +{ + fixed4 finalPixel = texureColor * color * fixed4(lighting, 1); + finalPixel = prepareLitPixelForOutput(finalPixel, color); + return finalPixel; +} + +inline fixed4 calculateLitPixel(fixed4 texureColor, fixed3 lighting) : SV_Target +{ + // note: we let the optimizer work, removed duplicate code. + return calculateLitPixel(texureColor, fixed4(1, 1, 1, 1), lighting); +} + +inline fixed4 calculateAdditiveLitPixel(fixed4 texureColor, fixed4 color, fixed3 lighting) : SV_Target +{ + fixed4 finalPixel; + +#if defined(_ALPHABLEND_ON) || defined(_MULTIPLYBLEND) || defined(_MULTIPLYBLEND_X2) || defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT) + //Normal Alpha, Additive and Multiply modes + finalPixel.rgb = (texureColor.rgb * lighting * color.rgb) * (texureColor.a * color.a); + finalPixel.a = 1.0; +#elif defined(_ALPHAPREMULTIPLY_ON) + //Pre multiplied alpha + finalPixel.rgb = texureColor.rgb * lighting * color.rgb * color.a; + finalPixel.a = 1.0; +#else + //Opaque + finalPixel.rgb = texureColor.rgb * lighting * color.rgb; + finalPixel.a = 1.0; +#endif + + return finalPixel; +} + +inline fixed4 calculateAdditiveLitPixel(fixed4 texureColor, fixed3 lighting) : SV_Target +{ + fixed4 finalPixel; + +#if defined(_ALPHABLEND_ON) || defined(_MULTIPLYBLEND) || defined(_MULTIPLYBLEND_X2) || defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT) + //Normal Alpha, Additive and Multiply modes + finalPixel.rgb = (texureColor.rgb * lighting) * texureColor.a; + finalPixel.a = 1.0; +#else + //Pre multiplied alpha and Opaque + finalPixel.rgb = texureColor.rgb * lighting; + finalPixel.a = 1.0; +#endif + + return finalPixel; +} + +inline fixed4 calculatePixel(fixed4 texureColor, fixed4 color) : SV_Target +{ + // note: we let the optimizer work, removed duplicate code. + return calculateLitPixel(texureColor, color, fixed3(1, 1, 1)); +} + +inline fixed4 calculatePixel(fixed4 texureColor) : SV_Target +{ + // note: we let the optimizer work, removed duplicate code. + return calculateLitPixel(texureColor, fixed4(1, 1, 1, 1), fixed3(1, 1, 1)); +} + +//////////////////////////////////////// +// Alpha Clipping +// + +#if defined(_ALPHA_CLIP) + +uniform fixed _Cutoff; + +#define ALPHA_CLIP(pixel, color) clip((pixel.a * color.a) - _Cutoff); + +#else + +#define ALPHA_CLIP(pixel, color) + +#endif + +//////////////////////////////////////// +// Color functions +// + +uniform fixed4 _Color; + +inline fixed4 calculateVertexColor(fixed4 color) +{ + return color * _Color; +} + +#if defined(_COLOR_ADJUST) + +uniform float _Hue; +uniform float _Saturation; +uniform float _Brightness; +uniform fixed4 _OverlayColor; + +float3 rgb2hsv(float3 c) +{ + float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + float4 p = lerp(float4(c.bg, K.wz), float4(c.gb, K.xy), step(c.b, c.g)); + float4 q = lerp(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r)); + + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +float3 hsv2rgb(float3 c) +{ + c = float3(c.x, clamp(c.yz, 0.0, 1.0)); + float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + float3 p = abs(frac(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * lerp(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} + +inline fixed4 adjustColor(fixed4 color) +{ + float3 hsv = rgb2hsv(color.rgb); + + hsv.x += _Hue; + hsv.y *= _Saturation; + hsv.z *= _Brightness; + + color.rgb = hsv2rgb(hsv); + + return color; +} + +#define COLORISE(pixel) pixel.rgb = lerp(pixel.rgb, _OverlayColor.rgb, _OverlayColor.a * pixel.a); +#define COLORISE_ADDITIVE(pixel) pixel.rgb = ((1.0-_OverlayColor.a) * pixel.rgb); + +#else // !_COLOR_ADJUST + +#define COLORISE(pixel) +#define COLORISE_ADDITIVE(pixel) + +#endif // !_COLOR_ADJUST + +//////////////////////////////////////// +// Fog +// + +#if defined(_FOG) && (defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)) + +inline fixed4 applyFog(fixed4 pixel, float fogCoordOrFactorAtLWRP) +{ +#if defined(_ADDITIVEBLEND) || defined(_ADDITIVEBLEND_SOFT) + //In additive mode blend from clear to black based on luminance + float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11; + fixed4 fogColor = lerp(fixed4(0,0,0,0), fixed4(0,0,0,1), luminance); +#elif defined(_MULTIPLYBLEND) + //In multiplied mode fade to white based on inverse luminance + float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11; + fixed4 fogColor = lerp(fixed4(1,1,1,1), fixed4(0,0,0,0), luminance); +#elif defined(_MULTIPLYBLEND_X2) + //In multipliedx2 mode fade to grey based on inverse luminance + float luminance = pixel.r * 0.3 + pixel.g * 0.59 + pixel.b * 0.11; + fixed4 fogColor = lerp(fixed4(0.5f,0.5f,0.5f,0.5f), fixed4(0,0,0,0), luminance); +#elif defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON) + //In alpha blended modes blend to fog color based on pixel alpha + fixed4 fogColor = lerp(fixed4(0,0,0,0), unity_FogColor, pixel.a); +#else + //In opaque mode just return fog color; + fixed4 fogColor = unity_FogColor; +#endif + + #if defined(USE_LWRP) || defined(USE_URP) + pixel.rgb = MixFogColor(pixel.rgb, fogColor.rgb, fogCoordOrFactorAtLWRP); + #else + UNITY_APPLY_FOG_COLOR(fogCoordOrFactorAtLWRP, pixel, fogColor); + #endif + + return pixel; +} + +#define APPLY_FOG(pixel, input) pixel = applyFog(pixel, input.fogCoord); +#define APPLY_FOG_LWRP(pixel, fogFactor) pixel = applyFog(pixel, fogFactor); + +#define APPLY_FOG_ADDITIVE(pixel, input) \ + UNITY_APPLY_FOG_COLOR(input.fogCoord, pixel.rgb, fixed4(0,0,0,0)); // fog towards black in additive pass + +#else + +#define APPLY_FOG(pixel, input) +#define APPLY_FOG_LWRP(pixel, fogFactor) +#define APPLY_FOG_ADDITIVE(pixel, input) + +#endif + +//////////////////////////////////////// +// Texture functions +// + +uniform sampler2D _MainTex; + +#if ETC1_EXTERNAL_ALPHA +//External alpha texture for ETC1 compression +uniform sampler2D _AlphaTex; +#endif //ETC1_EXTERNAL_ALPHA + +#if _TEXTURE_BLEND +uniform sampler2D _BlendTex; +uniform float _BlendAmount; + +inline fixed4 calculateBlendedTexturePixel(float2 texcoord) +{ + return (1.0-_BlendAmount) * tex2D(_MainTex, texcoord) + _BlendAmount * tex2D(_BlendTex, texcoord); +} +#endif // _TEXTURE_BLEND + +inline fixed4 calculateTexturePixel(float2 texcoord) +{ + fixed4 pixel; + +#if _TEXTURE_BLEND + pixel = calculateBlendedTexturePixel(texcoord); +#else + pixel = tex2D(_MainTex, texcoord); +#endif // !_TEXTURE_BLEND + +#if ETC1_EXTERNAL_ALPHA + fixed4 alpha = tex2D (_AlphaTex, texcoord); + pixel.a = lerp (pixel.a, alpha.r, _EnableExternalAlpha); +#endif + +#if defined(_COLOR_ADJUST) + pixel = adjustColor(pixel); +#endif // _COLOR_ADJUST + + return pixel; +} + +uniform fixed4 _MainTex_ST; + +inline float2 calculateTextureCoord(float4 texcoord) +{ + return TRANSFORM_TEX(texcoord, _MainTex); +} + +#endif // SHADER_SHARED_INCLUDED diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc.meta new file mode 100644 index 0000000..7e1ddf1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/ShaderShared.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c18c5cab567666f4d8c5b2bd4e61390b +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc new file mode 100644 index 0000000..018ca93 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc @@ -0,0 +1,200 @@ +#ifndef SPRITE_LIGHTING_INCLUDED +#define SPRITE_LIGHTING_INCLUDED + +//Check for using mesh normals +#if !defined(_FIXED_NORMALS_VIEWSPACE) && !defined(_FIXED_NORMALS_VIEWSPACE_BACKFACE) && !defined(_FIXED_NORMALS_MODELSPACE) && !defined(_FIXED_NORMALS_MODELSPACE_BACKFACE) +#define MESH_NORMALS +#endif + +//Check for fixing backfacing tangents +#if defined(_FIXED_NORMALS_VIEWSPACE_BACKFACE) || defined(_FIXED_NORMALS_MODELSPACE_BACKFACE) +#define FIXED_NORMALS_BACKFACE_RENDERING +#endif + +//////////////////////////////////////// +// Vertex structs +// + +struct VertexInput +{ + float4 vertex : POSITION; + float4 texcoord : TEXCOORD0; + float4 color : COLOR; +#if defined(MESH_NORMALS) + float3 normal : NORMAL; +#endif // _FIXED_NORMALS +#if defined(_NORMALMAP) + float4 tangent : TANGENT; +#endif // _NORMALMAP + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +//////////////////////////////////////// +// Normal functions +// + +uniform float4 _FixedNormal = float4(0, 0, 1, 1); + +inline float3 getFixedNormal() +{ + return _FixedNormal.xyz; +} + +inline float calculateBackfacingSign(float3 worldPos) +{ + //If we're using fixed normals and mesh is facing away from camera, flip tangentSign + //Unity uses a left handed coordinate system so camera always looks down the negative z axis + float3 cameraForward = float3(0,0,-1); + float3 meshWorldForward = mul((float3x3)unity_ObjectToWorld, cameraForward); + float3 toCamera = _WorldSpaceCameraPos - worldPos; + return sign(dot(toCamera, meshWorldForward)); +} + +inline half3 calculateSpriteWorldNormal(VertexInput vertex, float backFaceSign) +{ +#if defined(MESH_NORMALS) + + return calculateWorldNormal(vertex.normal); + +#else // !MESH_NORMALS + + float3 normal = getFixedNormal(); + +#if defined(_FIXED_NORMALS_VIEWSPACE) || defined(_FIXED_NORMALS_VIEWSPACE_BACKFACE) + //View space fixed normal + //Rotate fixed normal by inverse view matrix to convert the fixed normal into world space + float3x3 invView = transpose((float3x3)UNITY_MATRIX_V); + return normalize(mul(invView, normal)); +#else + //Model space fixed normal. +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) + //If back face rendering is enabled and the sprite is facing away from the camera (ie we're rendering the backface) then need to flip the normal + normal *= backFaceSign; +#endif + return calculateWorldNormal(normal); +#endif + +#endif // !MESH_NORMALS +} + +inline half3 calculateSpriteViewNormal(VertexInput vertex, float backFaceSign) +{ +#if defined(MESH_NORMALS) + + return normalize(mul((float3x3)UNITY_MATRIX_IT_MV, vertex.normal)); + +#else // !MESH_NORMALS + + float3 normal = getFixedNormal(); + +#if defined(_FIXED_NORMALS_VIEWSPACE) || defined(_FIXED_NORMALS_VIEWSPACE_BACKFACE) + //View space fixed normal + return normal; +#else + //Model space fixed normal +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) + //If back face rendering is enabled and the sprite is facing away from the camera (ie we're rendering the backface) then need to flip the normal + normal *= backFaceSign; +#endif + return normalize(mul((float3x3)UNITY_MATRIX_IT_MV, normal)); +#endif + +#endif // !MESH_NORMALS +} + +//////////////////////////////////////// +// Normal map functions +// + +#if defined(_NORMALMAP) + +inline half3 calculateSpriteWorldBinormal(VertexInput vertex, half3 normalWorld, half3 tangentWorld, float backFaceSign) +{ + float tangentSign = vertex.tangent.w; + +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) + tangentSign *= backFaceSign; +#endif + + return calculateWorldBinormal(normalWorld, tangentWorld, tangentSign); +} + +#endif // _NORMALMAP + +#if defined(_DIFFUSE_RAMP) + + +//////////////////////////////////////// +// Diffuse ramp functions +// + +//Disable for softer, more traditional diffuse ramping +#define HARD_DIFFUSE_RAMP + +uniform sampler2D _DiffuseRamp; + +inline fixed3 calculateDiffuseRamp(float ramp) +{ + return tex2D(_DiffuseRamp, float2(ramp, ramp)).rgb; +} + +inline fixed3 calculateRampedDiffuse(fixed3 lightColor, float attenuation, float angleDot) +{ + float d = angleDot * 0.5 + 0.5; +#if defined(HARD_DIFFUSE_RAMP) + half3 ramp = calculateDiffuseRamp(d * attenuation * 2); + return lightColor * ramp; +#else + half3 ramp = calculateDiffuseRamp(d); + return lightColor * ramp * (attenuation * 2); +#endif +} +#endif // _DIFFUSE_RAMP + +//////////////////////////////////////// +// Rim Lighting functions +// + +#ifdef _RIM_LIGHTING + +uniform float _RimPower; +uniform fixed4 _RimColor; + +inline fixed3 applyRimLighting(fixed3 posWorld, fixed3 normalWorld, fixed4 pixel) : SV_Target +{ + fixed3 viewDir = normalize(_WorldSpaceCameraPos - posWorld); + float invDot = 1.0 - saturate(dot(normalWorld, viewDir)); + float rimPower = pow(invDot, _RimPower); + float rim = saturate(rimPower * _RimColor.a); + +#if defined(_DIFFUSE_RAMP) + rim = calculateDiffuseRamp(rim).r; +#endif + + return lerp(pixel.rgb, _RimColor.xyz * pixel.a, rim); +} + +#endif //_RIM_LIGHTING + +//////////////////////////////////////// +// Emission functions +// + +#ifdef _EMISSION + +uniform sampler2D _EmissionMap; +uniform fixed4 _EmissionColor; +uniform float _EmissionPower; + + +#define APPLY_EMISSION(diffuse, uv) diffuse += tex2D(_EmissionMap, uv).rgb * _EmissionColor.rgb * _EmissionPower; +#define APPLY_EMISSION_SPECULAR(pixel, uv) pixel.rgb += (tex2D(_EmissionMap, uv).rgb * _EmissionColor.rgb * _EmissionPower) * pixel.a; + +#else //!_EMISSION + +#define APPLY_EMISSION(diffuse, uv) +#define APPLY_EMISSION_SPECULAR(pixel, uv) + +#endif //!_EMISSION + +#endif // SPRITE_LIGHTING_INCLUDED \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc.meta new file mode 100644 index 0000000..b25bff3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteLighting.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0cfb891658099ca4bb0c9544c08e60f9 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc new file mode 100644 index 0000000..8c763f4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc @@ -0,0 +1,252 @@ +#ifndef SPRITE_PIXEL_LIGHTING_INCLUDED +#define SPRITE_PIXEL_LIGHTING_INCLUDED + +#include "ShaderShared.cginc" +#include "SpriteLighting.cginc" +#include "SpriteSpecular.cginc" +#include "AutoLight.cginc" + +//////////////////////////////////////// +// Defines +// + +//////////////////////////////////////// +// Vertex output struct +// + +#if defined(_NORMALMAP) + #define _VERTEX_LIGHTING_INDEX TEXCOORD5 + #define _LIGHT_COORD_INDEX_0 6 + #define _LIGHT_COORD_INDEX_1 7 + #define _FOG_COORD_INDEX 8 +#else + #define _VERTEX_LIGHTING_INDEX TEXCOORD3 + #define _LIGHT_COORD_INDEX_0 4 + #define _LIGHT_COORD_INDEX_1 5 + #define _FOG_COORD_INDEX 6 +#endif // _NORMALMAP + +struct VertexOutput +{ + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 texcoord : TEXCOORD0; + float4 posWorld : TEXCOORD1; + half3 normalWorld : TEXCOORD2; +#if defined(_NORMALMAP) + half3 tangentWorld : TEXCOORD3; + half3 binormalWorld : TEXCOORD4; +#endif // _NORMALMAP + fixed3 vertexLighting : _VERTEX_LIGHTING_INDEX; + LIGHTING_COORDS(_LIGHT_COORD_INDEX_0, _LIGHT_COORD_INDEX_1) +#if defined(_FOG) + UNITY_FOG_COORDS(_FOG_COORD_INDEX) +#endif // _FOG + + UNITY_VERTEX_OUTPUT_STEREO +}; + +//////////////////////////////////////// +// Light calculations +// + +uniform fixed4 _LightColor0; + +inline fixed3 calculateLightDiffuse(VertexOutput input, float3 normalWorld, inout fixed4 albedo) +{ + //For directional lights _WorldSpaceLightPos0.w is set to zero + float3 lightWorldDirection = normalize(_WorldSpaceLightPos0.xyz - input.posWorld.xyz * _WorldSpaceLightPos0.w); + + float attenuation = LIGHT_ATTENUATION(input); + float angleDot = max(0, dot(normalWorld, lightWorldDirection)); + +#if defined(_DIFFUSE_RAMP) + fixed3 lightDiffuse = calculateRampedDiffuse(_LightColor0.rgb, attenuation, angleDot); +#else + fixed3 lightDiffuse = _LightColor0.rgb * (attenuation * angleDot); +#endif // _DIFFUSE_RAMP + + return lightDiffuse; +} + +inline float3 calculateNormalWorld(VertexOutput input) +{ +#if defined(_NORMALMAP) + return calculateNormalFromBumpMap(input.texcoord, input.tangentWorld, input.binormalWorld, input.normalWorld); +#else + return input.normalWorld; +#endif +} + +fixed3 calculateVertexLighting(float3 posWorld, float3 normalWorld) +{ + fixed3 vertexLighting = fixed3(0,0,0); + +#ifdef VERTEXLIGHT_ON + //Get approximated illumination from non-important point lights + vertexLighting = Shade4PointLights ( unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0, + unity_LightColor[0].rgb, unity_LightColor[1].rgb, unity_LightColor[2].rgb, unity_LightColor[3].rgb, + unity_4LightAtten0, posWorld, normalWorld) * 0.5; +#endif + + return vertexLighting; +} + +fixed3 calculateAmbientLight(half3 normalWorld) +{ +#if defined(_SPHERICAL_HARMONICS) + fixed3 ambient = ShadeSH9(half4(normalWorld, 1.0)); +#else + fixed3 ambient = unity_AmbientSky.rgb; +#endif + return ambient; +} + +#if defined(SPECULAR) + +fixed4 calculateSpecularLight(SpecularCommonData s, float3 viewDir, float3 normal, float3 lightDir, float3 lightColor, half3 ambient) +{ + SpecularLightData data = calculatePhysicsBasedSpecularLight (s.specColor, s.oneMinusReflectivity, s.smoothness, normal, viewDir, lightDir, lightColor, ambient, unity_IndirectSpecColor.rgb); + fixed4 pixel = calculateLitPixel(fixed4(s.diffColor, s.alpha), data.lighting); + pixel.rgb += data.specular * s.alpha; + return pixel; +} + +fixed4 calculateSpecularLightAdditive(SpecularCommonData s, float3 viewDir, float3 normal, float3 lightDir, float3 lightColor) +{ + SpecularLightData data = calculatePhysicsBasedSpecularLight (s.specColor, s.oneMinusReflectivity, s.smoothness, normal, viewDir, lightDir, lightColor, half3(0,0,0), half3(0,0,0)); + fixed4 pixel = calculateAdditiveLitPixel(fixed4(s.diffColor, s.alpha), data.lighting); + pixel.rgb += data.specular * s.alpha; + return pixel; +} + +#endif //SPECULAR + +//////////////////////////////////////// +// Vertex program +// + +VertexOutput vert(VertexInput v) +{ + VertexOutput output; + + UNITY_SETUP_INSTANCE_ID(input); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); + + output.pos = calculateLocalPos(v.vertex); + output.color = calculateVertexColor(v.color); + output.texcoord = calculateTextureCoord(v.texcoord); + output.posWorld = calculateWorldPos(v.vertex); + + float backFaceSign = 1; +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) + backFaceSign = calculateBackfacingSign(output.posWorld.xyz); +#endif + + output.normalWorld = calculateSpriteWorldNormal(v, backFaceSign); + output.vertexLighting = calculateVertexLighting(output.posWorld, output.normalWorld); + +#if defined(_NORMALMAP) + output.tangentWorld = calculateWorldTangent(v.tangent); + output.binormalWorld = calculateSpriteWorldBinormal(v, output.normalWorld, output.tangentWorld, backFaceSign); +#endif + + TRANSFER_VERTEX_TO_FRAGMENT(output) + +#if defined(_FOG) + UNITY_TRANSFER_FOG(output,output.pos); +#endif // _FOG + + return output; +} + +//////////////////////////////////////// +// Fragment programs +// + +fixed4 fragBase(VertexOutput input) : SV_Target +{ + fixed4 texureColor = calculateTexturePixel(input.texcoord); + ALPHA_CLIP(texureColor, input.color) + + //Get normal direction + fixed3 normalWorld = calculateNormalWorld(input); + + //Get Ambient diffuse + fixed3 ambient = calculateAmbientLight(normalWorld); + + +#if defined(SPECULAR) + + //For directional lights _WorldSpaceLightPos0.w is set to zero + float3 lightWorldDirection = normalize(_WorldSpaceLightPos0.xyz - input.posWorld.xyz * _WorldSpaceLightPos0.w); + float attenuation = LIGHT_ATTENUATION(input); + + //Returns pixel lit by light, texture color should inlcluded alpha + half3 viewDir = normalize(_WorldSpaceCameraPos - input.posWorld.xyz); + fixed4 pixel = calculateSpecularLight(getSpecularData(input.texcoord.xy, texureColor, input.color), viewDir, normalWorld, lightWorldDirection, _LightColor0.rgb * attenuation, ambient + input.vertexLighting); + + APPLY_EMISSION_SPECULAR(pixel, input.texcoord) + +#else + + //Get primary pixel light diffuse + fixed3 diffuse = calculateLightDiffuse(input, normalWorld, texureColor); + + //Combine along with vertex lighting for the base lighting pass + fixed3 lighting = ambient + diffuse + input.vertexLighting; + + APPLY_EMISSION(lighting, input.texcoord) + + fixed4 pixel = calculateLitPixel(texureColor, input.color, lighting); + +#endif + +#if defined(_RIM_LIGHTING) + pixel.rgb = applyRimLighting(input.posWorld, normalWorld, pixel); +#endif + + COLORISE(pixel) + APPLY_FOG(pixel, input) + + return pixel; +} + +fixed4 fragAdd(VertexOutput input) : SV_Target +{ + fixed4 texureColor = calculateTexturePixel(input.texcoord); + +#if defined(_COLOR_ADJUST) + texureColor = adjustColor(texureColor); +#endif // _COLOR_ADJUST + + ALPHA_CLIP(texureColor, input.color) + + //Get normal direction + fixed3 normalWorld = calculateNormalWorld(input); + +#if defined(SPECULAR) + + //For directional lights _WorldSpaceLightPos0.w is set to zero + float3 lightWorldDirection = normalize(_WorldSpaceLightPos0.xyz - input.posWorld.xyz * _WorldSpaceLightPos0.w); + float attenuation = LIGHT_ATTENUATION(input); + + half3 viewDir = normalize(_WorldSpaceCameraPos - input.posWorld.xyz); + fixed4 pixel = calculateSpecularLightAdditive(getSpecularData(input.texcoord.xy, texureColor, input.color), viewDir, normalWorld, lightWorldDirection, _LightColor0.rgb * attenuation); + +#else + + //Get light diffuse + fixed3 lighting = calculateLightDiffuse(input, normalWorld, texureColor); + fixed4 pixel = calculateAdditiveLitPixel(texureColor, input.color, lighting); + +#endif + + COLORISE_ADDITIVE(pixel) + APPLY_FOG_ADDITIVE(pixel, input) + + return pixel; +} + + +#endif // SPRITE_PIXEL_LIGHTING_INCLUDED \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc.meta new file mode 100644 index 0000000..73da285 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpritePixelLighting.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 7ffc57e05c42ec748838bea0a3aff9f9 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc new file mode 100644 index 0000000..401ed89 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc @@ -0,0 +1,51 @@ +#ifndef SPRITE_SHADOWS_INCLUDED +#define SPRITE_SHADOWS_INCLUDED + +#include "ShaderShared.cginc" + +//////////////////////////////////////// +// Vertex structs +// + +struct vertexInput +{ + float4 vertex : POSITION; + float4 texcoord : TEXCOORD0; +}; + +struct vertexOutput +{ + V2F_SHADOW_CASTER; + float4 texcoordAndAlpha : TEXCOORD1; +}; + +//////////////////////////////////////// +// Vertex program +// + +vertexOutput vert(vertexInput v, float4 vertexColor : COLOR) +{ + vertexOutput o; + TRANSFER_SHADOW_CASTER(o) + o.texcoordAndAlpha.xy = calculateTextureCoord(v.texcoord); + o.texcoordAndAlpha.z = 0; + o.texcoordAndAlpha.a = vertexColor.a; + return o; +} + +//////////////////////////////////////// +// Fragment program +// + + +uniform fixed _ShadowAlphaCutoff; + +fixed4 frag(vertexOutput IN) : SV_Target +{ + fixed4 texureColor = calculateTexturePixel(IN.texcoordAndAlpha.xy); + clip(texureColor.a * IN.texcoordAndAlpha.a - _ShadowAlphaCutoff); + + SHADOW_CASTER_FRAGMENT(IN) +} + +#endif // SPRITE_SHADOWS_INCLUDED \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc.meta new file mode 100644 index 0000000..09089fb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteShadows.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b7dbdfb1f55ee26459284220ad6d5bc4 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc new file mode 100644 index 0000000..e96d566 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc @@ -0,0 +1,246 @@ +#ifndef SPRITE_SPECULAR_INCLUDED +#define SPRITE_SPECULAR_INCLUDED + +#include "ShaderMaths.cginc" + +//////////////////////////////////////// +// Specular functions +// + +#if defined(_SPECULAR) || defined(_SPECULAR_GLOSSMAP) + +#define SPECULAR + + +//ALL THESE FUNCTIONS ARE TAKEN AND ADAPTED FROM UNITY'S OWN PHYSICS BASED STANDARD SHADER + +uniform float _Metallic; +uniform float _Glossiness; +uniform float _GlossMapScale; +uniform sampler2D _MetallicGlossMap; + +struct SpecularLightData +{ + half3 lighting; + half3 specular; +}; + +struct SpecularCommonData +{ + half3 diffColor, specColor; + // Note: smoothness & oneMinusReflectivity for optimization purposes, mostly for DX9 SM2.0 level. + // Most of the math is being done on these (1-x) values, and that saves a few precious ALU slots. + half oneMinusReflectivity, smoothness; + half alpha; +}; + +inline half2 getMetallicGloss(float2 uv) +{ + half2 mg; + +#ifdef _SPECULAR_GLOSSMAP + mg = tex2D(_MetallicGlossMap, uv).ra; + mg.g *= _GlossMapScale; +#else + mg.r = _Metallic; + mg.g = _Glossiness; +#endif + + return mg; +} + +inline half getOneMinusReflectivityFromMetallic(half metallic) +{ + // We'll need oneMinusReflectivity, so + // 1-reflectivity = 1-lerp(dielectricSpec, 1, metallic) = lerp(1-dielectricSpec, 0, metallic) + // store (1-dielectricSpec) in unity_ColorSpaceDielectricSpec.a, then + // 1-reflectivity = lerp(alpha, 0, metallic) = alpha + metallic*(0 - alpha) = + // = alpha - metallic * alpha + half oneMinusDielectricSpec = unity_ColorSpaceDielectricSpec.a; + return oneMinusDielectricSpec - metallic * oneMinusDielectricSpec; +} + +inline SpecularCommonData getSpecularData(float2 uv, half4 texureColor, fixed4 color) +{ + half2 metallicGloss = getMetallicGloss(uv); + half metallic = metallicGloss.x; + half smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m. + + fixed4 albedo = calculatePixel(texureColor, color); + + half3 specColor = lerp (unity_ColorSpaceDielectricSpec.rgb, albedo, metallic); + half oneMinusReflectivity = getOneMinusReflectivityFromMetallic(metallic); + half3 diffColor = albedo * oneMinusReflectivity; + + SpecularCommonData o = (SpecularCommonData)0; + o.diffColor = diffColor; + o.specColor = specColor; + o.oneMinusReflectivity = oneMinusReflectivity; + o.smoothness = smoothness; + +#if defined(_ALPHAPREMULTIPLY_ON) && (SHADER_TARGET >= 30) + // Reflectivity 'removes' from the rest of components, including Transparency + // outAlpha = 1-(1-alpha)*(1-reflectivity) = 1-(oneMinusReflectivity - alpha*oneMinusReflectivity) = + // = 1-oneMinusReflectivity + alpha*oneMinusReflectivity + //o.alpha = 1-oneMinusReflectivity + albedo.a*oneMinusReflectivity; + o.alpha = albedo.a; +#else + o.alpha = albedo.a; +#endif + + return o; +} +inline half SmoothnessToPerceptualRoughness(half smoothness) +{ + return (1 - smoothness); +} + +inline half PerceptualRoughnessToRoughness(half perceptualRoughness) +{ + return perceptualRoughness * perceptualRoughness; +} + +// Ref: http://jcgt.org/published/0003/02/03/paper.pdf +inline half SmithJointGGXVisibilityTerm (half NdotL, half NdotV, half roughness) +{ +#if 0 + // Original formulation: + // lambda_v = (-1 + sqrt(a2 * (1 - NdotL2) / NdotL2 + 1)) * 0.5f; + // lambda_l = (-1 + sqrt(a2 * (1 - NdotV2) / NdotV2 + 1)) * 0.5f; + // G = 1 / (1 + lambda_v + lambda_l); + + // Reorder code to be more optimal + half a = roughness; + half a2 = a * a; + + half lambdaV = NdotL * sqrt((-NdotV * a2 + NdotV) * NdotV + a2); + half lambdaL = NdotV * sqrt((-NdotL * a2 + NdotL) * NdotL + a2); + + // Simplify visibility term: (2.0f * NdotL * NdotV) / ((4.0f * NdotL * NdotV) * (lambda_v + lambda_l + 1e-5f)); + return 0.5f / (lambdaV + lambdaL + 1e-5f); // This function is not intended to be running on Mobile, + // therefore epsilon is smaller than can be represented by half +#else + // Approximation of the above formulation (simplify the sqrt, not mathematically correct but close enough) + half a = roughness; + half lambdaV = NdotL * (NdotV * (1 - a) + a); + half lambdaL = NdotV * (NdotL * (1 - a) + a); + + return 0.5f / (lambdaV + lambdaL + 1e-5f); +#endif +} + +inline half GGXTerm (half NdotH, half roughness) +{ + half a2 = roughness * roughness; + half d = (NdotH * a2 - NdotH) * NdotH + 1.0f; // 2 mad + return UNITY_INV_PI * a2 / (d * d + 1e-7f); // This function is not intended to be running on Mobile, + // therefore epsilon is smaller than what can be represented by half +} + +inline half3 FresnelTerm (half3 F0, half cosA) +{ + half t = pow5 (1 - cosA); // ala Schlick interpoliation + return F0 + (1-F0) * t; +} + +inline half3 FresnelLerp (half3 F0, half F90, half cosA) +{ + half t = pow5 (1 - cosA); // ala Schlick interpoliation + return lerp (F0, F90, t); +} + +// Note: Disney diffuse must be multiply by diffuseAlbedo / PI. This is done outside of this function. +inline half DisneyDiffuse(half NdotV, half NdotL, half LdotH, half perceptualRoughness) +{ + half fd90 = 0.5 + 2 * LdotH * LdotH * perceptualRoughness; + // Two schlick fresnel term + half lightScatter = (1 + (fd90 - 1) * pow5(1 - NdotL)); + half viewScatter = (1 + (fd90 - 1) * pow5(1 - NdotV)); + + return lightScatter * viewScatter; +} + +// Main Physically Based BRDF +// Derived from Disney work and based on Torrance-Sparrow micro-facet model +// +// BRDF = kD / pi + kS * (D * V * F) / 4 +// I = BRDF * NdotL +// +// * NDF (depending on UNITY_BRDF_GGX): +// a) Normalized BlinnPhong +// b) GGX +// * Smith for Visiblity term +// * Schlick approximation for Fresnel +SpecularLightData calculatePhysicsBasedSpecularLight(half3 specColor, half oneMinusReflectivity, half smoothness, half3 normal, half3 viewDir, half3 lightdir, half3 lightColor, half3 indirectDiffuse, half3 indirectSpecular) +{ + half perceptualRoughness = SmoothnessToPerceptualRoughness (smoothness); + half3 halfDir = safeNormalize (lightdir + viewDir); + +// NdotV should not be negative for visible pixels, but it can happen due to perspective projection and normal mapping +// In this case normal should be modified to become valid (i.e facing camera) and not cause weird artifacts. +// but this operation adds few ALU and users may not want it. Alternative is to simply take the abs of NdotV (less correct but works too). +// Following define allow to control this. Set it to 0 if ALU is critical on your platform. +// This correction is interesting for GGX with SmithJoint visibility function because artifacts are more visible in this case due to highlight edge of rough surface +// Edit: Disable this code by default for now as it is not compatible with two sided lighting used in SpeedTree. +#define UNITY_HANDLE_CORRECTLY_NEGATIVE_NDOTV 0 + +#if UNITY_HANDLE_CORRECTLY_NEGATIVE_NDOTV + // The amount we shift the normal toward the view vector is defined by the dot product. + half shiftAmount = dot(normal, viewDir); + normal = shiftAmount < 0.0f ? normal + viewDir * (-shiftAmount + 1e-5f) : normal; + // A re-normalization should be applied here but as the shift is small we don't do it to save ALU. + //normal = normalize(normal); + + half nv = saturate(dot(normal, viewDir)); // TODO: this saturate should no be necessary here +#else + half nv = abs(dot(normal, viewDir)); // This abs allow to limit artifact +#endif + + half nl = saturate(dot(normal, lightdir)); + half nh = saturate(dot(normal, halfDir)); + + half lv = saturate(dot(lightdir, viewDir)); + half lh = saturate(dot(lightdir, halfDir)); + + // Diffuse term + half diffuseTerm = DisneyDiffuse(nv, nl, lh, perceptualRoughness) * nl; + + // Specular term + // HACK: theoretically we should divide diffuseTerm by Pi and not multiply specularTerm! + // BUT 1) that will make shader look significantly darker than Legacy ones + // and 2) on engine side "Non-important" lights have to be divided by Pi too in cases when they are injected into ambient SH + half roughness = PerceptualRoughnessToRoughness(perceptualRoughness); + half V = SmithJointGGXVisibilityTerm (nl, nv, roughness); + half D = GGXTerm (nh, roughness); + + half specularTerm = V*D * UNITY_PI; // Torrance-Sparrow model, Fresnel is applied later + +# ifdef UNITY_COLORSPACE_GAMMA + specularTerm = sqrt(max(1e-4h, specularTerm)); +# endif + + // specularTerm * nl can be NaN on Metal in some cases, use max() to make sure it's a sane value + specularTerm = max(0, specularTerm * nl); + + // surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(roughness^2+1) + half surfaceReduction; +# ifdef UNITY_COLORSPACE_GAMMA + surfaceReduction = 1.0 - 0.28f * roughness * perceptualRoughness; // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1] +# else + surfaceReduction = 1.0 / (roughness*roughness + 1.0); // fade \in [0.5;1] +# endif + + // To provide true Lambert lighting, we need to be able to kill specular completely. + specularTerm *= any(specColor) ? 1.0 : 0.0; + + half grazingTerm = saturate(smoothness + (1-oneMinusReflectivity)); + + SpecularLightData outData = (SpecularLightData)0; + outData.lighting = indirectDiffuse + lightColor * diffuseTerm; + outData.specular = (specularTerm * lightColor * FresnelTerm (specColor, lh)) + (surfaceReduction * indirectSpecular * FresnelLerp (specColor, grazingTerm, nv)); + return outData; +} + +#endif // _SPECULAR && _SPECULAR_GLOSSMAP + +#endif // SPRITE_SPECULAR_INCLUDED \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc.meta new file mode 100644 index 0000000..a9fdc4f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteSpecular.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f195336fc94457241a37a0aa85923681 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc new file mode 100644 index 0000000..4385ffc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc @@ -0,0 +1,72 @@ +#ifndef SPRITE_UNLIT_INCLUDED +#define SPRITE_UNLIT_INCLUDED + +#include "ShaderShared.cginc" + +//////////////////////////////////////// +// Vertex structs +// + +struct VertexInput +{ + float4 vertex : POSITION; + float4 texcoord : TEXCOORD0; + fixed4 color : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct VertexOutput +{ + float4 pos : SV_POSITION; + float2 texcoord : TEXCOORD0; + fixed4 color : COLOR; +#if defined(_FOG) + UNITY_FOG_COORDS(1) +#endif // _FOG + + UNITY_VERTEX_OUTPUT_STEREO +}; + +//////////////////////////////////////// +// Vertex program +// + +VertexOutput vert(VertexInput input) +{ + VertexOutput output; + + UNITY_SETUP_INSTANCE_ID(input); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); + + output.pos = calculateLocalPos(input.vertex); + output.texcoord = calculateTextureCoord(input.texcoord); + output.color = calculateVertexColor(input.color); + +#if defined(_FOG) + UNITY_TRANSFER_FOG(output,output.pos); +#endif // _FOG + + return output; +} + +//////////////////////////////////////// +// Fragment program +// + + + + +fixed4 frag(VertexOutput input) : SV_Target +{ + fixed4 texureColor = calculateTexturePixel(input.texcoord.xy); + ALPHA_CLIP(texureColor, input.color) + + fixed4 pixel = calculatePixel(texureColor, input.color); + + COLORISE(pixel) + APPLY_FOG(pixel, input) + + return pixel; +} + +#endif // SPRITE_UNLIT_INCLUDED \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc.meta new file mode 100644 index 0000000..1e8d974 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteUnlit.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 072e7b07ec7fb1346a9dcd3bcbbb7111 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc new file mode 100644 index 0000000..3d8ee54 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc @@ -0,0 +1,473 @@ +#ifndef SPRITE_VERTEX_LIGHTING_INCLUDED +#define SPRITE_VERTEX_LIGHTING_INCLUDED + +#include "ShaderShared.cginc" +#include "SpriteLighting.cginc" +#include "SpriteSpecular.cginc" + +//////////////////////////////////////// +// Defines +// + +//Define to use spot lights (more expensive) +#define SPOT_LIGHTS + +//Have to process lighting per pixel if using normal maps or a diffuse ramp or rim lighting or specular +#if defined(_NORMALMAP) || defined(_DIFFUSE_RAMP) || defined(_RIM_LIGHTING) || defined(SPECULAR) +#define PER_PIXEL_LIGHTING +#endif + +//Turn off bump mapping and diffuse ramping on older shader models as they dont support needed number of outputs +#if defined(PER_PIXEL_LIGHTING) && (SHADER_TARGET < 30) + #undef PER_PIXEL_LIGHTING + #undef _NORMALMAP + #undef _DIFFUSE_RAMP + #undef _RIM_LIGHTING +#endif + +//In D3D9 only have a max of 9 TEXCOORD so can't have diffuse ramping or fog or rim lighting if processing lights per pixel +#if defined(SHADER_API_D3D9) && defined(PER_PIXEL_LIGHTING) + #if defined(_NORMALMAP) + #undef _DIFFUSE_RAMP + #undef _FOG + #undef _RIM_LIGHTING + #elif defined(_DIFFUSE_RAMP) + #undef _FOG + #undef _RIM_LIGHTING + #elif defined(_RIM_LIGHTING) + #undef _FOG + #undef _DIFFUSE_RAMP + #else + #undef _DIFFUSE_RAMP + #undef _RIM_LIGHTING + #endif +#endif + +#if defined(PER_PIXEL_LIGHTING) + #if defined(_NORMALMAP) && defined(_DIFFUSE_RAMP) + #define ATTENUATIONS TEXCOORD9 + #if defined(_RIM_LIGHTING) + #define _POS_WORLD_INDEX TEXCOORD10 + #define _FOG_COORD_INDEX 11 + #else + #define _FOG_COORD_INDEX 10 + #endif + #elif defined(_NORMALMAP) != defined(_DIFFUSE_RAMP) + #define ATTENUATIONS TEXCOORD8 + #if defined(_RIM_LIGHTING) + #define _POS_WORLD_INDEX TEXCOORD9 + #define _FOG_COORD_INDEX 10 + #else + #define _FOG_COORD_INDEX 9 + #endif + #else //!_DIFFUSE_RAMP && !_NORMALMAP + #if defined(_RIM_LIGHTING) + #define _POS_WORLD_INDEX TEXCOORD8 + #define _FOG_COORD_INDEX 9 + #else + #define _FOG_COORD_INDEX 8 + #endif + #endif +#else //!PER_PIXEL_LIGHTING + #define _FOG_COORD_INDEX 2 +#endif + +//////////////////////////////////////// +// Vertex output struct +// + +struct VertexOutput +{ + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float3 texcoord : TEXCOORD0; + +#if defined(PER_PIXEL_LIGHTING) + + half4 VertexLightInfo0 : TEXCOORD1; + half4 VertexLightInfo1 : TEXCOORD2; + half4 VertexLightInfo2 : TEXCOORD3; + half4 VertexLightInfo3 : TEXCOORD4; + half4 VertexLightInfo4 : TEXCOORD5; + + #if defined(_NORMALMAP) + half4 normalWorld : TEXCOORD6; + half4 tangentWorld : TEXCOORD7; + half4 binormalWorld : TEXCOORD8; + #else + half3 normalWorld : TEXCOORD6; + half3 VertexLightInfo5 : TEXCOORD7; + #endif + #if defined(_DIFFUSE_RAMP) + half4 LightAttenuations : ATTENUATIONS; + #endif + #if defined(_RIM_LIGHTING) + float4 posWorld : _POS_WORLD_INDEX; + #endif + +#else //!PER_PIXEL_LIGHTING + + half3 FullLighting : TEXCOORD1; + +#endif // !PER_PIXEL_LIGHTING + +#if defined(_FOG) + UNITY_FOG_COORDS(_FOG_COORD_INDEX) +#endif // _FOG + + UNITY_VERTEX_OUTPUT_STEREO +}; + +//////////////////////////////////////// +// Light calculations +// + +struct VertexLightInfo +{ + half3 lightDirection; + fixed3 lightColor; + +#if defined(_DIFFUSE_RAMP) + float attenuation; +#endif // _DIFFUSE_RAMP +}; + +inline VertexLightInfo getVertexLightAttenuatedInfo(int index, float3 viewPos) +{ + VertexLightInfo lightInfo; + + //For directional lights unity_LightPosition.w is set to zero + lightInfo.lightDirection = unity_LightPosition[index].xyz - viewPos.xyz * unity_LightPosition[index].w; + float lengthSq = dot(lightInfo.lightDirection, lightInfo.lightDirection); + + // don't produce NaNs if some vertex position overlaps with the light + lengthSq = max(lengthSq, 0.000001); + + lightInfo.lightDirection *= rsqrt(lengthSq); + + float attenuation = 1.0 / (1.0 + lengthSq * unity_LightAtten[index].z); + +#if defined(SPOT_LIGHTS) + //Spot light attenuation - for non-spot lights unity_LightAtten.x is set to -1 and y is set to 1 + { + float rho = max (0, dot(lightInfo.lightDirection, unity_SpotDirection[index].xyz)); + float spotAtt = (rho - unity_LightAtten[index].x) * unity_LightAtten[index].y; + attenuation *= saturate(spotAtt); + } +#endif // SPOT_LIGHTS + + //If using a diffuse ramp texture then need to pass through the lights attenuation, otherwise premultiply the light color with it +#if defined(_DIFFUSE_RAMP) + lightInfo.lightColor = unity_LightColor[index].rgb; + lightInfo.attenuation = attenuation; +#else + lightInfo.lightColor = unity_LightColor[index].rgb * attenuation; +#endif // _DIFFUSE_RAMP + + return lightInfo; +} + +//Magic constants used to tweak ambient to approximate pixel shader spherical harmonics +static const fixed3 worldUp = fixed3(0, 1, 0); +static const float skyGroundDotMul = 2.5; +static const float minEquatorMix = 0.5; +static const float equatorColorBlur = 0.33; + +fixed3 calculateAmbientLight(half3 normalWorld) +{ +#if defined(_SPHERICAL_HARMONICS) + float upDot = dot(normalWorld, worldUp); + + //Fade between a flat lerp from sky to ground and a 3 way lerp based on how bright the equator light is. + //This simulates how directional lights get blurred using spherical harmonics + + //Work out color from ground and sky, ignoring equator + float adjustedDot = upDot * skyGroundDotMul; + fixed3 skyGroundColor = lerp(unity_AmbientGround, unity_AmbientSky, saturate((adjustedDot + 1.0) * 0.5)); + + //Work out equator lights brightness + float equatorBright = saturate(dot(unity_AmbientEquator.rgb, unity_AmbientEquator.rgb)); + + //Blur equator color with sky and ground colors based on how bright it is. + fixed3 equatorBlurredColor = lerp(unity_AmbientEquator, saturate(unity_AmbientEquator + unity_AmbientGround + unity_AmbientSky), equatorBright * equatorColorBlur); + + //Work out 3 way lerp inc equator light + fixed3 equatorColor = lerp(equatorBlurredColor, unity_AmbientGround, -upDot) * step(upDot, 0) + lerp(equatorBlurredColor, unity_AmbientSky, upDot) * step(0, upDot); + + //Mix the two colors together based on how bright the equator light is + return lerp(skyGroundColor, equatorColor, saturate(equatorBright + minEquatorMix)); + +#else // !_SPHERICAL_HARMONICS + + //Flat ambient is just the sky color + return unity_AmbientSky.rgb; + +#endif // !_SPHERICAL_HARMONICS +} + +//////////////////////////////////////// +// Light Packing Functions +// + +#if defined(_DIFFUSE_RAMP) + +inline fixed3 calculateLightDiffuse(fixed3 lightColor, half3 viewNormal, half3 lightViewDir, float attenuation) +{ + float angleDot = max(0, dot(viewNormal, lightViewDir)); + fixed3 lightDiffuse = calculateRampedDiffuse(lightColor, attenuation, angleDot); + return lightDiffuse; +} + +#else + +inline fixed3 calculateLightDiffuse(fixed3 attenuatedLightColor, half3 viewNormal, half3 lightViewDir) +{ + float angleDot = max(0, dot(viewNormal, lightViewDir)); + fixed3 lightDiffuse = attenuatedLightColor * angleDot; + + return lightDiffuse; +} + +#endif // _NORMALMAP + + +#if defined(PER_PIXEL_LIGHTING) + +#define VERTEX_LIGHT_0_DIR VertexLightInfo0.xyz +#define VERTEX_LIGHT_0_R VertexLightInfo4.x +#define VERTEX_LIGHT_0_G VertexLightInfo4.y +#define VERTEX_LIGHT_0_B VertexLightInfo4.z + +#define VERTEX_LIGHT_1_DIR VertexLightInfo1.xyz +#define VERTEX_LIGHT_1_R VertexLightInfo0.w +#define VERTEX_LIGHT_1_G VertexLightInfo1.w +#define VERTEX_LIGHT_1_B VertexLightInfo2.w + +#define VERTEX_LIGHT_2_DIR VertexLightInfo2.xyz +#define VERTEX_LIGHT_2_R VertexLightInfo3.w +#define VERTEX_LIGHT_2_G VertexLightInfo4.w +#define VERTEX_LIGHT_2_B texcoord.z + +#define VERTEX_LIGHT_3_DIR VertexLightInfo3.xyz + +#if defined(_NORMALMAP) + #define VERTEX_LIGHT_3_R normalWorld.w + #define VERTEX_LIGHT_3_G tangentWorld.w + #define VERTEX_LIGHT_3_B binormalWorld.w +#else + #define VERTEX_LIGHT_3_R VertexLightInfo5.x + #define VERTEX_LIGHT_3_G VertexLightInfo5.y + #define VERTEX_LIGHT_3_B VertexLightInfo5.z +#endif + +#if defined(_DIFFUSE_RAMP) + + #define LIGHT_DIFFUSE_ATTEN_0 LightAttenuations.x + #define LIGHT_DIFFUSE_ATTEN_1 LightAttenuations.y + #define LIGHT_DIFFUSE_ATTEN_2 LightAttenuations.z + #define LIGHT_DIFFUSE_ATTEN_3 LightAttenuations.w + + #define PACK_VERTEX_LIGHT_DIFFUSE(index, output, lightInfo) \ + { \ + output.LIGHT_DIFFUSE_ATTEN_##index = lightInfo.attenuation; \ + } + + #define ADD_VERTEX_LIGHT_DIFFUSE(index, diffuse, input, lightColor, viewNormal, lightViewDir) \ + { \ + diffuse += calculateLightDiffuse(lightColor, viewNormal, lightViewDir, input.LIGHT_DIFFUSE_ATTEN_##index); \ + } +#else + #define PACK_VERTEX_LIGHT_DIFFUSE(index, output, lightInfo) + #define ADD_VERTEX_LIGHT_DIFFUSE(index, diffuse, input, lightColor, viewNormal, lightViewDir) \ + { \ + diffuse += calculateLightDiffuse(lightColor, viewNormal, lightViewDir); \ + } +#endif + +#define PACK_VERTEX_LIGHT(index, output, viewPos) \ + { \ + VertexLightInfo lightInfo = getVertexLightAttenuatedInfo(index, viewPos); \ + output.VERTEX_LIGHT_##index##_DIR = lightInfo.lightDirection; \ + output.VERTEX_LIGHT_##index##_R = lightInfo.lightColor.r; \ + output.VERTEX_LIGHT_##index##_G = lightInfo.lightColor.g; \ + output.VERTEX_LIGHT_##index##_B = lightInfo.lightColor.b; \ + PACK_VERTEX_LIGHT_DIFFUSE(index, output, lightInfo); \ + } + +#define ADD_VERTEX_LIGHT(index, input, viewNormal, diffuse) \ + { \ + half3 lightViewDir = input.VERTEX_LIGHT_##index##_DIR; \ + fixed3 lightColor = fixed3(input.VERTEX_LIGHT_##index##_R, input.VERTEX_LIGHT_##index##_G, input.VERTEX_LIGHT_##index##_B); \ + ADD_VERTEX_LIGHT_DIFFUSE(index, diffuse, input, lightColor, viewNormal, lightViewDir) \ + } + +#if defined(SPECULAR) + +#define ADD_VERTEX_LIGHT_SPEC(index, input, viewNormal, specData, combinedLightData, indirectDiffuse, indirectSpecular) \ + { \ + half3 lightViewDir = input.VERTEX_LIGHT_##index##_DIR; \ + fixed3 lightColor = fixed3(input.VERTEX_LIGHT_##index##_R, input.VERTEX_LIGHT_##index##_G, input.VERTEX_LIGHT_##index##_B); \ + SpecularLightData lightData = calculatePhysicsBasedSpecularLight(specData.specColor, specData.oneMinusReflectivity, specData.smoothness, viewNormal, fixed3(0,0,1), lightViewDir, lightColor, indirectDiffuse, indirectSpecular); \ + combinedLightData.lighting += lightData.lighting; \ + combinedLightData.specular += lightData.specular; \ + } + +#endif + +#else //!PER_PIXEL_LIGHTING + +//////////////////////////////////////// +// Vertex Only Functions +// + +inline fixed3 calculateLightDiffuse(int index, float3 viewPos, half3 viewNormal) +{ + VertexLightInfo lightInfo = getVertexLightAttenuatedInfo(index, viewPos); + float angleDot = max(0, dot(viewNormal, lightInfo.lightDirection)); + return lightInfo.lightColor * angleDot; +} + +#endif // !PER_PIXEL_LIGHTING + +//////////////////////////////////////// +// Vertex program +// + +VertexOutput vert(VertexInput input) +{ + VertexOutput output; + + UNITY_SETUP_INSTANCE_ID(input); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output); + + output.pos = calculateLocalPos(input.vertex); + output.color = calculateVertexColor(input.color); + output.texcoord = float3(calculateTextureCoord(input.texcoord), 0); + + float3 viewPos = UnityObjectToViewPos(input.vertex); //float3 viewPos = mul(UNITY_MATRIX_MV, input.vertex); // +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) || defined(_RIM_LIGHTING) + float4 powWorld = calculateWorldPos(input.vertex); +#endif + + float backFaceSign = 1; +#if defined(FIXED_NORMALS_BACKFACE_RENDERING) + backFaceSign = calculateBackfacingSign(powWorld.xyz); +#endif + +#if defined(PER_PIXEL_LIGHTING) + + #if defined(_RIM_LIGHTING) + output.posWorld = powWorld; + #endif + + PACK_VERTEX_LIGHT(0, output, viewPos) + PACK_VERTEX_LIGHT(1, output, viewPos) + PACK_VERTEX_LIGHT(2, output, viewPos) + PACK_VERTEX_LIGHT(3, output, viewPos) + + output.normalWorld.xyz = calculateSpriteWorldNormal(input, backFaceSign); + + #if defined(_NORMALMAP) + output.tangentWorld.xyz = calculateWorldTangent(input.tangent); + output.binormalWorld.xyz = calculateSpriteWorldBinormal(input, output.normalWorld, output.tangentWorld, backFaceSign); + #endif + +#else // !PER_PIXEL_LIGHTING + + //Just pack full lighting + float3 viewNormal = calculateSpriteViewNormal(input, backFaceSign); + //Get Ambient diffuse + float3 normalWorld = calculateSpriteWorldNormal(input, backFaceSign); + fixed3 ambient = calculateAmbientLight(normalWorld); + + fixed3 diffuse = calculateLightDiffuse(0, viewPos, viewNormal); + diffuse += calculateLightDiffuse(1, viewPos, viewNormal); + diffuse += calculateLightDiffuse(2, viewPos, viewNormal); + diffuse += calculateLightDiffuse(3, viewPos, viewNormal); + + output.FullLighting = ambient + diffuse; + +#endif // !PER_PIXEL_LIGHTING + +#if defined(_FOG) + UNITY_TRANSFER_FOG(output, output.pos); +#endif // _FOG + + return output; +} + +//////////////////////////////////////// +// Fragment program +// + +fixed4 frag(VertexOutput input) : SV_Target +{ + fixed4 texureColor = calculateTexturePixel(input.texcoord.xy); + ALPHA_CLIP(texureColor, input.color) + +#if defined(PER_PIXEL_LIGHTING) + + #if defined(_NORMALMAP) + half3 normalWorld = calculateNormalFromBumpMap(input.texcoord.xy, input.tangentWorld.xyz, input.binormalWorld.xyz, input.normalWorld.xyz); + #else + half3 normalWorld = input.normalWorld.xyz; + #endif + + //Get Ambient diffuse + fixed3 ambient = calculateAmbientLight(normalWorld); + + half3 normalView = normalize(mul((float3x3)UNITY_MATRIX_V, normalWorld)); + +#if defined(SPECULAR) + + SpecularCommonData specData = getSpecularData(input.texcoord.xy, texureColor, input.color); + + SpecularLightData combinedLightData = (SpecularLightData)0; + ADD_VERTEX_LIGHT_SPEC(0, input, normalView, specData, combinedLightData, ambient, unity_IndirectSpecColor.rgb) + ADD_VERTEX_LIGHT_SPEC(1, input, normalView, specData, combinedLightData, fixed3(0,0,0), fixed3(0,0,0)) + ADD_VERTEX_LIGHT_SPEC(2, input, normalView, specData, combinedLightData, fixed3(0,0,0), fixed3(0,0,0)) + ADD_VERTEX_LIGHT_SPEC(3, input, normalView, specData, combinedLightData, fixed3(0,0,0), fixed3(0,0,0)) + + fixed4 pixel = calculateLitPixel(fixed4(specData.diffColor, specData.alpha), combinedLightData.lighting); + pixel.rgb += combinedLightData.specular * specData.alpha; + + APPLY_EMISSION_SPECULAR(pixel, input.texcoord) + +#else + + //Find vertex light diffuse + fixed3 diffuse = fixed3(0,0,0); + + //Add each vertex light to diffuse + ADD_VERTEX_LIGHT(0, input, normalView, diffuse) + ADD_VERTEX_LIGHT(1, input, normalView, diffuse) + ADD_VERTEX_LIGHT(2, input, normalView, diffuse) + ADD_VERTEX_LIGHT(3, input, normalView, diffuse) + + fixed3 lighting = ambient + diffuse; + + APPLY_EMISSION(lighting, input.texcoord.xy) + + fixed4 pixel = calculateLitPixel(texureColor, input.color, lighting); + +#endif + +#if defined(_RIM_LIGHTING) + pixel.rgb = applyRimLighting(input.posWorld, normalWorld, pixel); +#endif + +#else // !PER_PIXEL_LIGHTING + + APPLY_EMISSION(input.FullLighting, input.texcoord.xy) + + fixed4 pixel = calculateLitPixel(texureColor, input.color, input.FullLighting); + +#endif // !PER_PIXEL_LIGHTING + + COLORISE(pixel) + APPLY_FOG(pixel, input) + + return pixel; +} + +#endif // SPRITE_VERTEX_LIGHTING_INCLUDED diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc.meta new file mode 100644 index 0000000..5987054 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CGIncludes/SpriteVertexLighting.cginc.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c739dcf9dbcab944898d0b796e11afb9 +timeCreated: 1494092582 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader new file mode 100644 index 0000000..0c80ebc --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader @@ -0,0 +1,522 @@ +Shader "Hidden/Sprite-CameraDepthNormalsTexture" { + +// Use this shader to render a DepthNormals texture for a camera with correct sprite normals (using camera.RenderWithShader with replacement tag "RenderType") + +Properties { + _MainTex ("", 2D) = "white" {} + _Cutoff ("", Float) = 0.5 + _Color ("", Color) = (1,1,1,1) +} + +SubShader { + Tags { "RenderType"="Sprite" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _FixedNormal; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteViewSpaceFixedNormal" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/SpriteLighting.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.nz.xyz = getFixedNormal(); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteModelSpaceFixedNormal" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/SpriteLighting.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + float3 worldPos = mul(unity_ObjectToWorld, v.vertex); + float3 normal = getFixedNormal(); +//Only do this if backface is enabled :/ + normal *= calculateBackfacingSign(worldPos.xyz); +// + o.nz.xyz = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, normal)); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="Opaque" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TransparentCutout" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _MainTex_ST; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +uniform fixed4 _Color; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a*_Color.a - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeBark" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertBark(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag( v2f i ) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeLeaf" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertLeaf(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag( v2f i ) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeOpaque" "DisableBatching"="True" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeTransparentCutout" "DisableBatching"="True" } + Pass { + Cull Back +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + Pass { + Cull Front +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = -COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + +} + +SubShader { + Tags { "RenderType"="TreeBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert (appdata_tree_billboard v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainBillboardTree(v.vertex, v.texcoord1.xy, v.texcoord.y); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv.x = v.texcoord.x; + o.uv.y = v.texcoord.y > 0; + o.nz.xyz = float3(0,0,1); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - 0.001 ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="GrassBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassBillboardVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="Grass" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +Fallback Off +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader.meta new file mode 100644 index 0000000..ba10b83 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthNormalsTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4794ea6b2d07cc546ba97a809b5f9ada +timeCreated: 1494092583 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader new file mode 100644 index 0000000..3a7f60d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader @@ -0,0 +1,518 @@ +Shader "Hidden/Sprite-CameraDepthTexture" { + +// Use this shader to render a Depth texture for a camera with soft edged Sprites (using camera.RenderWithShader with replacement tag "RenderType") +// Note the depth is encoded into the pixels RGB not the full RGBA (alpha is needed for blending) + +Properties { + _MainTex ("", 2D) = "white" {} + _Cutoff ("", Float) = 0.5 + _Color ("", Color) = (1,1,1,1) +} + +SubShader { + Tags { "RenderType"="Sprite" } + Pass { + Cull Off + Blend SrcAlpha OneMinusSrcAlpha +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/ShaderMaths.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), alpha); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteViewSpaceFixedNormal" } + Pass { + Cull Off + Blend SrcAlpha OneMinusSrcAlpha +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/ShaderMaths.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), alpha); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteModelSpaceFixedNormal" } + Pass { + Cull Off + Blend SrcAlpha OneMinusSrcAlpha +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/ShaderMaths.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), alpha); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="Opaque" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +struct v2f { + float4 pos : SV_POSITION; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.depth = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TransparentCutout" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _MainTex_ST; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +uniform fixed4 _Color; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a*_Color.a - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeBark" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertBark(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.depth = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag( v2f i ) : SV_Target { + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeLeaf" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertLeaf(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag( v2f i ) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeOpaque" "DisableBatching"="True" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.depth = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeTransparentCutout" "DisableBatching"="True" } + Pass { + Cull Back +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } + Pass { + Cull Front +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } + +} + +SubShader { + Tags { "RenderType"="TreeBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert (appdata_tree_billboard v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainBillboardTree(v.vertex, v.texcoord1.xy, v.texcoord.y); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv.x = v.texcoord.x; + o.uv.y = v.texcoord.y > 0; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - 0.001 ); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="GrassBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassBillboardVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="Grass" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderMaths.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float depth : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord; + o.depth = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return fixed4(EncodeFloatRGB (i.depth), 1); +} +ENDCG + } +} + +Fallback Off +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader.meta new file mode 100644 index 0000000..abf6acb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraDepthTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f768a57e040cc48489ad8c7392a31154 +timeCreated: 1494092586 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader new file mode 100644 index 0000000..1cf6a77 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader @@ -0,0 +1,522 @@ +Shader "Hidden/Sprite-CameraNormalsTexture" { + +// Use this shader to render a Normals texture for a camera with correct sprite normals (using camera.RenderWithShader with replacement tag "RenderType") + +Properties { + _MainTex ("", 2D) = "white" {} + _Cutoff ("", Float) = 0.5 + _Color ("", Color) = (1,1,1,1) +} + +SubShader { + Tags { "RenderType"="Sprite" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _FixedNormal; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return i.nz; +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteViewSpaceFixedNormal" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/SpriteLighting.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + o.nz.xyz = getFixedNormal(); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return i.nz; +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="SpriteModelSpaceFixedNormal" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "CGIncludes/ShaderShared.cginc" +#include "CGIncludes/SpriteLighting.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = calculateTextureCoord(v.texcoord); + float3 worldPos = mul(unity_ObjectToWorld, v.vertex); + float3 normal = getFixedNormal(); +//Only do this if backface is enabled :/ + normal *= calculateBackfacingSign(worldPos.xyz); +// + o.nz.xyz = normalize(mul((float3x3)UNITY_MATRIX_IT_MV, normal)); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = calculateTexturePixel(i.uv ); + float alpha = texcol.a*_Color.a; + clip( alpha - _Cutoff ); + return i.nz; +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="Opaque" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TransparentCutout" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _MainTex_ST; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +uniform fixed4 _Color; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a*_Color.a - _Cutoff ); + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeBark" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertBark(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag( v2f i ) : SV_Target { + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeLeaf" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertLeaf(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag( v2f i ) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeOpaque" "DisableBatching"="True" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeTransparentCutout" "DisableBatching"="True" } + Pass { + Cull Back +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return i.nz; +} +ENDCG + } + Pass { + Cull Front +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = -COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - _Cutoff ); + return i.nz; +} +ENDCG + } + +} + +SubShader { + Tags { "RenderType"="TreeBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert (appdata_tree_billboard v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainBillboardTree(v.vertex, v.texcoord1.xy, v.texcoord.y); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv.x = v.texcoord.x; + o.uv.y = v.texcoord.y > 0; + o.nz.xyz = float3(0,0,1); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - 0.001 ); + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="GrassBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassBillboardVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return i.nz; +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="Grass" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return i.nz; +} +ENDCG + } +} + +Fallback Off +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader.meta new file mode 100644 index 0000000..88d7505 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/CameraNormalsTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 537141eca02c6df4bb8b4f77567e9de2 +timeCreated: 1494092584 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md new file mode 100644 index 0000000..15d7899 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md @@ -0,0 +1,46 @@ +Contributed by ToddRivers + +# Unity Sprite Shaders +An Uber Shader specialised for rendering Sprites in Unity. +Even though it's designed for Sprites it can be used for a whole range of uses. It supports a wide range of optional shader features that won't effect performance unless they are used. +It also supports per-pixel effects such as normal maps and diffuse ramping whilst using Vertex Lit rendering. + +### Lighting +The shaders support lighting using both Forward Rendering and Vertex Lit Rendering. +Forward rendering is more accurate but is slower and crucially means the sprite has to write to depth using alpha clipping to avoid overdraw. +Vertex lit means all lighting can be done in one pass meaning full alpha can be used. + +### Normal Mapping +Normals maps are supported in both lighting modes (in Vertex Lit rendering data for normal mapping is packed into texture channels and then processed per pixel). + +### Blend Modes +Easily switch between blend modes including pre-multiplied alpha, additive, multiply etc. + +### Rim Lighting +Camera-space rim lighting is supported in both lighting modes. + +### Diffuse Ramp +A ramp texture is optionally supported for toon shading effects. + +### Shadows +Shadows are supported using alpha clipping. + +### Gradient based Ambient lighting +Both lighting modes support using a gradient for ambient light. In Vertex Lit mode the Spherical Harmonics is approximated from the ground, equator and sky colors. + +### Emission Map +An optional emission map is supported. + +### Camera Space Normals +As sprites are 2d their normals will always be constant. The shaders allow you to define a fixed normal in camera space rather than pass through mesh normals. +This not only saves vertex throughput but means lighting looks less 'flat' for rendering sprites with a perspective camera. + +### Color Adjustment +The shaders allow optional adjustment of hue / saturation and brightness as well as applying a solid color overlay effect for flashing a sprite to a solid color (eg. for damage effects). + +### Fog +Fog is optionally supported + + +## To Use +On your object's material click the drop down for shader and select Spine\Sprite\Pixel Lit, Vertex Lit or Unlit. diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md.meta new file mode 100644 index 0000000..78cb908 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/README.md.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cecd0ea162097a94c89a97af6baf0a66 +timeCreated: 1479457854 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader new file mode 100644 index 0000000..4d834a2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader @@ -0,0 +1,446 @@ +Shader "Hidden/Internal-SpriteDepthNormalsTexture" { + +// Use this shader to render a DepthNormals texture for a camera with correct sprite normals (using camera.RenderWithShader) + +Properties { + _MainTex ("", 2D) = "white" {} + _Cutoff ("", Float) = 0.5 + _Color ("", Color) = (1,1,1,1) +} + +SubShader { + Tags { "RenderType"="Sprite" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _MainTex_ST; +uniform float4 _FixedNormal; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.nz.xyz = _FixedNormal.xyz; +#if UNITY_REVERSED_Z + o.nz.z = -o.nz.z; +#endif + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +uniform fixed4 _Color; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a*_Color.a - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + } + +SubShader { + Tags { "RenderType"="Opaque" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TransparentCutout" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +uniform float4 _MainTex_ST; +v2f vert( appdata_base v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +uniform fixed4 _Color; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a*_Color.a - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeBark" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertBark(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag( v2f i ) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeLeaf" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "Lighting.cginc" +#include "UnityBuiltin3xTreeLibrary.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert( appdata_full v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TreeVertLeaf(v); + + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag( v2f i ) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeOpaque" "DisableBatching"="True" } + Pass { +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float4 nz : TEXCOORD0; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +fixed4 frag(v2f i) : SV_Target { + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="TreeTransparentCutout" "DisableBatching"="True" } + Pass { + Cull Back +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + half alpha = tex2D(_MainTex, i.uv).a; + + clip (alpha - _Cutoff); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + Pass { + Cull Front +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +struct appdata { + float4 vertex : POSITION; + float3 normal : NORMAL; + fixed4 color : COLOR; + float4 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; +v2f vert( appdata v ) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainAnimateTree(v.vertex, v.color.w); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = -COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } + +} + +SubShader { + Tags { "RenderType"="TreeBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; +v2f vert (appdata_tree_billboard v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + TerrainBillboardTree(v.vertex, v.texcoord1.xy, v.texcoord.y); + o.pos = UnityObjectToClipPos(v.vertex); + o.uv.x = v.texcoord.x; + o.uv.y = v.texcoord.y > 0; + o.nz.xyz = float3(0,0,1); + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + clip( texcol.a - 0.001 ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="GrassBillboard" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" + +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassBillboardVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord.xy; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +SubShader { + Tags { "RenderType"="Grass" } + Pass { + Cull Off +CGPROGRAM +#pragma target 3.0 +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" +#include "TerrainEngine.cginc" +struct v2f { + float4 pos : SV_POSITION; + fixed4 color : COLOR; + float2 uv : TEXCOORD0; + float4 nz : TEXCOORD1; + UNITY_VERTEX_OUTPUT_STEREO +}; + +v2f vert (appdata_full v) { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + WavingGrassVert (v); + o.color = v.color; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = v.texcoord; + o.nz.xyz = COMPUTE_VIEW_NORMAL; + o.nz.w = COMPUTE_DEPTH_01; + return o; +} +uniform sampler2D _MainTex; +uniform fixed _Cutoff; +fixed4 frag(v2f i) : SV_Target { + fixed4 texcol = tex2D( _MainTex, i.uv ); + fixed alpha = texcol.a * i.color.a; + clip( alpha - _Cutoff ); + return EncodeDepthNormal (i.nz.w, i.nz.xyz); +} +ENDCG + } +} + +Fallback Off +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader.meta new file mode 100644 index 0000000..7290467 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpriteDepthNormalsTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: abbda12fddbb0b048a842a3835470d30 +timeCreated: 1480325971 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader new file mode 100644 index 0000000..ac15682 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader @@ -0,0 +1,170 @@ +Shader "Spine/Sprite/Pixel Lit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + _BumpScale("Scale", Float) = 1.0 + _BumpMap ("Normal Map", 2D) = "bump" {} + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _EmissionColor("Color", Color) = (0,0,0,0) + _EmissionMap("Emission", 2D) = "white" {} + _EmissionPower("Emission Power", Float) = 2.0 + + _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5 + _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0 + [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0 + _MetallicGlossMap("Metallic", 2D) = "white" {} + + _DiffuseRamp ("Diffuse Ramp Texture", 2D) = "gray" {} + + _FixedNormal ("Fixed Normal", Vector) = (0,0,1,1) + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.5 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _RimPower("Rim Power", Float) = 2.0 + _RimColor ("Rim Color", Color) = (1,1,1,1) + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 200 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass + { + Name "FORWARD" + Tags { "LightMode" = "ForwardBase" } + Blend [_SrcBlend] [_DstBlend] + // Note: ZWrite needs to be enabled for following ForwardAdd pass, otherwise parts will look as if shining through by getting lit. + ZWrite On + ZTest LEqual + Cull [_Cull] + + CGPROGRAM + #pragma target 3.0 + + #pragma shader_feature _ _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ADDITIVEBLEND _ADDITIVEBLEND_SOFT _MULTIPLYBLEND _MULTIPLYBLEND_X2 + #pragma shader_feature _ _FIXED_NORMALS_VIEWSPACE _FIXED_NORMALS_VIEWSPACE_BACKFACE _FIXED_NORMALS_MODELSPACE _FIXED_NORMALS_MODELSPACE_BACKFACE + #pragma shader_feature _ _SPECULAR _SPECULAR_GLOSSMAP + #pragma shader_feature _NORMALMAP + #pragma shader_feature _ALPHA_CLIP + #pragma shader_feature _EMISSION + #pragma shader_feature _RIM_LIGHTING + #pragma shader_feature _DIFFUSE_RAMP + #pragma shader_feature _COLOR_ADJUST + #pragma shader_feature _TEXTURE_BLEND + #pragma shader_feature _SPHERICAL_HARMONICS + #pragma shader_feature _FOG + + #pragma multi_compile_fwdbase + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_fog + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment fragBase + + #include "CGIncludes/SpritePixelLighting.cginc" + ENDCG + } + Pass + { + Name "FORWARD_DELTA" + Tags { "LightMode" = "ForwardAdd" } + Blend [_SrcBlend] One + ZWrite Off + ZTest LEqual + Cull [_Cull] + + CGPROGRAM + #pragma target 3.0 + + #pragma shader_feature _ _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ADDITIVEBLEND _ADDITIVEBLEND_SOFT _MULTIPLYBLEND _MULTIPLYBLEND_X2 + #pragma shader_feature _ _FIXED_NORMALS_VIEWSPACE _FIXED_NORMALS_VIEWSPACE_BACKFACE _FIXED_NORMALS_MODELSPACE _FIXED_NORMALS_MODELSPACE_BACKFACE + #pragma shader_feature _ _SPECULAR _SPECULAR_GLOSSMAP + #pragma shader_feature _NORMALMAP + #pragma shader_feature _ALPHA_CLIP + #pragma shader_feature _DIFFUSE_RAMP + #pragma shader_feature _COLOR_ADJUST + #pragma shader_feature _TEXTURE_BLEND + #pragma shader_feature _FOG + + #pragma multi_compile_fwdadd_fullshadows + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_fog + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment fragAdd + + #include "CGIncludes/SpritePixelLighting.cginc" + ENDCG + } + Pass + { + Name "ShadowCaster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + Fog { Mode Off } + ZWrite On + ZTest LEqual + Cull Off + Lighting Off + + CGPROGRAM + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_shadowcaster + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment frag + + #include "CGIncludes/SpriteShadows.cginc" + ENDCG + } + } + + FallBack "Spine/Sprite/Unlit" + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader.meta new file mode 100644 index 0000000..c5a0947 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesPixelLit.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6f7a5a97a82637f478494bc40ea8c8a2 +timeCreated: 1479457857 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader new file mode 100644 index 0000000..66c1660 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader @@ -0,0 +1,109 @@ +Shader "Spine/Sprite/Unlit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _ZWrite ("Depth Write", Float) = 0.0 + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.0 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 100 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass + { + Name "Normal" + + Blend [_SrcBlend] [_DstBlend] + Lighting Off + ZWrite [_ZWrite] + ZTest LEqual + Cull [_Cull] + Lighting Off + + CGPROGRAM + #pragma shader_feature _ _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ADDITIVEBLEND _ADDITIVEBLEND_SOFT _MULTIPLYBLEND _MULTIPLYBLEND_X2 + #pragma shader_feature _ALPHA_CLIP + #pragma shader_feature _TEXTURE_BLEND + #pragma shader_feature _COLOR_ADJUST + #pragma shader_feature _FOG + + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_fog + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment frag + + #include "CGIncludes/SpriteUnlit.cginc" + ENDCG + } + Pass + { + Name "ShadowCaster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + Fog { Mode Off } + ZWrite On + ZTest LEqual + Cull Off + Lighting Off + + CGPROGRAM + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_shadowcaster + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment frag + + #include "CGIncludes/SpriteShadows.cginc" + ENDCG + } + } + + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader.meta new file mode 100644 index 0000000..0304ebb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesUnlit.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 64005298b9a80bb4899eabd5140dc4a8 +timeCreated: 1479457857 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader new file mode 100644 index 0000000..c567e4a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader @@ -0,0 +1,137 @@ +Shader "Spine/Sprite/Vertex Lit" +{ + Properties + { + _MainTex ("Main Texture", 2D) = "white" {} + _Color ("Color", Color) = (1,1,1,1) + + _BumpScale("Scale", Float) = 1.0 + _BumpMap ("Normal Map", 2D) = "bump" {} + + [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0 + [PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {} + [PerRendererData] _EnableExternalAlpha ("Enable External Alpha", Float) = 0 + + _EmissionColor("Color", Color) = (0,0,0,0) + _EmissionMap("Emission", 2D) = "white" {} + _EmissionPower("Emission Power", Float) = 2.0 + + _Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5 + _GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0 + [Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0 + _MetallicGlossMap("Metallic", 2D) = "white" {} + + _DiffuseRamp ("Diffuse Ramp Texture", 2D) = "gray" {} + + _FixedNormal ("Fixed Normal", Vector) = (0,0,1,1) + _ZWrite ("Depth Write", Float) = 0.0 + _Cutoff ("Depth alpha cutoff", Range(0,1)) = 0.0 + _ShadowAlphaCutoff ("Shadow alpha cutoff", Range(0,1)) = 0.1 + _CustomRenderQueue ("Custom Render Queue", Float) = 0.0 + + _OverlayColor ("Overlay Color", Color) = (0,0,0,0) + _Hue("Hue", Range(-0.5,0.5)) = 0.0 + _Saturation("Saturation", Range(0,2)) = 1.0 + _Brightness("Brightness", Range(0,2)) = 1.0 + + _RimPower("Rim Power", Float) = 2.0 + _RimColor ("Rim Color", Color) = (1,1,1,1) + + _BlendTex ("Blend Texture", 2D) = "white" {} + _BlendAmount ("Blend", Range(0,1)) = 0.0 + + [HideInInspector] _SrcBlend ("__src", Float) = 1.0 + [HideInInspector] _DstBlend ("__dst", Float) = 0.0 + [HideInInspector] _RenderQueue ("__queue", Float) = 0.0 + [HideInInspector] _Cull ("__cull", Float) = 0.0 + [HideInInspector] _StencilRef("Stencil Reference", Float) = 1.0 + [HideInInspector][Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comparison", Float) = 8 // Set to Always as default + + // Outline properties are drawn via custom editor. + [HideInInspector] _OutlineWidth("Outline Width", Range(0,8)) = 3.0 + [HideInInspector] _OutlineColor("Outline Color", Color) = (1,1,0,1) + [HideInInspector] _OutlineReferenceTexWidth("Reference Texture Width", Int) = 1024 + [HideInInspector] _ThresholdEnd("Outline Threshold", Range(0,1)) = 0.25 + [HideInInspector] _OutlineSmoothness("Outline Smoothness", Range(0,1)) = 1.0 + [HideInInspector][MaterialToggle(_USE8NEIGHBOURHOOD_ON)] _Use8Neighbourhood("Sample 8 Neighbours", Float) = 1 + [HideInInspector] _OutlineMipLevel("Outline Mip Level", Range(0,3)) = 0 + } + + SubShader + { + Tags { "Queue"="Transparent" "RenderType"="Sprite" "AlphaDepth"="False" "CanUseSpriteAtlas"="True" "IgnoreProjector"="True" } + LOD 150 + + Stencil { + Ref[_StencilRef] + Comp[_StencilComp] + Pass Keep + } + + Pass + { + Name "Vertex" + Tags { "LightMode" = "Vertex" } + Blend [_SrcBlend] [_DstBlend] + ZWrite [_ZWrite] + ZTest LEqual + Cull [_Cull] + Lighting On + + CGPROGRAM + #pragma target 3.0 + + #pragma shader_feature _ _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON _ADDITIVEBLEND _ADDITIVEBLEND_SOFT _MULTIPLYBLEND _MULTIPLYBLEND_X2 + #pragma shader_feature _ _FIXED_NORMALS_VIEWSPACE _FIXED_NORMALS_VIEWSPACE_BACKFACE _FIXED_NORMALS_MODELSPACE _FIXED_NORMALS_MODELSPACE_BACKFACE + #pragma shader_feature _ _SPECULAR _SPECULAR_GLOSSMAP + #pragma shader_feature _NORMALMAP + #pragma shader_feature _ALPHA_CLIP + #pragma shader_feature _EMISSION + #pragma shader_feature _DIFFUSE_RAMP + #pragma shader_feature _COLOR_ADJUST + #pragma shader_feature _RIM_LIGHTING + #pragma shader_feature _TEXTURE_BLEND + #pragma shader_feature _SPHERICAL_HARMONICS + #pragma shader_feature _FOG + + + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_fog + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment frag + + #include "CGIncludes/SpriteVertexLighting.cginc" + ENDCG + } + Pass + { + Name "ShadowCaster" + Tags { "LightMode"="ShadowCaster" } + Offset 1, 1 + + Fog { Mode Off } + ZWrite On + ZTest LEqual + Cull Off + Lighting Off + + CGPROGRAM + #pragma fragmentoption ARB_precision_hint_fastest + #pragma multi_compile_shadowcaster + #pragma multi_compile _ PIXELSNAP_ON + #pragma multi_compile _ ETC1_EXTERNAL_ALPHA + + #pragma vertex vert + #pragma fragment frag + + #include "CGIncludes/SpriteShadows.cginc" + ENDCG + } + } + + FallBack "Spine/Sprite/Unlit" + CustomEditor "SpineSpriteShaderGUI" +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader.meta new file mode 100644 index 0000000..34d232e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Sprite/SpritesVertexLit.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2ce511398fb980f41b7d316c51534590 +timeCreated: 1479457856 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility.meta new file mode 100644 index 0000000..188c117 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: bc59776133d26dc469c8ba66bdc647e4 +folderAsset: yes +timeCreated: 1492387122 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader new file mode 100644 index 0000000..ee2045d --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader @@ -0,0 +1,66 @@ +Shader "Hidden/Spine/Bones" { +Properties { + _Color ("Color", Color) = (0.5,0.5,0.5,0.5) + _MainTex ("Particle Texture", 2D) = "white" {} +} + +Category { + Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" } + Blend SrcAlpha OneMinusSrcAlpha + AlphaTest Greater .01 + ColorMask RGB + + Lighting Off Cull Off ZTest Always ZWrite Off Fog { Mode Off } + + SubShader { + Pass { + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag +// #pragma multi_compile_particles + + #include "UnityCG.cginc" + + sampler2D _MainTex; + fixed4 _Color; + + struct appdata_t { + float4 vertex : POSITION; + fixed4 color : COLOR; + float2 texcoord : TEXCOORD0; + }; + + struct v2f { + float4 vertex : SV_POSITION; + fixed4 color : COLOR; + float2 texcoord : TEXCOORD0; +// #ifdef SOFTPARTICLES_ON +// float4 projPos : TEXCOORD1; +// #endif + }; + + float4 _MainTex_ST; + + v2f vert (appdata_t v) { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); +// #ifdef SOFTPARTICLES_ON +// o.projPos = ComputeScreenPos (o.vertex); +// COMPUTE_EYEDEPTH(o.projPos.z); +// #endif + o.color = v.color; + o.texcoord = TRANSFORM_TEX(v.texcoord,_MainTex); + return o; + } + + sampler2D_float _CameraDepthTexture; + + fixed4 frag (v2f i) : SV_Target { + return i.color * _Color * tex2D(_MainTex, i.texcoord); + } + ENDCG + } + } +} +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader.meta new file mode 100644 index 0000000..17117f3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/Hidden-Spine-Bones.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 66988de88a15abd4e8846c6805485f57 +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat new file mode 100644 index 0000000..c7bc5ad --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat @@ -0,0 +1,37 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: HiddenPass + m_Shader: {fileID: 4800000, guid: 913475501bf19374c84390868a9d6d3d, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 5 + m_CustomRenderQueue: -1 + stringTagMap: {} + m_SavedProperties: + serializedVersion: 2 + m_TexEnvs: + - first: + name: _MainTex + second: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - first: + name: _Cutoff + second: 0.1 + - first: + name: _InvFade + second: 1 + m_Colors: + - first: + name: _Color + second: {r: 1, g: 1, b: 1, a: 1} + - first: + name: _TintColor + second: {r: 0.5, g: 0.5, b: 0.5, a: 0} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat.meta new file mode 100644 index 0000000..f9a2a31 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.mat.meta @@ -0,0 +1,6 @@ +fileFormatVersion: 2 +guid: 43227e5adadc6f24bb4bf74b92a56fb4 +NativeFormatImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader new file mode 100644 index 0000000..c06650a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader @@ -0,0 +1,12 @@ +Shader "Spine/Special/HiddenPass" { + SubShader + { + Tags {"Queue" = "Geometry-1" } + Lighting Off + Pass + { + ZWrite Off + ColorMask 0 + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader.meta new file mode 100644 index 0000000..01ca4ed --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Shaders/Utility/HiddenPass.shader.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 913475501bf19374c84390868a9d6d3d +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets.meta new file mode 100644 index 0000000..0c46466 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 5d7322e83d799d849bea71dbd6f1c24e +folderAsset: yes +timeCreated: 1563297885 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials.meta new file mode 100644 index 0000000..642bab4 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 16fbcfb5e341ff44bb99593fff04539d +folderAsset: yes +timeCreated: 1563298958 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs new file mode 100644 index 0000000..3f64932 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs @@ -0,0 +1,129 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +using Spine; +using Spine.Unity; + +namespace Spine.Unity { + [CreateAssetMenu(menuName = "Spine/SkeletonData Modifiers/Blend Mode Materials", order = 200)] + public class BlendModeMaterialsAsset : SkeletonDataModifierAsset { + public Material multiplyMaterialTemplate; + public Material screenMaterialTemplate; + public Material additiveMaterialTemplate; + + public bool applyAdditiveMaterial = true; + + public override void Apply (SkeletonData skeletonData) { + ApplyMaterials(skeletonData, multiplyMaterialTemplate, screenMaterialTemplate, additiveMaterialTemplate, applyAdditiveMaterial); + } + + public static void ApplyMaterials (SkeletonData skeletonData, Material multiplyTemplate, Material screenTemplate, Material additiveTemplate, bool includeAdditiveSlots) { + if (skeletonData == null) throw new ArgumentNullException("skeletonData"); + + using (var materialCache = new AtlasMaterialCache()) { + var entryBuffer = new List(); + var slotsItems = skeletonData.Slots.Items; + for (int slotIndex = 0, slotCount = skeletonData.Slots.Count; slotIndex < slotCount; slotIndex++) { + var slot = slotsItems[slotIndex]; + if (slot.blendMode == BlendMode.Normal) continue; + if (!includeAdditiveSlots && slot.blendMode == BlendMode.Additive) continue; + + entryBuffer.Clear(); + foreach (var skin in skeletonData.Skins) + skin.GetAttachments(slotIndex, entryBuffer); + + Material templateMaterial = null; + switch (slot.blendMode) { + case BlendMode.Multiply: + templateMaterial = multiplyTemplate; + break; + case BlendMode.Screen: + templateMaterial = screenTemplate; + break; + case BlendMode.Additive: + templateMaterial = additiveTemplate; + break; + } + if (templateMaterial == null) continue; + + foreach (var entry in entryBuffer) { + var renderableAttachment = entry.Attachment as IHasRendererObject; + if (renderableAttachment != null) { + renderableAttachment.RendererObject = materialCache.CloneAtlasRegionWithMaterial((AtlasRegion)renderableAttachment.RendererObject, templateMaterial); + } + } + } + + } + //attachmentBuffer.Clear(); + } + + class AtlasMaterialCache : IDisposable { + readonly Dictionary, AtlasPage> cache = new Dictionary, AtlasPage>(); + + /// Creates a clone of an AtlasRegion that uses different Material settings, while retaining the original texture. + public AtlasRegion CloneAtlasRegionWithMaterial (AtlasRegion originalRegion, Material materialTemplate) { + var newRegion = originalRegion.Clone(); + newRegion.page = GetAtlasPageWithMaterial(originalRegion.page, materialTemplate); + return newRegion; + } + + AtlasPage GetAtlasPageWithMaterial (AtlasPage originalPage, Material materialTemplate) { + if (originalPage == null) throw new ArgumentNullException("originalPage"); + + AtlasPage newPage = null; + var key = new KeyValuePair(originalPage, materialTemplate); + cache.TryGetValue(key, out newPage); + + if (newPage == null) { + newPage = originalPage.Clone(); + var originalMaterial = originalPage.rendererObject as Material; + newPage.rendererObject = new Material(materialTemplate) { + name = originalMaterial.name + " " + materialTemplate.name, + mainTexture = originalMaterial.mainTexture + }; + cache.Add(key, newPage); + } + + return newPage; + } + + public void Dispose () { + cache.Clear(); + } + } + + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs.meta new file mode 100644 index 0000000..15e2173 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/BlendModeMaterialsAsset.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 12b0b98acbcda44468a7ae4e35000abe +timeCreated: 1536404384 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: + - multiplyMaterialTemplate: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df, + type: 2} + - screenMaterialTemplate: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be, + type: 2} + - additiveMaterialTemplate: {fileID: 2100000, guid: 4deba332d47209e4780b3c5fcf0e3745, + type: 2} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset new file mode 100644 index 0000000..4e4446f --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset @@ -0,0 +1,20 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 12b0b98acbcda44468a7ae4e35000abe, type: 3} + m_Name: Default BlendModeMaterials + m_EditorClassIdentifier: + multiplyMaterialTemplate: {fileID: 2100000, guid: 53bf0ab317d032d418cf1252d68f51df, + type: 2} + screenMaterialTemplate: {fileID: 2100000, guid: 73f0f46d3177c614baf0fa48d646a9be, + type: 2} + additiveMaterialTemplate: {fileID: 2100000, guid: 4deba332d47209e4780b3c5fcf0e3745, + type: 2} + applyAdditiveMaterial: 1 diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset.meta new file mode 100644 index 0000000..7f9d67a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/Default BlendModeMaterials.asset.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 22c0225612a65ee4fb15bad49f644762 +timeCreated: 1536404361 +licenseType: Pro +NativeFormatImporter: + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat new file mode 100644 index 0000000..f40488b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonPMAAdditive + m_Shader: {fileID: 4800000, guid: 53efa1d97f5d9f74285d4330cda14e36, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_EnableInstancingVariants: 0 + m_DoubleSidedGI: 0 + m_CustomRenderQueue: -1 + stringTagMap: {} + disabledShaderPasses: [] + m_SavedProperties: + serializedVersion: 3 + m_TexEnvs: + - : + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - _MainTex: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - : 0 + - _Cutoff: 0.1 + - _StraightAlphaInput: 0 + m_Colors: + - : {r: 0, g: 2.018574, b: 1e-45, a: 0.000007110106} + - _Color: {r: 1, g: 1, b: 1, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat.meta new file mode 100644 index 0000000..e8edf09 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAAdditive.mat.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4deba332d47209e4780b3c5fcf0e3745 +timeCreated: 1496447909 +licenseType: Free +NativeFormatImporter: + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat new file mode 100644 index 0000000..28c90c1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonPMAMultiply + m_Shader: {fileID: 4800000, guid: 8bdcdc7ee298e594a9c20c61d25c33b6, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_CustomRenderQueue: -1 + stringTagMap: {} + m_SavedProperties: + serializedVersion: 2 + m_TexEnvs: + - first: + name: + second: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - first: + name: _MainTex + second: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - first: + name: + second: 0 + - first: + name: _Cutoff + second: 0.1 + m_Colors: + - first: + name: + second: {r: 0, g: 2.018574, b: 1e-45, a: 0.000007110106} + - first: + name: _Color + second: {r: 1, g: 1, b: 1, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat.meta new file mode 100644 index 0000000..c8c8038 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAMultiply.mat.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 53bf0ab317d032d418cf1252d68f51df +timeCreated: 1496447909 +licenseType: Free +NativeFormatImporter: + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat new file mode 100644 index 0000000..601f987 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + serializedVersion: 6 + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: SkeletonPMAScreen + m_Shader: {fileID: 4800000, guid: 4e8caa36c07aacf4ab270da00784e4d9, type: 3} + m_ShaderKeywords: + m_LightmapFlags: 4 + m_CustomRenderQueue: -1 + stringTagMap: {} + m_SavedProperties: + serializedVersion: 2 + m_TexEnvs: + - first: + name: + second: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + - first: + name: _MainTex + second: + m_Texture: {fileID: 0} + m_Scale: {x: 1, y: 1} + m_Offset: {x: 0, y: 0} + m_Floats: + - first: + name: + second: 0 + - first: + name: _Cutoff + second: 0.1 + m_Colors: + - first: + name: + second: {r: 0, g: 2.018574, b: 1e-45, a: 0.000007121922} + - first: + name: _Color + second: {r: 1, g: 1, b: 1, a: 1} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat.meta new file mode 100644 index 0000000..6a1a749 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SkeletonDataModifierAssets/BlendModeMaterials/SkeletonPMAScreen.mat.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 73f0f46d3177c614baf0fa48d646a9be +timeCreated: 1496447909 +licenseType: Free +NativeFormatImporter: + mainObjectFileID: 2100000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs new file mode 100644 index 0000000..a0dd2e2 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs @@ -0,0 +1,298 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System; +using System.Collections; + +namespace Spine.Unity { + + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public abstract class SpineAttributeBase : PropertyAttribute { + public string dataField = ""; + public string startsWith = ""; + public bool includeNone = true; + public bool fallbackToTextField = false; + } + + public class SpineBone : SpineAttributeBase { + /// + /// Smart popup menu for Spine Bones + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + public SpineBone (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + + public static Spine.Bone GetBone (string boneName, SkeletonRenderer renderer) { + return renderer.skeleton == null ? null : renderer.skeleton.FindBone(boneName); + } + + public static Spine.BoneData GetBoneData (string boneName, SkeletonDataAsset skeletonDataAsset) { + var data = skeletonDataAsset.GetSkeletonData(true); + return data.FindBone(boneName); + } + } + + public class SpineSlot : SpineAttributeBase { + public bool containsBoundingBoxes = false; + + /// + /// Smart popup menu for Spine Slots + /// + /// Filters popup results to elements that begin with supplied string. + /// Disables popup results that don't contain bounding box attachments when true. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + public SpineSlot (string startsWith = "", string dataField = "", bool containsBoundingBoxes = false, bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.containsBoundingBoxes = containsBoundingBoxes; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + } + + public class SpineAnimation : SpineAttributeBase { + /// + /// Smart popup menu for Spine Animations + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + public SpineAnimation (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + } + + public class SpineEvent : SpineAttributeBase { + /// + /// Smart popup menu for Spine Events (Spine.EventData) + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent(SkeletonRenderer)() will be called as a fallback. + /// + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + + public bool audioOnly = false; + + public SpineEvent (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false, bool audioOnly = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + this.audioOnly = audioOnly; + } + } + + public class SpineIkConstraint : SpineAttributeBase { + /// + /// Smart popup menu for Spine IK Constraints (Spine.IkConstraint) + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent(SkeletonRenderer)() will be called as a fallback. + /// + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + public SpineIkConstraint (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + } + + public class SpineTransformConstraint : SpineAttributeBase { + /// + /// Smart popup menu for Spine Transform Constraints (Spine.TransformConstraint) + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + public SpineTransformConstraint (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + } + + public class SpinePathConstraint : SpineAttributeBase { + /// + /// Smart popup menu for Spine Events (Spine.PathConstraint) + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives). + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent(SkeletonRenderer)() will be called as a fallback. + /// + public SpinePathConstraint (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + } + + public class SpineSkin : SpineAttributeBase { + /// + /// Smart popup menu for Spine Skins + /// + /// Filters popup results to elements that begin with supplied string. + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If true, the default choice will be serialized as an empty string. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + + public bool defaultAsEmptyString = false; + + public SpineSkin (string startsWith = "", string dataField = "", bool includeNone = true, bool fallbackToTextField = false, bool defaultAsEmptyString = false) { + this.startsWith = startsWith; + this.dataField = dataField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + this.defaultAsEmptyString = defaultAsEmptyString; + } + } + + public class SpineAttachment : SpineAttributeBase { + public bool returnAttachmentPath = false; + public bool currentSkinOnly = false; + public bool placeholdersOnly = false; + public string skinField = ""; + public string slotField = ""; + + /// + /// Smart popup menu for Spine Attachments + /// + /// Filters popup results to only include the current Skin. Only valid when a SkeletonRenderer is the data source. + /// Returns a fully qualified path for an Attachment in the format "Skin/Slot/AttachmentName". This path format is only used by the SpineAttachment helper methods like SpineAttachment.GetAttachment and .GetHierarchy. Do not use full path anywhere else in Spine's system. + /// Filters popup results to exclude attachments that are not children of Skin Placeholders + /// If specified, a locally scoped field with the name supplied by in slotField will be used to limit the popup results to children of a named slot + /// If specified, a locally scoped field with the name supplied by in skinField will be used to limit the popup results to entries of the named skin + /// If true, the dropdown list will include a "none" option which stored as an empty string. + /// If true, and an animation list source can't be found, the field will fall back to a normal text field. If false, it will show an error. + /// If specified, a locally scoped field with the name supplied by in dataField will be used to fill the popup results. + /// Valid types are SkeletonDataAsset and SkeletonRenderer (and derivatives) + /// If left empty and the script the attribute is applied to is derived from Component, GetComponent() will be called as a fallback. + /// + public SpineAttachment (bool currentSkinOnly = true, bool returnAttachmentPath = false, bool placeholdersOnly = false, string slotField = "", string dataField = "", string skinField = "", bool includeNone = true, bool fallbackToTextField = false) { + this.currentSkinOnly = currentSkinOnly; + this.returnAttachmentPath = returnAttachmentPath; + this.placeholdersOnly = placeholdersOnly; + this.slotField = slotField; + this.dataField = dataField; + this.skinField = skinField; + this.includeNone = includeNone; + this.fallbackToTextField = fallbackToTextField; + } + + public static SpineAttachment.Hierarchy GetHierarchy (string fullPath) { + return new SpineAttachment.Hierarchy(fullPath); + } + + public static Spine.Attachment GetAttachment (string attachmentPath, Spine.SkeletonData skeletonData) { + var hierarchy = SpineAttachment.GetHierarchy(attachmentPath); + return string.IsNullOrEmpty(hierarchy.name) ? null : skeletonData.FindSkin(hierarchy.skin).GetAttachment(skeletonData.FindSlotIndex(hierarchy.slot), hierarchy.name); + } + + public static Spine.Attachment GetAttachment (string attachmentPath, SkeletonDataAsset skeletonDataAsset) { + return GetAttachment(attachmentPath, skeletonDataAsset.GetSkeletonData(true)); + } + + /// + /// A struct that represents 3 strings that help identify and locate an attachment in a skeleton. + public struct Hierarchy { + public string skin; + public string slot; + public string name; + + public Hierarchy (string fullPath) { + string[] chunks = fullPath.Split(new char[]{'/'}, System.StringSplitOptions.RemoveEmptyEntries); + if (chunks.Length == 0) { + skin = ""; + slot = ""; + name = ""; + return; + } + else if (chunks.Length < 2) { + throw new System.Exception("Cannot generate Attachment Hierarchy from string! Not enough components! [" + fullPath + "]"); + } + skin = chunks[0]; + slot = chunks[1]; + name = ""; + for (int i = 2; i < chunks.Length; i++) { + name += chunks[i]; + } + } + } + } + + public class SpineAtlasRegion : PropertyAttribute { + public string atlasAssetField; + + public SpineAtlasRegion (string atlasAssetField = "") { + this.atlasAssetField = atlasAssetField; + } + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs.meta new file mode 100644 index 0000000..00a5090 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/SpineAttributes.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ce216f51ebc1d3f40929f4e58d1c65e5 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility.meta new file mode 100644 index 0000000..7098b07 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 52627c17e6dd4bf4dad4bdfc490ce823 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs new file mode 100644 index 0000000..be93170 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs @@ -0,0 +1,808 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +#if UNITY_2019_3_OR_NEWER +#define CONFIGURABLE_ENTER_PLAY_MODE +#endif + + +using UnityEngine; +using System.Collections.Generic; +using System; + + +namespace Spine.Unity.AttachmentTools { + + public static class AtlasUtilities { + internal const TextureFormat SpineTextureFormat = TextureFormat.RGBA32; + internal const float DefaultMipmapBias = -0.5f; + internal const bool UseMipMaps = false; + internal const float DefaultScale = 0.01f; + + const int NonrenderingRegion = -1; + + #if CONFIGURABLE_ENTER_PLAY_MODE + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + static void Init () { + // handle disabled domain reload + AtlasUtilities.ClearCache(); + } + #endif + + public static AtlasRegion ToAtlasRegion (this Texture2D t, Material materialPropertySource, float scale = DefaultScale) { + return t.ToAtlasRegion(materialPropertySource.shader, scale, materialPropertySource); + } + + public static AtlasRegion ToAtlasRegion (this Texture2D t, Shader shader, float scale = DefaultScale, Material materialPropertySource = null) { + var material = new Material(shader); + if (materialPropertySource != null) { + material.CopyPropertiesFromMaterial(materialPropertySource); + material.shaderKeywords = materialPropertySource.shaderKeywords; + } + + material.mainTexture = t; + var page = material.ToSpineAtlasPage(); + + float width = t.width; + float height = t.height; + + var region = new AtlasRegion(); + region.name = t.name; + region.index = -1; + region.rotate = false; + + // World space units + Vector2 boundsMin = Vector2.zero, boundsMax = new Vector2(width, height) * scale; + + // Texture space/pixel units + region.width = (int)width; + region.originalWidth = (int)width; + region.height = (int)height; + region.originalHeight = (int)height; + region.offsetX = width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); + region.offsetY = height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); + + // Use the full area of the texture. + region.u = 0; + region.v = 1; + region.u2 = 1; + region.v2 = 0; + region.x = 0; + region.y = 0; + + region.page = page; + + return region; + } + + /// + /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data. + public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { + return t.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); + } + + /// + /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data. + public static AtlasRegion ToAtlasRegionPMAClone (this Texture2D t, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { + var material = new Material(shader); + if (materialPropertySource != null) { + material.CopyPropertiesFromMaterial(materialPropertySource); + material.shaderKeywords = materialPropertySource.shaderKeywords; + } + var newTexture = t.GetClone(textureFormat, mipmaps, applyPMA : true); + + newTexture.name = t.name + "-pma-"; + material.name = t.name + shader.name; + + material.mainTexture = newTexture; + var page = material.ToSpineAtlasPage(); + + var region = newTexture.ToAtlasRegion(shader); + region.page = page; + + return region; + } + + /// + /// Creates a new Spine.AtlasPage from a UnityEngine.Material. If the material has a preassigned texture, the page width and height will be set. + public static AtlasPage ToSpineAtlasPage (this Material m) { + var newPage = new AtlasPage { + rendererObject = m, + name = m.name + }; + + var t = m.mainTexture; + if (t != null) { + newPage.width = t.width; + newPage.height = t.height; + } + + return newPage; + } + + /// + /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. + public static AtlasRegion ToAtlasRegion (this Sprite s, AtlasPage page) { + if (page == null) throw new System.ArgumentNullException("page", "page cannot be null. AtlasPage determines which texture region belongs and how it should be rendered. You can use material.ToSpineAtlasPage() to get a shareable AtlasPage from a Material, or use the sprite.ToAtlasRegion(material) overload."); + var region = s.ToAtlasRegion(); + region.page = page; + return region; + } + + /// + /// Creates a Spine.AtlasRegion from a UnityEngine.Sprite. This creates a new AtlasPage object for every AtlasRegion you create. You can centralize Material control by creating a shared atlas page using Material.ToSpineAtlasPage and using the sprite.ToAtlasRegion(AtlasPage) overload. + public static AtlasRegion ToAtlasRegion (this Sprite s, Material material) { + var region = s.ToAtlasRegion(); + region.page = material.ToSpineAtlasPage(); + return region; + } + + public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Material materialPropertySource, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps) { + return s.ToAtlasRegionPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource); + } + + /// + /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate of the Sprite's texture data. + public static AtlasRegion ToAtlasRegionPMAClone (this Sprite s, Shader shader, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, Material materialPropertySource = null) { + var material = new Material(shader); + if (materialPropertySource != null) { + material.CopyPropertiesFromMaterial(materialPropertySource); + material.shaderKeywords = materialPropertySource.shaderKeywords; + } + + var tex = s.ToTexture(textureFormat, mipmaps, applyPMA : true); + tex.name = s.name + "-pma-"; + material.name = tex.name + shader.name; + + material.mainTexture = tex; + var page = material.ToSpineAtlasPage(); + + var region = s.ToAtlasRegion(true); + region.page = page; + + return region; + } + + internal static AtlasRegion ToAtlasRegion (this Sprite s, bool isolatedTexture = false) { + var region = new AtlasRegion(); + region.name = s.name; + region.index = -1; + region.rotate = s.packed && s.packingRotation != SpritePackingRotation.None; + + // World space units + Bounds bounds = s.bounds; + Vector2 boundsMin = bounds.min, boundsMax = bounds.max; + + // Texture space/pixel units + Rect spineRect = s.rect.SpineUnityFlipRect(s.texture.height); + region.width = (int)spineRect.width; + region.originalWidth = (int)spineRect.width; + region.height = (int)spineRect.height; + region.originalHeight = (int)spineRect.height; + region.offsetX = spineRect.width * (0.5f - InverseLerp(boundsMin.x, boundsMax.x, 0)); + region.offsetY = spineRect.height * (0.5f - InverseLerp(boundsMin.y, boundsMax.y, 0)); + + if (isolatedTexture) { + region.u = 0; + region.v = 1; + region.u2 = 1; + region.v2 = 0; + region.x = 0; + region.y = 0; + } else { + Texture2D tex = s.texture; + Rect uvRect = TextureRectToUVRect(s.textureRect, tex.width, tex.height); + region.u = uvRect.xMin; + region.v = uvRect.yMax; + region.u2 = uvRect.xMax; + region.v2 = uvRect.yMin; + region.x = (int)spineRect.x; + region.y = (int)spineRect.y; + } + + return region; + } + + #region Runtime Repacking + static readonly Dictionary existingRegions = new Dictionary(); + static readonly List regionIndices = new List(); + static readonly List texturesToPack = new List(); + static readonly List originalRegions = new List(); + static readonly List repackedRegions = new List(); + static readonly List repackedAttachments = new List(); + static List[] texturesToPackAtParam = new List[1]; + + /// + /// Fills the outputAttachments list with new attachment objects based on the attachments in sourceAttachments, + /// but mapped to a new single texture using the same material. + /// Returned Material and Texture behave like new Texture2D(), thus you need to call Destroy() + /// to free resources. + /// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory + /// footprint when used excessively. Set to true + /// or call to clear this texture cache. + /// You may want to call Resources.UnloadUnusedAssets() after that. + /// + /// The list of attachments to be repacked. + /// The List(Attachment) to populate with the newly created Attachment objects. + /// May be null. If no Material property source is provided, no special + /// When set to true, is called after + /// repacking to clear the texture cache. See remarks for additional info. + public static void GetRepackedAttachments (List sourceAttachments, List outputAttachments, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, string newAssetName = "Repacked Attachments", bool clearCache = false, bool useOriginalNonrenderables = true) { + if (sourceAttachments == null) throw new System.ArgumentNullException("sourceAttachments"); + if (outputAttachments == null) throw new System.ArgumentNullException("outputAttachments"); + + // Use shared lists to detect and use shared regions. + existingRegions.Clear(); + regionIndices.Clear(); + texturesToPack.Clear(); + originalRegions.Clear(); + + outputAttachments.Clear(); + outputAttachments.AddRange(sourceAttachments); + + int newRegionIndex = 0; + for (int i = 0, n = sourceAttachments.Count; i < n; i++) { + var originalAttachment = sourceAttachments[i]; + + if (IsRenderable(originalAttachment)) { + var newAttachment = originalAttachment.GetCopy(true); + var region = newAttachment.GetRegion(); + int existingIndex; + if (existingRegions.TryGetValue(region, out existingIndex)) { + regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment. + } else { + originalRegions.Add(region); + texturesToPack.Add(region.ToTexture(textureFormat, mipmaps)); // Add the texture to the PackTextures argument + existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions + regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment. + newRegionIndex++; + } + + outputAttachments[i] = newAttachment; + } else { + outputAttachments[i] = useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true); + regionIndices.Add(NonrenderingRegion); // Output attachments pairs with regionIndexes list 1:1. Pad with a sentinel if the attachment doesn't have a region. + } + } + + // Fill a new texture with the collected attachment textures. + var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps); + newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias; + newTexture.name = newAssetName; + // Copy settings + if (texturesToPack.Count > 0) { + var sourceTexture = texturesToPack[0]; + newTexture.CopyTextureAttributesFrom(sourceTexture); + } + var rects = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize); + + // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments + Shader shader = materialPropertySource == null ? Shader.Find("Spine/Skeleton") : materialPropertySource.shader; + var newMaterial = new Material(shader); + if (materialPropertySource != null) { + newMaterial.CopyPropertiesFromMaterial(materialPropertySource); + newMaterial.shaderKeywords = materialPropertySource.shaderKeywords; + } + + newMaterial.name = newAssetName; + newMaterial.mainTexture = newTexture; + var page = newMaterial.ToSpineAtlasPage(); + page.name = newAssetName; + + repackedRegions.Clear(); + for (int i = 0, n = originalRegions.Count; i < n; i++) { + var oldRegion = originalRegions[i]; + var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page); + repackedRegions.Add(newRegion); + } + + // Map the cloned attachments to the repacked atlas. + for (int i = 0, n = outputAttachments.Count; i < n; i++) { + var a = outputAttachments[i]; + if (IsRenderable(a)) + a.SetRegion(repackedRegions[regionIndices[i]]); + } + + // Clean up. + if (clearCache) + AtlasUtilities.ClearCache(); + + outputTexture = newTexture; + outputMaterial = newMaterial; + } + + /// + /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas + /// comprised of all the regions from the original skin. + /// GetRepackedSkin is an expensive operation, preferably call it at level load time. + /// No Spine.Atlas object is created so there is no way to find AtlasRegions except through the Attachments using them. + /// Returned Material and Texture behave like new Texture2D(), thus you need to call Destroy() + /// to free resources. + /// This method caches necessary Texture copies for later re-use, which might steadily increase the texture memory + /// footprint when used excessively. Set to true + /// or call to clear this texture cache. + /// You may want to call Resources.UnloadUnusedAssets() after that. + /// + /// When set to true, is called after + /// repacking to clear the texture cache. See remarks for additional info. + /// Optional additional textures (such as normal maps) to copy while repacking. + /// To copy e.g. the main texture and normal maps, pass 'new int[] { Shader.PropertyToID("_BumpMap") }' at this parameter. + /// When additionalTexturePropertyIDsToCopy is non-null, + /// this array will be filled with the resulting repacked texture for every property, + /// just as the main repacked texture is assigned to outputTexture. + /// When additionalTexturePropertyIDsToCopy is non-null, + /// this array will be used as TextureFormat at the Texture at the respective property. + /// When additionalTextureFormats is null or when its array size is smaller, + /// textureFormat is used where there exists no corresponding array item. + /// When additionalTexturePropertyIDsToCopy is non-null, + /// this array will be used to determine whether linear or sRGB color space is used at the + /// Texture at the respective property. When additionalTextureIsLinear is null, linear color space + /// is assumed at every additional Texture element. + /// When e.g. packing the main texture and normal maps, pass 'new bool[] { true }' at this parameter, because normal maps use + /// linear color space. + public static Skin GetRepackedSkin (this Skin o, string newName, Material materialPropertySource, out Material outputMaterial, out Texture2D outputTexture, + int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, + bool useOriginalNonrenderables = true, bool clearCache = false, + int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null, + TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) { + + return GetRepackedSkin(o, newName, materialPropertySource.shader, out outputMaterial, out outputTexture, + maxAtlasSize, padding, textureFormat, mipmaps, materialPropertySource, + clearCache, useOriginalNonrenderables, additionalTexturePropertyIDsToCopy, additionalOutputTextures, + additionalTextureFormats, additionalTextureIsLinear); + } + + /// + /// Creates and populates a duplicate skin with cloned attachments that are backed by a new packed texture atlas + /// comprised of all the regions from the original skin. + /// See documentation of for details. + public static Skin GetRepackedSkin (this Skin o, string newName, Shader shader, out Material outputMaterial, out Texture2D outputTexture, + int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, + Material materialPropertySource = null, bool clearCache = false, bool useOriginalNonrenderables = true, + int[] additionalTexturePropertyIDsToCopy = null, Texture2D[] additionalOutputTextures = null, + TextureFormat[] additionalTextureFormats = null, bool[] additionalTextureIsLinear = null) { + + outputTexture = null; + if (additionalTexturePropertyIDsToCopy != null && additionalTextureIsLinear == null) { + additionalTextureIsLinear = new bool[additionalTexturePropertyIDsToCopy.Length]; + for (int i = 0; i < additionalTextureIsLinear.Length; ++i) { + additionalTextureIsLinear[i] = true; + } + } + + if (o == null) throw new System.NullReferenceException("Skin was null"); + var skinAttachments = o.Attachments; + var newSkin = new Skin(newName); + + newSkin.bones.AddRange(o.bones); + newSkin.constraints.AddRange(o.constraints); + + // Use these to detect and use shared regions. + existingRegions.Clear(); + regionIndices.Clear(); + + // Collect all textures from the attachments of the original skin. + repackedAttachments.Clear(); + int numTextureParamsToRepack = 1 + (additionalTexturePropertyIDsToCopy == null ? 0 : additionalTexturePropertyIDsToCopy.Length); + additionalOutputTextures = (additionalTexturePropertyIDsToCopy == null ? null : new Texture2D[additionalTexturePropertyIDsToCopy.Length]); + if (texturesToPackAtParam.Length < numTextureParamsToRepack) + Array.Resize(ref texturesToPackAtParam, numTextureParamsToRepack); + for (int i = 0; i < numTextureParamsToRepack; ++i) { + if (texturesToPackAtParam[i] != null) + texturesToPackAtParam[i].Clear(); + else + texturesToPackAtParam[i] = new List(); + } + originalRegions.Clear(); + int newRegionIndex = 0; + + foreach (var skinEntry in skinAttachments) { + var originalKey = skinEntry.Key; + var originalAttachment = skinEntry.Value; + + Attachment newAttachment; + if (IsRenderable(originalAttachment)) { + newAttachment = originalAttachment.GetCopy(true); + var region = newAttachment.GetRegion(); + int existingIndex; + if (existingRegions.TryGetValue(region, out existingIndex)) { + regionIndices.Add(existingIndex); // Store the region index for the eventual new attachment. + } else { + originalRegions.Add(region); + for (int i = 0; i < numTextureParamsToRepack; ++i) { + Texture2D regionTexture = (i == 0 ? + region.ToTexture(textureFormat, mipmaps) : + region.ToTexture((additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ? + additionalTextureFormats[i - 1] : textureFormat, + mipmaps, additionalTexturePropertyIDsToCopy[i - 1], additionalTextureIsLinear[i - 1])); + texturesToPackAtParam[i].Add(regionTexture); // Add the texture to the PackTextures argument + } + existingRegions.Add(region, newRegionIndex); // Add the region to the dictionary of known regions + regionIndices.Add(newRegionIndex); // Store the region index for the eventual new attachment. + newRegionIndex++; + } + + repackedAttachments.Add(newAttachment); + newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, newAttachment); + } else { + newSkin.SetAttachment(originalKey.SlotIndex, originalKey.Name, useOriginalNonrenderables ? originalAttachment : originalAttachment.GetCopy(true)); + } + } + + // Rehydrate the repacked textures as a Material, Spine atlas and Spine.AtlasAttachments + var newMaterial = new Material(shader); + if (materialPropertySource != null) { + newMaterial.CopyPropertiesFromMaterial(materialPropertySource); + newMaterial.shaderKeywords = materialPropertySource.shaderKeywords; + } + newMaterial.name = newName; + + Rect[] rects = null; + for (int i = 0; i < numTextureParamsToRepack; ++i) { + // Fill a new texture with the collected attachment textures. + var newTexture = new Texture2D(maxAtlasSize, maxAtlasSize, + (i > 0 && additionalTextureFormats != null && i - 1 < additionalTextureFormats.Length) ? + additionalTextureFormats[i - 1] : textureFormat, + mipmaps, + (i > 0) ? additionalTextureIsLinear[i - 1] : false); + newTexture.mipMapBias = AtlasUtilities.DefaultMipmapBias; + var texturesToPack = texturesToPackAtParam[i]; + if (texturesToPack.Count > 0) { + var sourceTexture = texturesToPack[0]; + newTexture.CopyTextureAttributesFrom(sourceTexture); + } + newTexture.name = newName; + var rectsForTexParam = newTexture.PackTextures(texturesToPack.ToArray(), padding, maxAtlasSize); + if (i == 0) { + rects = rectsForTexParam; + newMaterial.mainTexture = newTexture; + outputTexture = newTexture; + } + else { + newMaterial.SetTexture(additionalTexturePropertyIDsToCopy[i - 1], newTexture); + additionalOutputTextures[i - 1] = newTexture; + } + } + + var page = newMaterial.ToSpineAtlasPage(); + page.name = newName; + + repackedRegions.Clear(); + for (int i = 0, n = originalRegions.Count; i < n; i++) { + var oldRegion = originalRegions[i]; + var newRegion = UVRectToAtlasRegion(rects[i], oldRegion, page); + repackedRegions.Add(newRegion); + } + + // Map the cloned attachments to the repacked atlas. + for (int i = 0, n = repackedAttachments.Count; i < n; i++) { + var a = repackedAttachments[i]; + if (IsRenderable(a)) + a.SetRegion(repackedRegions[regionIndices[i]]); + } + + // Clean up. + if (clearCache) + AtlasUtilities.ClearCache(); + + outputMaterial = newMaterial; + return newSkin; + } + + public static Sprite ToSprite (this AtlasRegion ar, float pixelsPerUnit = 100) { + return Sprite.Create(ar.GetMainTexture(), ar.GetUnityRect(), new Vector2(0.5f, 0.5f), pixelsPerUnit); + } + + struct IntAndAtlasRegionKey { + int i; + AtlasRegion region; + + public IntAndAtlasRegionKey(int i, AtlasRegion region) { + this.i = i; + this.region = region; + } + + public override int GetHashCode () { + return i.GetHashCode() * 23 ^ region.GetHashCode(); + } + } + static Dictionary CachedRegionTextures = new Dictionary(); + static List CachedRegionTexturesList = new List(); + + /// + /// Frees up textures cached by repacking and remapping operations. + /// + /// Calling with parameter premultiplyAlpha=true, + /// or will cache textures for later re-use, + /// which might steadily increase the texture memory footprint when used excessively. + /// You can clear this Texture cache by calling . + /// You may also want to call Resources.UnloadUnusedAssets() after that. Be aware that while this cleanup + /// frees up memory, it is also a costly operation and will likely cause a spike in the framerate. + /// Thus it is recommended to perform costly repacking and cleanup operations after e.g. a character customization + /// screen has been exited, and if required additionally after a certain number of GetRemappedClone() calls. + /// + public static void ClearCache () { + foreach (var t in CachedRegionTexturesList) { + UnityEngine.Object.Destroy(t); + } + CachedRegionTextures.Clear(); + CachedRegionTexturesList.Clear(); + } + + /// Creates a new Texture2D object based on an AtlasRegion. + /// If applyImmediately is true, Texture2D.Apply is called immediately after the Texture2D is filled with data. + public static Texture2D ToTexture (this AtlasRegion ar, TextureFormat textureFormat = SpineTextureFormat, bool mipmaps = UseMipMaps, + int texturePropertyId = 0, bool linear = false, bool applyPMA = false) { + + Texture2D output; + + IntAndAtlasRegionKey cacheKey = new IntAndAtlasRegionKey(texturePropertyId, ar); + CachedRegionTextures.TryGetValue(cacheKey, out output); + if (output == null) { + Texture2D sourceTexture = texturePropertyId == 0 ? ar.GetMainTexture() : ar.GetTexture(texturePropertyId); + Rect r = ar.GetUnityRect(); + // Compensate any image resizing due to Texture 'Max Size' import settings. + // sourceTexture.width returns the resized image dimensions, at least in newer Unity versions. + if (sourceTexture.width < ar.page.width) { + float scaleX = (float)(sourceTexture.width) / (float)(ar.page.width); + float scaleY = (float)(sourceTexture.height) / (float)(ar.page.height); + var scale = new Vector2(scaleX, scaleY); + r = new Rect(Vector2.Scale(r.position, scale), Vector2.Scale(r.size, scale)); + } + + int width = (int)r.width; + int height = (int)r.height; + output = new Texture2D(width, height, textureFormat, mipmaps, linear) { name = ar.name }; + output.CopyTextureAttributesFrom(sourceTexture); + if (applyPMA) + AtlasUtilities.CopyTextureApplyPMA(sourceTexture, r, output); + else + AtlasUtilities.CopyTexture(sourceTexture, r, output); + CachedRegionTextures.Add(cacheKey, output); + CachedRegionTexturesList.Add(output); + } + + return output; + } + + static Texture2D ToTexture (this Sprite s, TextureFormat textureFormat = SpineTextureFormat, + bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) { + + var spriteTexture = s.texture; + Rect r; + if (!s.packed || s.packingMode == SpritePackingMode.Rectangle) { + r = s.textureRect; + } + else { + r = new Rect(); + r.xMin = Math.Min(s.uv[0].x, s.uv[1].x) * spriteTexture.width; + r.xMax = Math.Max(s.uv[0].x, s.uv[1].x) * spriteTexture.width; + r.yMin = Math.Min(s.uv[0].y, s.uv[2].y) * spriteTexture.height; + r.yMax = Math.Max(s.uv[0].y, s.uv[2].y) * spriteTexture.height; + #if UNITY_EDITOR + if (s.uv.Length > 4) { + Debug.LogError("When using a tightly packed SpriteAtlas with Spine, you may only access Sprites that are packed as 'FullRect' from it! " + + "You can either disable 'Tight Packing' at the whole SpriteAtlas, or change the single Sprite's TextureImporter Setting 'MeshType' to 'Full Rect'." + + "Sprite Asset: " + s.name, s); + } + #endif + } + var newTexture = new Texture2D((int)r.width, (int)r.height, textureFormat, mipmaps, linear); + newTexture.CopyTextureAttributesFrom(spriteTexture); + if (applyPMA) + AtlasUtilities.CopyTextureApplyPMA(spriteTexture, r, newTexture); + else + AtlasUtilities.CopyTexture(spriteTexture, r, newTexture); + return newTexture; + } + + static Texture2D GetClone (this Texture2D t, TextureFormat textureFormat = SpineTextureFormat, + bool mipmaps = UseMipMaps, bool linear = false, bool applyPMA = false) { + + var newTexture = new Texture2D((int)t.width, (int)t.height, textureFormat, mipmaps, linear); + newTexture.CopyTextureAttributesFrom(t); + if (applyPMA) + AtlasUtilities.CopyTextureApplyPMA(t, new Rect(0, 0, t.width, t.height), newTexture); + else + AtlasUtilities.CopyTexture(t, new Rect(0, 0, t.width, t.height), newTexture); + return newTexture; + } + + static void CopyTexture (Texture2D source, Rect sourceRect, Texture2D destination) { + if (SystemInfo.copyTextureSupport == UnityEngine.Rendering.CopyTextureSupport.None) { + // GetPixels fallback for old devices. + Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height); + destination.SetPixels(pixelBuffer); + destination.Apply(); + } else { + Graphics.CopyTexture(source, 0, 0, (int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height, destination, 0, 0, 0, 0); + } + } + + static void CopyTextureApplyPMA (Texture2D source, Rect sourceRect, Texture2D destination) { + Color[] pixelBuffer = source.GetPixels((int)sourceRect.x, (int)sourceRect.y, (int)sourceRect.width, (int)sourceRect.height); + for (int i = 0, n = pixelBuffer.Length; i < n; i++) { + Color p = pixelBuffer[i]; + float a = p.a; + p.r = p.r * a; + p.g = p.g * a; + p.b = p.b * a; + pixelBuffer[i] = p; + } + destination.SetPixels(pixelBuffer); + destination.Apply(); + } + + static bool IsRenderable (Attachment a) { + return a is IHasRendererObject; + } + + /// + /// Get a rect with flipped Y so that a Spine atlas rect gets converted to a Unity Sprite rect and vice versa. + static Rect SpineUnityFlipRect (this Rect rect, int textureHeight) { + rect.y = textureHeight - rect.y - rect.height; + return rect; + } + + /// + /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up). + /// This overload relies on region.page.height being correctly set. + static Rect GetUnityRect (this AtlasRegion region) { + return region.GetSpineAtlasRect().SpineUnityFlipRect(region.page.height); + } + + /// + /// Gets the Rect of an AtlasRegion according to Unity texture coordinates (x-right, y-up). + static Rect GetUnityRect (this AtlasRegion region, int textureHeight) { + return region.GetSpineAtlasRect().SpineUnityFlipRect(textureHeight); + } + + /// + /// Returns a Rect of the AtlasRegion according to Spine texture coordinates. (x-right, y-down) + static Rect GetSpineAtlasRect (this AtlasRegion region, bool includeRotate = true) { + if (includeRotate && (region.degrees == 90 || region.degrees == 270)) + return new Rect(region.x, region.y, region.height, region.width); + else + return new Rect(region.x, region.y, region.width, region.height); + } + + /// + /// Denormalize a uvRect into a texture-space Rect. + static Rect UVRectToTextureRect (Rect uvRect, int texWidth, int texHeight) { + uvRect.x *= texWidth; + uvRect.width *= texWidth; + uvRect.y *= texHeight; + uvRect.height *= texHeight; + return uvRect; + } + + /// + /// Normalize a texture Rect into UV coordinates. + static Rect TextureRectToUVRect (Rect textureRect, int texWidth, int texHeight) { + textureRect.x = Mathf.InverseLerp(0, texWidth, textureRect.x); + textureRect.y = Mathf.InverseLerp(0, texHeight, textureRect.y); + textureRect.width = Mathf.InverseLerp(0, texWidth, textureRect.width); + textureRect.height = Mathf.InverseLerp(0, texHeight, textureRect.height); + return textureRect; + } + + /// + /// Creates a new Spine AtlasRegion according to a Unity UV Rect (x-right, y-up, uv-normalized). + static AtlasRegion UVRectToAtlasRegion (Rect uvRect, AtlasRegion referenceRegion, AtlasPage page) { + var tr = UVRectToTextureRect(uvRect, page.width, page.height); + var rr = tr.SpineUnityFlipRect(page.height); + + int x = (int)rr.x, y = (int)rr.y; + int w, h; + if (referenceRegion.degrees == 90 || referenceRegion.degrees == 270) { + w = (int)rr.height; + h = (int)rr.width; + } else { + w = (int)rr.width; + h = (int)rr.height; + } + + int originalW = Mathf.RoundToInt((float)w * ((float)referenceRegion.originalWidth / (float)referenceRegion.width)); + int originalH = Mathf.RoundToInt((float)h * ((float)referenceRegion.originalHeight / (float)referenceRegion.height)); + int offsetX = Mathf.RoundToInt((float)referenceRegion.offsetX * ((float)w / (float)referenceRegion.width)); + int offsetY = Mathf.RoundToInt((float)referenceRegion.offsetY * ((float)h / (float)referenceRegion.height)); + + if (referenceRegion.degrees == 270) { + w = (int)rr.width; + h = (int)rr.height; + } + + float u = uvRect.xMin; + float u2 = uvRect.xMax; + float v = uvRect.yMax; + float v2 = uvRect.yMin; + + return new AtlasRegion { + page = page, + name = referenceRegion.name, + + u = u, + u2 = u2, + v = v, + v2 = v2, + + index = -1, + + width = w, + originalWidth = originalW, + height = h, + originalHeight = originalH, + offsetX = offsetX, + offsetY = offsetY, + x = x, + y = y, + + rotate = referenceRegion.rotate, + degrees = referenceRegion.degrees + }; + } + + /// + /// Convenience method for getting the main texture of the material of the page of the region. + static Texture2D GetMainTexture (this AtlasRegion region) { + var material = (region.page.rendererObject as Material); + return material.mainTexture as Texture2D; + } + + /// + /// Convenience method for getting any texture of the material of the page of the region by texture property name. + static Texture2D GetTexture (this AtlasRegion region, string texturePropertyName) { + var material = (region.page.rendererObject as Material); + return material.GetTexture(texturePropertyName) as Texture2D; + } + + /// + /// Convenience method for getting any texture of the material of the page of the region by texture property id. + static Texture2D GetTexture (this AtlasRegion region, int texturePropertyId) { + var material = (region.page.rendererObject as Material); + return material.GetTexture(texturePropertyId) as Texture2D; + } + + static void CopyTextureAttributesFrom(this Texture2D destination, Texture2D source) { + destination.filterMode = source.filterMode; + destination.anisoLevel = source.anisoLevel; + #if UNITY_EDITOR + destination.alphaIsTransparency = source.alphaIsTransparency; + #endif + destination.wrapModeU = source.wrapModeU; + destination.wrapModeV = source.wrapModeV; + destination.wrapModeW = source.wrapModeW; + } + #endregion + + static float InverseLerp (float a, float b, float value) { + return (value - a) / (b - a); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs.meta new file mode 100644 index 0000000..32d291e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AtlasUtilities.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 25ceef568a3dad448bf8a14fcc326964 +timeCreated: 1563321428 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs new file mode 100644 index 0000000..2181562 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs @@ -0,0 +1,147 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using System.Collections; + +namespace Spine.Unity.AttachmentTools { + + public static class AttachmentCloneExtensions { + /// + /// Clones the attachment. + public static Attachment GetCopy (this Attachment o, bool cloneMeshesAsLinked) { + var meshAttachment = o as MeshAttachment; + if (meshAttachment != null && cloneMeshesAsLinked) + return meshAttachment.NewLinkedMesh(); + return o.Copy(); + } + + #region Runtime Linked MeshAttachments + /// + /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to the AtlasRegion provided. + public static MeshAttachment GetLinkedMesh (this MeshAttachment o, string newLinkedMeshName, AtlasRegion region) { + if (region == null) throw new System.ArgumentNullException("region"); + MeshAttachment mesh = o.NewLinkedMesh(); + mesh.SetRegion(region, false); + return mesh; + } + + /// + /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. + /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool) + public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Shader shader, Material materialPropertySource = null) { + var m = new Material(shader); + if (materialPropertySource != null) { + m.CopyPropertiesFromMaterial(materialPropertySource); + m.shaderKeywords = materialPropertySource.shaderKeywords; + } + return o.GetLinkedMesh(sprite.name, sprite.ToAtlasRegion()); + } + + /// + /// Returns a new linked mesh linked to this MeshAttachment. It will be mapped to an AtlasRegion generated from a Sprite. The AtlasRegion will be mapped to a new Material based on the shader. + /// For better caching and batching, use GetLinkedMesh(string, AtlasRegion, bool) + public static MeshAttachment GetLinkedMesh (this MeshAttachment o, Sprite sprite, Material materialPropertySource) { + return o.GetLinkedMesh(sprite, materialPropertySource.shader, materialPropertySource); + } + #endregion + + #region RemappedClone Convenience Methods + /// + /// Gets a clone of the attachment remapped with a sprite image. + /// The remapped clone. + /// The original attachment. + /// The sprite whose texture to use. + /// The source material used to copy the shader and material properties from. + /// If true, a premultiply alpha clone of the original texture will be created. + /// See remarks below for additional info. + /// If true MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment. + /// If true the size of the original attachment will be followed, instead of using the Sprite size. + /// If true and the original Attachment is a MeshAttachment, then + /// a non-central sprite pivot will shift uv coords in the opposite direction. Vertices will not be offset in + /// any case when the original Attachment is a MeshAttachment. + /// If true and the original Attachment is a RegionAttachment, then + /// the original region's scale value is used instead of the Sprite's pixels per unit property. Since uniform scale is used, + /// x scale of the original attachment (width scale) is used, scale in y direction (height scale) is ignored. + /// When parameter premultiplyAlpha is set to true, a premultiply alpha clone of the + /// original texture will be created. Additionally, this PMA Texture clone is cached for later re-use, + /// which might steadily increase the Texture memory footprint when used excessively. + /// See on how to clear these cached textures. + public static Attachment GetRemappedClone (this Attachment o, Sprite sprite, Material sourceMaterial, + bool premultiplyAlpha = true, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, + bool pivotShiftsMeshUVCoords = true, bool useOriginalRegionScale = false) { + var atlasRegion = premultiplyAlpha ? sprite.ToAtlasRegionPMAClone(sourceMaterial) : sprite.ToAtlasRegion(new Material(sourceMaterial) { mainTexture = sprite.texture } ); + if (!pivotShiftsMeshUVCoords && o is MeshAttachment) { + // prevent non-central sprite pivot setting offsetX/Y and shifting uv coords out of mesh bounds + atlasRegion.offsetX = 0; + atlasRegion.offsetY = 0; + } + float scale = 1f / sprite.pixelsPerUnit; + if (useOriginalRegionScale) { + var regionAttachment = o as RegionAttachment; + if (regionAttachment != null) + scale = regionAttachment.width / regionAttachment.regionOriginalWidth; + } + return o.GetRemappedClone(atlasRegion, cloneMeshAsLinked, useOriginalRegionSize, scale); + } + + /// + /// Gets a clone of the attachment remapped with an atlasRegion image. + /// The remapped clone. + /// The original attachment. + /// Atlas region. + /// If true MeshAttachments will be cloned as linked meshes and will inherit animation from the original attachment. + /// If true the size of the original attachment will be followed, instead of using the Sprite size. + /// Unity units per pixel scale used to scale the atlas region size when not using the original region size. + public static Attachment GetRemappedClone (this Attachment o, AtlasRegion atlasRegion, bool cloneMeshAsLinked = true, bool useOriginalRegionSize = false, float scale = 0.01f) { + var regionAttachment = o as RegionAttachment; + if (regionAttachment != null) { + RegionAttachment newAttachment = (RegionAttachment)regionAttachment.Copy(); + newAttachment.SetRegion(atlasRegion, false); + if (!useOriginalRegionSize) { + newAttachment.width = atlasRegion.width * scale; + newAttachment.height = atlasRegion.height * scale; + } + newAttachment.UpdateOffset(); + return newAttachment; + } else { + var meshAttachment = o as MeshAttachment; + if (meshAttachment != null) { + MeshAttachment newAttachment = cloneMeshAsLinked ? meshAttachment.NewLinkedMesh() : (MeshAttachment)meshAttachment.Copy(); + newAttachment.SetRegion(atlasRegion); + return newAttachment; + } + } + + return o.GetCopy(true); // Non-renderable Attachments will return as normal cloned attachments. + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs.meta new file mode 100644 index 0000000..4d6580e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentCloneExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3431ed563b2c62f4c8c974a99365ba52 +timeCreated: 1563321428 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs new file mode 100644 index 0000000..6005387 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs @@ -0,0 +1,211 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using System.Collections; + +namespace Spine.Unity.AttachmentTools { + public static class AttachmentRegionExtensions { + #region GetRegion + /// + /// Tries to get the region (image) of a renderable attachment. If the attachment is not renderable, it returns null. + public static AtlasRegion GetRegion (this Attachment attachment) { + var renderableAttachment = attachment as IHasRendererObject; + if (renderableAttachment != null) + return renderableAttachment.RendererObject as AtlasRegion; + + return null; + } + + /// Gets the region (image) of a RegionAttachment + public static AtlasRegion GetRegion (this RegionAttachment regionAttachment) { + return regionAttachment.RendererObject as AtlasRegion; + } + + /// Gets the region (image) of a MeshAttachment + public static AtlasRegion GetRegion (this MeshAttachment meshAttachment) { + return meshAttachment.RendererObject as AtlasRegion; + } + #endregion + #region SetRegion + /// + /// Tries to set the region (image) of a renderable attachment. If the attachment is not renderable, nothing is applied. + public static void SetRegion (this Attachment attachment, AtlasRegion region, bool updateOffset = true) { + var regionAttachment = attachment as RegionAttachment; + if (regionAttachment != null) + regionAttachment.SetRegion(region, updateOffset); + + var meshAttachment = attachment as MeshAttachment; + if (meshAttachment != null) + meshAttachment.SetRegion(region, updateOffset); + } + + /// Sets the region (image) of a RegionAttachment + public static void SetRegion (this RegionAttachment attachment, AtlasRegion region, bool updateOffset = true) { + if (region == null) throw new System.ArgumentNullException("region"); + + // (AtlasAttachmentLoader.cs) + attachment.RendererObject = region; + attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); + attachment.regionOffsetX = region.offsetX; + attachment.regionOffsetY = region.offsetY; + attachment.regionWidth = region.width; + attachment.regionHeight = region.height; + attachment.regionOriginalWidth = region.originalWidth; + attachment.regionOriginalHeight = region.originalHeight; + + if (updateOffset) attachment.UpdateOffset(); + } + + /// Sets the region (image) of a MeshAttachment + public static void SetRegion (this MeshAttachment attachment, AtlasRegion region, bool updateUVs = true) { + if (region == null) throw new System.ArgumentNullException("region"); + + // (AtlasAttachmentLoader.cs) + attachment.RendererObject = region; + attachment.RegionU = region.u; + attachment.RegionV = region.v; + attachment.RegionU2 = region.u2; + attachment.RegionV2 = region.v2; + attachment.RegionRotate = region.rotate; + attachment.RegionDegrees = region.degrees; + attachment.regionOffsetX = region.offsetX; + attachment.regionOffsetY = region.offsetY; + attachment.regionWidth = region.width; + attachment.regionHeight = region.height; + attachment.regionOriginalWidth = region.originalWidth; + attachment.regionOriginalHeight = region.originalHeight; + + if (updateUVs) attachment.UpdateUVs(); + } + #endregion + + #region Runtime RegionAttachments + /// + /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses a new AtlasPage with the Material provided./// + public static RegionAttachment ToRegionAttachment (this Sprite sprite, Material material, float rotation = 0f) { + return sprite.ToRegionAttachment(material.ToSpineAtlasPage(), rotation); + } + + /// + /// Creates a RegionAttachment based on a sprite. This method creates a real, usable AtlasRegion. That AtlasRegion uses the AtlasPage provided./// + public static RegionAttachment ToRegionAttachment (this Sprite sprite, AtlasPage page, float rotation = 0f) { + if (sprite == null) throw new System.ArgumentNullException("sprite"); + if (page == null) throw new System.ArgumentNullException("page"); + var region = sprite.ToAtlasRegion(page); + var unitsPerPixel = 1f / sprite.pixelsPerUnit; + return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation); + } + + /// + /// Creates a Spine.AtlasRegion that uses a premultiplied alpha duplicate texture of the Sprite's texture data. + /// Returns a RegionAttachment that uses it. Use this if you plan to use a premultiply alpha shader such as "Spine/Skeleton". + /// The duplicate texture is cached for later re-use. See documentation of + /// for additional details. + public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Shader shader, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, Material materialPropertySource = null, float rotation = 0f) { + if (sprite == null) throw new System.ArgumentNullException("sprite"); + if (shader == null) throw new System.ArgumentNullException("shader"); + var region = sprite.ToAtlasRegionPMAClone(shader, textureFormat, mipmaps, materialPropertySource); + var unitsPerPixel = 1f / sprite.pixelsPerUnit; + return region.ToRegionAttachment(sprite.name, unitsPerPixel, rotation); + } + + public static RegionAttachment ToRegionAttachmentPMAClone (this Sprite sprite, Material materialPropertySource, TextureFormat textureFormat = AtlasUtilities.SpineTextureFormat, bool mipmaps = AtlasUtilities.UseMipMaps, float rotation = 0f) { + return sprite.ToRegionAttachmentPMAClone(materialPropertySource.shader, textureFormat, mipmaps, materialPropertySource, rotation); + } + + /// + /// Creates a new RegionAttachment from a given AtlasRegion. + public static RegionAttachment ToRegionAttachment (this AtlasRegion region, string attachmentName, float scale = 0.01f, float rotation = 0f) { + if (string.IsNullOrEmpty(attachmentName)) throw new System.ArgumentException("attachmentName can't be null or empty.", "attachmentName"); + if (region == null) throw new System.ArgumentNullException("region"); + + // (AtlasAttachmentLoader.cs) + var attachment = new RegionAttachment(attachmentName); + + attachment.RendererObject = region; + attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate); + attachment.regionOffsetX = region.offsetX; + attachment.regionOffsetY = region.offsetY; + attachment.regionWidth = region.width; + attachment.regionHeight = region.height; + attachment.regionOriginalWidth = region.originalWidth; + attachment.regionOriginalHeight = region.originalHeight; + + attachment.Path = region.name; + attachment.scaleX = 1; + attachment.scaleY = 1; + attachment.rotation = rotation; + + attachment.r = 1; + attachment.g = 1; + attachment.b = 1; + attachment.a = 1; + + // pass OriginalWidth and OriginalHeight because UpdateOffset uses it in its calculation. + attachment.width = attachment.regionOriginalWidth * scale; + attachment.height = attachment.regionOriginalHeight * scale; + + attachment.SetColor(Color.white); + attachment.UpdateOffset(); + return attachment; + } + + /// Sets the scale. Call regionAttachment.UpdateOffset to apply the change. + public static void SetScale (this RegionAttachment regionAttachment, Vector2 scale) { + regionAttachment.scaleX = scale.x; + regionAttachment.scaleY = scale.y; + } + + /// Sets the scale. Call regionAttachment.UpdateOffset to apply the change. + public static void SetScale (this RegionAttachment regionAttachment, float x, float y) { + regionAttachment.scaleX = x; + regionAttachment.scaleY = y; + } + + /// Sets the position offset. Call regionAttachment.UpdateOffset to apply the change. + public static void SetPositionOffset (this RegionAttachment regionAttachment, Vector2 offset) { + regionAttachment.x = offset.x; + regionAttachment.y = offset.y; + } + + /// Sets the position offset. Call regionAttachment.UpdateOffset to apply the change. + public static void SetPositionOffset (this RegionAttachment regionAttachment, float x, float y) { + regionAttachment.x = x; + regionAttachment.y = y; + } + + /// Sets the rotation. Call regionAttachment.UpdateOffset to apply the change. + public static void SetRotation (this RegionAttachment regionAttachment, float rotation) { + regionAttachment.rotation = rotation; + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs.meta new file mode 100644 index 0000000..5826211 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/AttachmentRegionExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7e7eac783deea004e9bc403eca68a7dc +timeCreated: 1563321428 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs new file mode 100644 index 0000000..68ec0d9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs @@ -0,0 +1,324 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using System.Collections.Generic; +using UnityEngine; + +#if UNITY_EDITOR + +namespace Spine.Unity { + /// Utility class providing methods to check material settings for incorrect combinations. + public class MaterialChecks { + + static readonly int STRAIGHT_ALPHA_PARAM_ID = Shader.PropertyToID("_StraightAlphaInput"); + static readonly string ALPHAPREMULTIPLY_ON_KEYWORD = "_ALPHAPREMULTIPLY_ON"; + static readonly string STRAIGHT_ALPHA_KEYWORD = "_STRAIGHT_ALPHA_INPUT"; + static readonly string[] FIXED_NORMALS_KEYWORDS = { + "_FIXED_NORMALS_VIEWSPACE", + "_FIXED_NORMALS_VIEWSPACE_BACKFACE", + "_FIXED_NORMALS_MODELSPACE", + "_FIXED_NORMALS_MODELSPACE_BACKFACE", + "_FIXED_NORMALS_WORLDSPACE" + }; + static readonly string NORMALMAP_KEYWORD = "_NORMALMAP"; + static readonly string CANVAS_GROUP_COMPATIBLE_KEYWORD = "_CANVAS_GROUP_COMPATIBLE"; + + public static readonly string kPMANotSupportedLinearMessage = + "\nWarning: Premultiply-alpha atlas textures not supported in Linear color space!\n\nPlease\n" + + "a) re-export atlas as straight alpha texture with 'premultiply alpha' unchecked\n" + + " (if you have already done this, please set the 'Straight Alpha Texture' Material parameter to 'true') or\n" + + "b) switch to Gamma color space via\nProject Settings - Player - Other Settings - Color Space.\n"; + public static readonly string kZSpacingRequiredMessage = + "\nWarning: Z Spacing required on selected shader! Otherwise you will receive incorrect results.\n\nPlease\n" + + "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n" + + "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n"; + public static readonly string kZSpacingRecommendedMessage = + "\nWarning: Z Spacing recommended on selected shader configuration!\n\nPlease\n" + + "1) make sure at least minimal 'Z Spacing' is set at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' and\n" + + "2) ensure that the skeleton has overlapping parts on different Z depth. You can adjust this in Spine via draw order.\n"; + public static readonly string kAddNormalsMessage = + "\nWarning: 'Add Normals' required when not using 'Fixed Normals'!\n\nPlease\n" + + "a) enable 'Add Normals' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n" + + "b) enable 'Fixed Normals' at the Material.\n"; + public static readonly string kSolveTangentsMessage = + "\nWarning: 'Solve Tangents' required when using a Normal Map!\n\nPlease\n" + + "a) enable 'Solve Tangents' at the SkeletonRenderer/SkeletonAnimation component under 'Advanced' or\n" + + "b) clear the 'Normal Map' parameter at the Material.\n"; + public static readonly string kNoSkeletonGraphicMaterialMessage = + "\nWarning: Normal non-UI shaders other than 'Spine/SkeletonGraphic *' are not compatible with 'SkeletonGraphic' components! " + + "This will lead to incorrect rendering on some devices.\n\n" + + "Please change the assigned Material to e.g. 'SkeletonGraphicDefault' or change the used shader to one of the 'Spine/SkeletonGraphic *' shaders.\n\n" + + "Note that 'Spine/SkeletonGraphic *' shall still be used when using URP.\n"; + public static readonly string kNoSkeletonGraphicTintBlackMaterialMessage = + "\nWarning: Only enable 'Canvas Group Tint Black' when using a 'SkeletonGraphic Tint Black' shader!\n" + + "This will lead to incorrect rendering.\n\nPlease\n" + + "a) disable 'Canvas Group Tint Black' under 'Advanced' or\n" + + "b) use a 'SkeletonGraphic Tint Black' Material if you need Tint Black on a CanvasGroup.\n"; + + public static readonly string kTintBlackMessage = + "\nWarning: 'Advanced - Tint Black' required when using any 'Tint Black' shader!\n\nPlease\n" + + "a) enable 'Tint Black' at the SkeletonRenderer/SkeletonGraphic component under 'Advanced' or\n" + + "b) use a different shader at the Material.\n"; + public static readonly string kCanvasTintBlackMessage = + "\nWarning: Canvas 'Additional Shader Channels' 'uv1' and 'uv2' are required when 'Advanced - Tint Black' is enabled!\n\n" + + "Please enable both 'uv1' and 'uv2' channels at the parent Canvas component parameter 'Additional Shader Channels'.\n"; + public static readonly string kCanvasGroupCompatibleMessage = + "\nWarning: 'Canvas Group Tint Black' is enabled at SkeletonGraphic but not 'CanvasGroup Compatible' at the Material!\n\nPlease\n" + + "a) enable 'CanvasGroup Compatible' at the Material or\n" + + "b) disable 'Canvas Group Tint Black' at the SkeletonGraphic component under 'Advanced'.\n" + + "You may want to duplicate the 'SkeletonGraphicDefault' material and change settings at the duplicate to not affect all instances."; + + public static bool IsMaterialSetupProblematic (SkeletonRenderer renderer, ref string errorMessage) { + var materials = renderer.GetComponent().sharedMaterials; + bool isProblematic = false; + foreach (var material in materials) { + if (material == null) continue; + isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage); + if (renderer.zSpacing == 0) { + isProblematic |= IsZSpacingRequired(material, ref errorMessage); + } + if (renderer.addNormals == false && RequiresMeshNormals(material)) { + isProblematic = true; + errorMessage += kAddNormalsMessage; + } + if (renderer.calculateTangents == false && RequiresTangents(material)) { + isProblematic = true; + errorMessage += kSolveTangentsMessage; + } + if (renderer.tintBlack == false && RequiresTintBlack(material)) { + isProblematic = true; + errorMessage += kTintBlackMessage; + } + } + return isProblematic; + } + + public static bool IsMaterialSetupProblematic(SkeletonGraphic skeletonGraphic, ref string errorMessage) + { + var material = skeletonGraphic.material; + bool isProblematic = false; + if (material) { + isProblematic |= IsMaterialSetupProblematic(material, ref errorMessage); + var settings = skeletonGraphic.MeshGenerator.settings; + if (settings.zSpacing == 0) { + isProblematic |= IsZSpacingRequired(material, ref errorMessage); + } + if (IsSpineNonSkeletonGraphicMaterial(material)) { + isProblematic = true; + errorMessage += kNoSkeletonGraphicMaterialMessage; + } + if (settings.tintBlack == false && RequiresTintBlack(material)) { + isProblematic = true; + errorMessage += kTintBlackMessage; + } + if (settings.tintBlack == true && CanvasNotSetupForTintBlack(skeletonGraphic)) { + isProblematic = true; + errorMessage += kCanvasTintBlackMessage; + } + if (settings.canvasGroupTintBlack == true && !IsSkeletonGraphicTintBlackMaterial(material)) { + isProblematic = true; + errorMessage += kNoSkeletonGraphicTintBlackMaterialMessage; + } + if (settings.canvasGroupTintBlack == true && !IsCanvasGroupCompatible(material)) { + isProblematic = true; + errorMessage += kCanvasGroupCompatibleMessage; + } + } + return isProblematic; + } + + public static bool IsMaterialSetupProblematic(Material material, ref string errorMessage) { + return !IsColorSpaceSupported(material, ref errorMessage); + } + + public static bool IsZSpacingRequired(Material material, ref string errorMessage) { + bool hasForwardAddPass = material.FindPass("FORWARD_DELTA") >= 0; + if (hasForwardAddPass) { + errorMessage += kZSpacingRequiredMessage; + return true; + } + bool zWrite = material.HasProperty("_ZWrite") && material.GetFloat("_ZWrite") > 0.0f; + if (zWrite) { + errorMessage += kZSpacingRecommendedMessage; + return true; + } + return false; + } + + public static bool IsColorSpaceSupported (Material material, ref string errorMessage) { + if (QualitySettings.activeColorSpace == ColorSpace.Linear) { + if (IsPMAMaterial(material)) { + errorMessage += kPMANotSupportedLinearMessage; + return false; + } + } + return true; + } + + + public static bool UsesSpineShader (Material material) { + return material.shader.name.Contains("Spine/"); + } + + public static bool IsTextureSetupProblematic (Material material, ColorSpace colorSpace, + bool sRGBTexture, bool mipmapEnabled, bool alphaIsTransparency, + string texturePath, string materialPath, + ref string errorMessage) { + + if (material == null || !UsesSpineShader(material)) { + return false; + } + + bool isProblematic = false; + if (IsPMAMaterial(material)) { + // 'sRGBTexture = true' generates incorrectly weighted mipmaps at PMA textures, + // causing white borders due to undesired custom weighting. + if (sRGBTexture && mipmapEnabled && colorSpace == ColorSpace.Gamma) { + errorMessage += string.Format("`{0}` : Problematic Texture Settings found: " + + "When enabling `Generate Mip Maps` in Gamma color space, it is recommended " + + "to disable `sRGB (Color Texture)` on `Premultiply alpha` textures. Otherwise " + + "you will receive white border artifacts on an atlas exported with default " + + "`Premultiply alpha` settings.\n" + + "(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath); + isProblematic = true; + } + if (alphaIsTransparency) { + string materialName = System.IO.Path.GetFileName(materialPath); + errorMessage += string.Format("`{0}` and material `{1}` : Problematic " + + "Texture / Material Settings found: It is recommended to disable " + + "`Alpha Is Transparency` on `Premultiply alpha` textures.\n" + + "Assuming `Premultiply alpha` texture because `Straight Alpha Texture` " + + "is disabled at material). " + + "(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName); + isProblematic = true; + } + } + else { // straight alpha texture + if (!alphaIsTransparency) { + string materialName = System.IO.Path.GetFileName(materialPath); + errorMessage += string.Format("`{0}` and material `{1}` : Incorrect" + + "Texture / Material Settings found: It is strongly recommended " + + "to enable `Alpha Is Transparency` on `Straight alpha` textures.\n" + + "Assuming `Straight alpha` texture because `Straight Alpha Texture` " + + "is enabled at material). " + + "(You can disable this warning in `Edit - Preferences - Spine`)\n", texturePath, materialName); + isProblematic = true; + } + } + return isProblematic; + } + + public static void EnablePMAAtMaterial (Material material, bool enablePMA) { + if (material.HasProperty(STRAIGHT_ALPHA_PARAM_ID)) { + material.SetInt(STRAIGHT_ALPHA_PARAM_ID, enablePMA ? 0 : 1); + if (enablePMA) + material.DisableKeyword(STRAIGHT_ALPHA_KEYWORD); + else + material.EnableKeyword(STRAIGHT_ALPHA_KEYWORD); + } + else { + if (enablePMA) + material.EnableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD); + else + material.DisableKeyword(ALPHAPREMULTIPLY_ON_KEYWORD); + } + } + + static bool IsPMAMaterial (Material material) { + bool usesAlphaPremultiplyKeyword = IsSpriteShader(material); + if (usesAlphaPremultiplyKeyword) + return material.IsKeywordEnabled(ALPHAPREMULTIPLY_ON_KEYWORD); + else + return material.HasProperty(STRAIGHT_ALPHA_PARAM_ID) && material.GetInt(STRAIGHT_ALPHA_PARAM_ID) == 0; + } + + static bool IsURP3DMaterial (Material material) { + return material.shader.name.Contains("Universal Render Pipeline/Spine"); + } + + static bool IsSpineNonSkeletonGraphicMaterial (Material material) { + return material.shader.name.Contains("Spine") && !material.shader.name.Contains("SkeletonGraphic"); + } + + static bool IsSkeletonGraphicTintBlackMaterial (Material material) { + return material.shader.name.Contains("Spine") && material.shader.name.Contains("SkeletonGraphic") + && material.shader.name.Contains("Black"); + } + + static bool AreShadowsDisabled (Material material) { + return material.IsKeywordEnabled("_RECEIVE_SHADOWS_OFF"); + } + + static bool RequiresMeshNormals (Material material) { + bool anyFixedNormalSet = false; + foreach (string fixedNormalKeyword in FIXED_NORMALS_KEYWORDS) { + if (material.IsKeywordEnabled(fixedNormalKeyword)) { + anyFixedNormalSet = true; + break; + } + } + bool isShaderWithMeshNormals = IsSpriteShader(material); + return isShaderWithMeshNormals && !anyFixedNormalSet; + } + + static bool IsSpriteShader (Material material) { + string shaderName = material.shader.name; + return shaderName.Contains("Spine/Sprite/Pixel Lit") || + shaderName.Contains("Spine/Sprite/Vertex Lit") || + shaderName.Contains("2D/Spine/Sprite") || // covers both URP and LWRP + shaderName.Contains("Pipeline/Spine/Sprite"); // covers both URP and LWRP + } + + static bool RequiresTintBlack (Material material) { + bool isTintBlackShader = + material.shader.name.Contains("Spine") && + material.shader.name.Contains("Tint Black"); + return isTintBlackShader; + } + + static bool RequiresTangents (Material material) { + return material.IsKeywordEnabled(NORMALMAP_KEYWORD); + } + static bool IsCanvasGroupCompatible (Material material) { + return material.IsKeywordEnabled(CANVAS_GROUP_COMPATIBLE_KEYWORD); + } + + static bool CanvasNotSetupForTintBlack (SkeletonGraphic skeletonGraphic) { + Canvas canvas = skeletonGraphic.canvas; + if (!canvas) + return false; + var requiredChannels = + AdditionalCanvasShaderChannels.TexCoord1 | + AdditionalCanvasShaderChannels.TexCoord2; + return (canvas.additionalShaderChannels & requiredChannels) != requiredChannels; + } + } +} + +#endif // UNITY_EDITOR diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs.meta new file mode 100644 index 0000000..7535c40 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/MaterialChecks.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e68fa8db689084946adce454b83e6d4a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs new file mode 100644 index 0000000..4ca34de --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs @@ -0,0 +1,614 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; + +namespace Spine.Unity { + public static class SkeletonExtensions { + + #region Colors + const float ByteToFloat = 1f / 255f; + public static Color GetColor (this Skeleton s) { return new Color(s.r, s.g, s.b, s.a); } + public static Color GetColor (this RegionAttachment a) { return new Color(a.r, a.g, a.b, a.a); } + public static Color GetColor (this MeshAttachment a) { return new Color(a.r, a.g, a.b, a.a); } + public static Color GetColor (this Slot s) { return new Color(s.r, s.g, s.b, s.a); } + public static Color GetColorTintBlack (this Slot s) { return new Color(s.r2, s.g2, s.b2, 1f); } + + public static void SetColor (this Skeleton skeleton, Color color) { + skeleton.A = color.a; + skeleton.R = color.r; + skeleton.G = color.g; + skeleton.B = color.b; + } + + public static void SetColor (this Skeleton skeleton, Color32 color) { + skeleton.A = color.a * ByteToFloat; + skeleton.R = color.r * ByteToFloat; + skeleton.G = color.g * ByteToFloat; + skeleton.B = color.b * ByteToFloat; + } + + public static void SetColor (this Slot slot, Color color) { + slot.A = color.a; + slot.R = color.r; + slot.G = color.g; + slot.B = color.b; + } + + public static void SetColor (this Slot slot, Color32 color) { + slot.A = color.a * ByteToFloat; + slot.R = color.r * ByteToFloat; + slot.G = color.g * ByteToFloat; + slot.B = color.b * ByteToFloat; + } + + public static void SetColor (this RegionAttachment attachment, Color color) { + attachment.A = color.a; + attachment.R = color.r; + attachment.G = color.g; + attachment.B = color.b; + } + + public static void SetColor (this RegionAttachment attachment, Color32 color) { + attachment.A = color.a * ByteToFloat; + attachment.R = color.r * ByteToFloat; + attachment.G = color.g * ByteToFloat; + attachment.B = color.b * ByteToFloat; + } + + public static void SetColor (this MeshAttachment attachment, Color color) { + attachment.A = color.a; + attachment.R = color.r; + attachment.G = color.g; + attachment.B = color.b; + } + + public static void SetColor (this MeshAttachment attachment, Color32 color) { + attachment.A = color.a * ByteToFloat; + attachment.R = color.r * ByteToFloat; + attachment.G = color.g * ByteToFloat; + attachment.B = color.b * ByteToFloat; + } + #endregion + + #region Skeleton + /// Sets the Skeleton's local scale using a UnityEngine.Vector2. If only individual components need to be set, set Skeleton.ScaleX or Skeleton.ScaleY. + public static void SetLocalScale (this Skeleton skeleton, Vector2 scale) { + skeleton.ScaleX = scale.x; + skeleton.ScaleY = scale.y; + } + + /// Gets the internal bone matrix as a Unity bonespace-to-skeletonspace transformation matrix. + public static Matrix4x4 GetMatrix4x4 (this Bone bone) { + return new Matrix4x4 { + m00 = bone.a, + m01 = bone.b, + m03 = bone.worldX, + m10 = bone.c, + m11 = bone.d, + m13 = bone.worldY, + m33 = 1 + }; + } + #endregion + + #region Bone + /// Sets the bone's (local) X and Y according to a Vector2 + public static void SetLocalPosition (this Bone bone, Vector2 position) { + bone.X = position.x; + bone.Y = position.y; + } + + /// Sets the bone's (local) X and Y according to a Vector3. The z component is ignored. + public static void SetLocalPosition (this Bone bone, Vector3 position) { + bone.X = position.x; + bone.Y = position.y; + } + + /// Gets the bone's local X and Y as a Vector2. + public static Vector2 GetLocalPosition (this Bone bone) { + return new Vector2(bone.x, bone.y); + } + + /// Gets the position of the bone in Skeleton-space. + public static Vector2 GetSkeletonSpacePosition (this Bone bone) { + return new Vector2(bone.worldX, bone.worldY); + } + + /// Gets a local offset from the bone and converts it into Skeleton-space. + public static Vector2 GetSkeletonSpacePosition (this Bone bone, Vector2 boneLocal) { + Vector2 o; + bone.LocalToWorld(boneLocal.x, boneLocal.y, out o.x, out o.y); + return o; + } + + /// Gets the bone's Unity World position using its Spine GameObject Transform. UpdateWorldTransform needs to have been called for this to return the correct, updated value. + public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform) { + return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY)); + } + + public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform, float positionScale) { + return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX * positionScale, bone.worldY * positionScale)); + } + + /// Gets a skeleton space UnityEngine.Quaternion representation of bone.WorldRotationX. + public static Quaternion GetQuaternion (this Bone bone) { + var halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; + return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation)); + } + + /// Gets a bone-local space UnityEngine.Quaternion representation of bone.rotation. + public static Quaternion GetLocalQuaternion (this Bone bone) { + var halfRotation = bone.rotation * Mathf.Deg2Rad * 0.5f; + return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation)); + } + + /// Returns the Skeleton's local scale as a UnityEngine.Vector2. If only individual components are needed, use Skeleton.ScaleX or Skeleton.ScaleY. + public static Vector2 GetLocalScale (this Skeleton skeleton) { + return new Vector2(skeleton.ScaleX, skeleton.ScaleY); + } + + /// Calculates a 2x2 Transformation Matrix that can convert a skeleton-space position to a bone-local position. + public static void GetWorldToLocalMatrix (this Bone bone, out float ia, out float ib, out float ic, out float id) { + float a = bone.a, b = bone.b, c = bone.c, d = bone.d; + float invDet = 1 / (a * d - b * c); + ia = invDet * d; + ib = invDet * -b; + ic = invDet * -c; + id = invDet * a; + } + + /// UnityEngine.Vector2 override of Bone.WorldToLocal. This converts a skeleton-space position into a bone local position. + public static Vector2 WorldToLocal (this Bone bone, Vector2 worldPosition) { + Vector2 o; + bone.WorldToLocal(worldPosition.x, worldPosition.y, out o.x, out o.y); + return o; + } + + /// Sets the skeleton-space position of a bone. + /// The local position in its parent bone space, or in skeleton space if it is the root bone. + public static Vector2 SetPositionSkeletonSpace (this Bone bone, Vector2 skeletonSpacePosition) { + if (bone.parent == null) { // root bone + bone.SetLocalPosition(skeletonSpacePosition); + return skeletonSpacePosition; + } else { + var parent = bone.parent; + Vector2 parentLocal = parent.WorldToLocal(skeletonSpacePosition); + bone.SetLocalPosition(parentLocal); + return parentLocal; + } + } + #endregion + + #region Attachments + public static Material GetMaterial (this Attachment a) { + object rendererObject = null; + var renderableAttachment = a as IHasRendererObject; + if (renderableAttachment != null) + rendererObject = renderableAttachment.RendererObject; + + if (rendererObject == null) + return null; + + #if SPINE_TK2D + return (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; + #else + return (Material)((AtlasRegion)rendererObject).page.rendererObject; + #endif + } + + /// Fills a Vector2 buffer with local vertices. + /// The VertexAttachment + /// Slot where the attachment belongs. + /// Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated. + public static Vector2[] GetLocalVertices (this VertexAttachment va, Slot slot, Vector2[] buffer) { + int floatsCount = va.worldVerticesLength; + int bufferTargetSize = floatsCount >> 1; + buffer = buffer ?? new Vector2[bufferTargetSize]; + if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", va.Name, floatsCount), "buffer"); + + if (va.bones == null) { + var localVerts = va.vertices; + for (int i = 0; i < bufferTargetSize; i++) { + int j = i * 2; + buffer[i] = new Vector2(localVerts[j], localVerts[j+1]); + } + } else { + var floats = new float[floatsCount]; + va.ComputeWorldVertices(slot, floats); + + Bone sb = slot.bone; + float ia, ib, ic, id, bwx = sb.worldX, bwy = sb.worldY; + sb.GetWorldToLocalMatrix(out ia, out ib, out ic, out id); + + for (int i = 0; i < bufferTargetSize; i++) { + int j = i * 2; + float x = floats[j] - bwx, y = floats[j+1] - bwy; + buffer[i] = new Vector2(x * ia + y * ib, x * ic + y * id); + } + } + + return buffer; + } + + /// Calculates world vertices and fills a Vector2 buffer. + /// The VertexAttachment + /// Slot where the attachment belongs. + /// Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated. + public static Vector2[] GetWorldVertices (this VertexAttachment a, Slot slot, Vector2[] buffer) { + int worldVertsLength = a.worldVerticesLength; + int bufferTargetSize = worldVertsLength >> 1; + buffer = buffer ?? new Vector2[bufferTargetSize]; + if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", a.Name, worldVertsLength), "buffer"); + + var floats = new float[worldVertsLength]; + a.ComputeWorldVertices(slot, floats); + + for (int i = 0, n = worldVertsLength >> 1; i < n; i++) { + int j = i * 2; + buffer[i] = new Vector2(floats[j], floats[j + 1]); + } + + return buffer; + } + + /// Gets the PointAttachment's Unity World position using its Spine GameObject Transform. + public static Vector3 GetWorldPosition (this PointAttachment attachment, Slot slot, Transform spineGameObjectTransform) { + Vector3 skeletonSpacePosition; + skeletonSpacePosition.z = 0; + attachment.ComputeWorldPosition(slot.bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y); + return spineGameObjectTransform.TransformPoint(skeletonSpacePosition); + } + + /// Gets the PointAttachment's Unity World position using its Spine GameObject Transform. + public static Vector3 GetWorldPosition (this PointAttachment attachment, Bone bone, Transform spineGameObjectTransform) { + Vector3 skeletonSpacePosition; + skeletonSpacePosition.z = 0; + attachment.ComputeWorldPosition(bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y); + return spineGameObjectTransform.TransformPoint(skeletonSpacePosition); + } + #endregion + } +} + +namespace Spine { + using System; + using System.Collections.Generic; + + public struct BoneMatrix { + public float a, b, c, d, x, y; + + /// Recursively calculates a worldspace bone matrix based on BoneData. + public static BoneMatrix CalculateSetupWorld (BoneData boneData) { + if (boneData == null) + return default(BoneMatrix); + + // End condition: isRootBone + if (boneData.parent == null) + return GetInheritedInternal(boneData, default(BoneMatrix)); + + BoneMatrix result = CalculateSetupWorld(boneData.parent); + return GetInheritedInternal(boneData, result); + } + + static BoneMatrix GetInheritedInternal (BoneData boneData, BoneMatrix parentMatrix) { + var parent = boneData.parent; + if (parent == null) return new BoneMatrix(boneData); // isRootBone + + float pa = parentMatrix.a, pb = parentMatrix.b, pc = parentMatrix.c, pd = parentMatrix.d; + BoneMatrix result = default(BoneMatrix); + result.x = pa * boneData.x + pb * boneData.y + parentMatrix.x; + result.y = pc * boneData.x + pd * boneData.y + parentMatrix.y; + + switch (boneData.transformMode) { + case TransformMode.Normal: { + float rotationY = boneData.rotation + 90 + boneData.shearY; + float la = MathUtils.CosDeg(boneData.rotation + boneData.shearX) * boneData.scaleX; + float lb = MathUtils.CosDeg(rotationY) * boneData.scaleY; + float lc = MathUtils.SinDeg(boneData.rotation + boneData.shearX) * boneData.scaleX; + float ld = MathUtils.SinDeg(rotationY) * boneData.scaleY; + result.a = pa * la + pb * lc; + result.b = pa * lb + pb * ld; + result.c = pc * la + pd * lc; + result.d = pc * lb + pd * ld; + break; + } + case TransformMode.OnlyTranslation: { + float rotationY = boneData.rotation + 90 + boneData.shearY; + result.a = MathUtils.CosDeg(boneData.rotation + boneData.shearX) * boneData.scaleX; + result.b = MathUtils.CosDeg(rotationY) * boneData.scaleY; + result.c = MathUtils.SinDeg(boneData.rotation + boneData.shearX) * boneData.scaleX; + result.d = MathUtils.SinDeg(rotationY) * boneData.scaleY; + break; + } + case TransformMode.NoRotationOrReflection: { + float s = pa * pa + pc * pc, prx; + if (s > 0.0001f) { + s = Math.Abs(pa * pd - pb * pc) / s; + pb = pc * s; + pd = pa * s; + prx = MathUtils.Atan2(pc, pa) * MathUtils.RadDeg; + } else { + pa = 0; + pc = 0; + prx = 90 - MathUtils.Atan2(pd, pb) * MathUtils.RadDeg; + } + float rx = boneData.rotation + boneData.shearX - prx; + float ry = boneData.rotation + boneData.shearY - prx + 90; + float la = MathUtils.CosDeg(rx) * boneData.scaleX; + float lb = MathUtils.CosDeg(ry) * boneData.scaleY; + float lc = MathUtils.SinDeg(rx) * boneData.scaleX; + float ld = MathUtils.SinDeg(ry) * boneData.scaleY; + result.a = pa * la - pb * lc; + result.b = pa * lb - pb * ld; + result.c = pc * la + pd * lc; + result.d = pc * lb + pd * ld; + break; + } + case TransformMode.NoScale: + case TransformMode.NoScaleOrReflection: { + float cos = MathUtils.CosDeg(boneData.rotation), sin = MathUtils.SinDeg(boneData.rotation); + float za = pa * cos + pb * sin; + float zc = pc * cos + pd * sin; + float s = (float)Math.Sqrt(za * za + zc * zc); + if (s > 0.00001f) + s = 1 / s; + za *= s; + zc *= s; + s = (float)Math.Sqrt(za * za + zc * zc); + float r = MathUtils.PI / 2 + MathUtils.Atan2(zc, za); + float zb = MathUtils.Cos(r) * s; + float zd = MathUtils.Sin(r) * s; + float la = MathUtils.CosDeg(boneData.shearX) * boneData.scaleX; + float lb = MathUtils.CosDeg(90 + boneData.shearY) * boneData.scaleY; + float lc = MathUtils.SinDeg(boneData.shearX) * boneData.scaleX; + float ld = MathUtils.SinDeg(90 + boneData.shearY) * boneData.scaleY; + if (boneData.transformMode != TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : false) { + zb = -zb; + zd = -zd; + } + result.a = za * la + zb * lc; + result.b = za * lb + zb * ld; + result.c = zc * la + zd * lc; + result.d = zc * lb + zd * ld; + break; + } + } + + return result; + } + + /// Constructor for a local bone matrix based on Setup Pose BoneData. + public BoneMatrix (BoneData boneData) { + float rotationY = boneData.rotation + 90 + boneData.shearY; + float rotationX = boneData.rotation + boneData.shearX; + + a = MathUtils.CosDeg(rotationX) * boneData.scaleX; + c = MathUtils.SinDeg(rotationX) * boneData.scaleX; + b = MathUtils.CosDeg(rotationY) * boneData.scaleY; + d = MathUtils.SinDeg(rotationY) * boneData.scaleY; + x = boneData.x; + y = boneData.y; + } + + /// Constructor for a local bone matrix based on a bone instance's current pose. + public BoneMatrix (Bone bone) { + float rotationY = bone.rotation + 90 + bone.shearY; + float rotationX = bone.rotation + bone.shearX; + + a = MathUtils.CosDeg(rotationX) * bone.scaleX; + c = MathUtils.SinDeg(rotationX) * bone.scaleX; + b = MathUtils.CosDeg(rotationY) * bone.scaleY; + d = MathUtils.SinDeg(rotationY) * bone.scaleY; + x = bone.x; + y = bone.y; + } + + public BoneMatrix TransformMatrix (BoneMatrix local) { + return new BoneMatrix { + a = this.a * local.a + this.b * local.c, + b = this.a * local.b + this.b * local.d, + c = this.c * local.a + this.d * local.c, + d = this.c * local.b + this.d * local.d, + x = this.a * local.x + this.b * local.y + this.x, + y = this.c * local.x + this.d * local.y + this.y + }; + } + } + + public static class SpineSkeletonExtensions { + public static bool IsWeighted (this VertexAttachment va) { + return va.bones != null && va.bones.Length > 0; + } + + public static bool IsRenderable (this Attachment a) { + return a is IHasRendererObject; + } + + #region Transform Modes + public static bool InheritsRotation (this TransformMode mode) { + const int RotationBit = 0; + return ((int)mode & (1U << RotationBit)) == 0; + } + + public static bool InheritsScale (this TransformMode mode) { + const int ScaleBit = 1; + return ((int)mode & (1U << ScaleBit)) == 0; + } + #endregion + + #region Posing + internal static void SetPropertyToSetupPose (this Skeleton skeleton, int propertyID) { + int tt = propertyID >> 24; + var timelineType = (TimelineType)tt; + int i = propertyID - (tt << 24); + + Bone bone; + IkConstraint ikc; + PathConstraint pc; + + switch (timelineType) { + // Bone + case TimelineType.Rotate: + bone = skeleton.bones.Items[i]; + bone.rotation = bone.data.rotation; + break; + case TimelineType.Translate: + bone = skeleton.bones.Items[i]; + bone.x = bone.data.x; + bone.y = bone.data.y; + break; + case TimelineType.Scale: + bone = skeleton.bones.Items[i]; + bone.scaleX = bone.data.scaleX; + bone.scaleY = bone.data.scaleY; + break; + case TimelineType.Shear: + bone = skeleton.bones.Items[i]; + bone.shearX = bone.data.shearX; + bone.shearY = bone.data.shearY; + break; + + // Slot + case TimelineType.Attachment: + skeleton.SetSlotAttachmentToSetupPose(i); + break; + case TimelineType.Color: + skeleton.slots.Items[i].SetColorToSetupPose(); + break; + case TimelineType.TwoColor: + skeleton.slots.Items[i].SetColorToSetupPose(); + break; + case TimelineType.Deform: + skeleton.slots.Items[i].Deform.Clear(); + break; + + // Skeleton + case TimelineType.DrawOrder: + skeleton.SetDrawOrderToSetupPose(); + break; + + // IK Constraint + case TimelineType.IkConstraint: + ikc = skeleton.ikConstraints.Items[i]; + ikc.mix = ikc.data.mix; + ikc.softness = ikc.data.softness; + ikc.bendDirection = ikc.data.bendDirection; + ikc.stretch = ikc.data.stretch; + break; + + // TransformConstraint + case TimelineType.TransformConstraint: + var tc = skeleton.transformConstraints.Items[i]; + var tcData = tc.data; + tc.rotateMix = tcData.rotateMix; + tc.translateMix = tcData.translateMix; + tc.scaleMix = tcData.scaleMix; + tc.shearMix = tcData.shearMix; + break; + + // Path Constraint + case TimelineType.PathConstraintPosition: + pc = skeleton.pathConstraints.Items[i]; + pc.position = pc.data.position; + break; + case TimelineType.PathConstraintSpacing: + pc = skeleton.pathConstraints.Items[i]; + pc.spacing = pc.data.spacing; + break; + case TimelineType.PathConstraintMix: + pc = skeleton.pathConstraints.Items[i]; + pc.rotateMix = pc.data.rotateMix; + pc.translateMix = pc.data.translateMix; + break; + } + } + + /// Resets the DrawOrder to the Setup Pose's draw order + public static void SetDrawOrderToSetupPose (this Skeleton skeleton) { + var slotsItems = skeleton.slots.Items; + int n = skeleton.slots.Count; + + var drawOrder = skeleton.drawOrder; + drawOrder.Clear(false); + drawOrder.EnsureCapacity(n); + drawOrder.Count = n; + System.Array.Copy(slotsItems, drawOrder.Items, n); + } + + /// Resets all the slots on the skeleton to their Setup Pose attachments but does not reset slot colors. + public static void SetSlotAttachmentsToSetupPose (this Skeleton skeleton) { + var slotsItems = skeleton.slots.Items; + for (int i = 0; i < skeleton.slots.Count; i++) { + Slot slot = slotsItems[i]; + string attachmentName = slot.data.attachmentName; + slot.Attachment = string.IsNullOrEmpty(attachmentName) ? null : skeleton.GetAttachment(i, attachmentName); + } + } + + /// Resets the color of a slot to Setup Pose value. + public static void SetColorToSetupPose (this Slot slot) { + slot.r = slot.data.r; + slot.g = slot.data.g; + slot.b = slot.data.b; + slot.a = slot.data.a; + slot.r2 = slot.data.r2; + slot.g2 = slot.data.g2; + slot.b2 = slot.data.b2; + } + + /// Sets a slot's attachment to setup pose. If you have the slotIndex, Skeleton.SetSlotAttachmentToSetupPose is faster. + public static void SetAttachmentToSetupPose (this Slot slot) { + var slotData = slot.data; + slot.Attachment = slot.bone.skeleton.GetAttachment(slotData.name, slotData.attachmentName); + } + + /// Resets the attachment of slot at a given slotIndex to setup pose. This is faster than Slot.SetAttachmentToSetupPose. + public static void SetSlotAttachmentToSetupPose (this Skeleton skeleton, int slotIndex) { + var slot = skeleton.slots.Items[slotIndex]; + string attachmentName = slot.data.attachmentName; + if (string.IsNullOrEmpty(attachmentName)) { + slot.Attachment = null; + } else { + var attachment = skeleton.GetAttachment(slotIndex, attachmentName); + slot.Attachment = attachment; + } + } + + /// Resets Skeleton parts to Setup Pose according to a Spine.Animation's keyed items. + public static void SetKeyedItemsToSetupPose (this Animation animation, Skeleton skeleton) { + animation.Apply(skeleton, 0, 0, false, null, 0, MixBlend.Setup, MixDirection.Out); + } + + public static void AllowImmediateQueue (this TrackEntry trackEntry) { + if (trackEntry.nextTrackLast < 0) trackEntry.nextTrackLast = 0; + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs.meta new file mode 100644 index 0000000..427cdd1 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkeletonExtensions.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea85c8f6a91a6ab45881b0dbdaabb7d0 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs new file mode 100644 index 0000000..7da1182 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs @@ -0,0 +1,168 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using System.Collections; + +namespace Spine.Unity.AttachmentTools { + + public static class SkinUtilities { + + #region Skeleton Skin Extensions + /// + /// Convenience method for duplicating a skeleton's current active skin so changes to it will not affect other skeleton instances. . + public static Skin UnshareSkin (this Skeleton skeleton, bool includeDefaultSkin, bool unshareAttachments, AnimationState state = null) { + // 1. Copy the current skin and set the skeleton's skin to the new one. + var newSkin = skeleton.GetClonedSkin("cloned skin", includeDefaultSkin, unshareAttachments, true); + skeleton.SetSkin(newSkin); + + // 2. Apply correct attachments: skeleton.SetToSetupPose + animationState.Apply + if (state != null) { + skeleton.SetToSetupPose(); + state.Apply(skeleton); + } + + // 3. Return unshared skin. + return newSkin; + } + + public static Skin GetClonedSkin (this Skeleton skeleton, string newSkinName, bool includeDefaultSkin = false, bool cloneAttachments = false, bool cloneMeshesAsLinked = true) { + var newSkin = new Skin(newSkinName); // may have null name. Harmless. + var defaultSkin = skeleton.data.DefaultSkin; + var activeSkin = skeleton.skin; + + if (includeDefaultSkin) + defaultSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); + + if (activeSkin != null) + activeSkin.CopyTo(newSkin, true, cloneAttachments, cloneMeshesAsLinked); + + return newSkin; + } + #endregion + + /// + /// Gets a shallow copy of the skin. The cloned skin's attachments are shared with the original skin. + public static Skin GetClone (this Skin original) { + var newSkin = new Skin(original.name + " clone"); + var newSkinAttachments = newSkin.Attachments; + var newSkinBones = newSkin.Bones; + var newSkinConstraints = newSkin.Constraints; + + foreach (var a in original.Attachments) + newSkinAttachments[a.Key] = a.Value; + + newSkinBones.AddRange(original.bones); + newSkinConstraints.AddRange(original.constraints); + return newSkin; + } + + /// Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced. + public static void SetAttachment (this Skin skin, string slotName, string keyName, Attachment attachment, Skeleton skeleton) { + int slotIndex = skeleton.FindSlotIndex(slotName); + if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); + if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); + skin.SetAttachment(slotIndex, keyName, attachment); + } + + /// Adds skin items from another skin. For items that already exist, the previous values are replaced. + public static void AddAttachments (this Skin skin, Skin otherSkin) { + if (otherSkin == null) return; + otherSkin.CopyTo(skin, true, false); + } + + /// Gets an attachment from the skin for the specified slot index and name. + public static Attachment GetAttachment (this Skin skin, string slotName, string keyName, Skeleton skeleton) { + int slotIndex = skeleton.FindSlotIndex(slotName); + if (skeleton == null) throw new System.ArgumentNullException("skeleton", "skeleton cannot be null."); + if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); + return skin.GetAttachment(slotIndex, keyName); + } + + /// Adds an attachment to the skin for the specified slot index and name. If the name already exists for the slot, the previous value is replaced. + public static void SetAttachment (this Skin skin, int slotIndex, string keyName, Attachment attachment) { + skin.SetAttachment(slotIndex, keyName, attachment); + } + + public static void RemoveAttachment (this Skin skin, string slotName, string keyName, SkeletonData skeletonData) { + int slotIndex = skeletonData.FindSlotIndex(slotName); + if (skeletonData == null) throw new System.ArgumentNullException("skeletonData", "skeletonData cannot be null."); + if (slotIndex == -1) throw new System.ArgumentException(string.Format("Slot '{0}' does not exist in skeleton.", slotName), "slotName"); + skin.RemoveAttachment(slotIndex, keyName); + } + + public static void Clear (this Skin skin) { + skin.Attachments.Clear(); + } + + //[System.Obsolete] + public static void Append (this Skin destination, Skin source) { + source.CopyTo(destination, true, false); + } + + public static void CopyTo (this Skin source, Skin destination, bool overwrite, bool cloneAttachments, bool cloneMeshesAsLinked = true) { + var sourceAttachments = source.Attachments; + var destinationAttachments = destination.Attachments; + var destinationBones = destination.Bones; + var destinationConstraints = destination.Constraints; + + if (cloneAttachments) { + if (overwrite) { + foreach (var e in sourceAttachments) { + Attachment clonedAttachment = e.Value.GetCopy(cloneMeshesAsLinked); + destinationAttachments[new Skin.SkinEntry(e.Key.SlotIndex, e.Key.Name, clonedAttachment)] = clonedAttachment; + } + } else { + foreach (var e in sourceAttachments) { + if (destinationAttachments.ContainsKey(e.Key)) continue; + Attachment clonedAttachment = e.Value.GetCopy(cloneMeshesAsLinked); + destinationAttachments.Add(new Skin.SkinEntry(e.Key.SlotIndex, e.Key.Name, clonedAttachment), clonedAttachment); + } + } + } else { + if (overwrite) { + foreach (var e in sourceAttachments) + destinationAttachments[e.Key] = e.Value; + } else { + foreach (var e in sourceAttachments) { + if (destinationAttachments.ContainsKey(e.Key)) continue; + destinationAttachments.Add(e.Key, e.Value); + } + } + } + + foreach (BoneData data in source.bones) + if (!destinationBones.Contains(data)) destinationBones.Add(data); + + foreach (ConstraintData data in source.constraints) + if (!destinationConstraints.Contains(data)) destinationConstraints.Add(data); + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs.meta new file mode 100644 index 0000000..5ac1f29 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/SkinUtilities.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f4692b9527684d048862210ba3f9834e +timeCreated: 1563321428 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs new file mode 100644 index 0000000..03f14aa --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs @@ -0,0 +1,91 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; +using System.Collections; + +namespace Spine.Unity.AnimationTools { + public static class TimelineExtensions { + + /// Evaluates the resulting value of a TranslateTimeline at a given time. + /// SkeletonData can be accessed from Skeleton.Data or from SkeletonDataAsset.GetSkeletonData. + /// If no SkeletonData is given, values are computed relative to setup pose instead of local-absolute. + public static Vector2 Evaluate (this TranslateTimeline timeline, float time, SkeletonData skeletonData = null) { + const int PREV_TIME = -3, PREV_X = -2, PREV_Y = -1; + const int X = 1, Y = 2; + + var frames = timeline.frames; + if (time < frames[0]) return Vector2.zero; + + float x, y; + if (time >= frames[frames.Length - TranslateTimeline.ENTRIES]) { // Time is after last frame. + x = frames[frames.Length + PREV_X]; + y = frames[frames.Length + PREV_Y]; + } + else { + // Interpolate between the previous frame and the current frame. + int frame = Animation.BinarySearch(frames, time, TranslateTimeline.ENTRIES); + x = frames[frame + PREV_X]; + y = frames[frame + PREV_Y]; + float frameTime = frames[frame]; + float percent = timeline.GetCurvePercent(frame / TranslateTimeline.ENTRIES - 1, + 1 - (time - frameTime) / (frames[frame + PREV_TIME] - frameTime)); + + x += (frames[frame + X] - x) * percent; + y += (frames[frame + Y] - y) * percent; + } + + Vector2 xy = new Vector2(x, y); + if (skeletonData == null) { + return xy; + } + else { + var boneData = skeletonData.bones.Items[timeline.boneIndex]; + return xy + new Vector2(boneData.x, boneData.y); + } + } + + /// Gets the translate timeline for a given boneIndex. + /// You can get the boneIndex using SkeletonData.FindBoneIndex. + /// The root bone is always boneIndex 0. + /// This will return null if a TranslateTimeline is not found. + public static TranslateTimeline FindTranslateTimelineForBone (this Animation a, int boneIndex) { + foreach (var timeline in a.timelines) { + if (timeline.GetType().IsSubclassOf(typeof(TranslateTimeline))) + continue; + + var translateTimeline = timeline as TranslateTimeline; + if (translateTimeline != null && translateTimeline.boneIndex == boneIndex) + return translateTimeline; + } + return null; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs.meta new file mode 100644 index 0000000..6198f84 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/TimelineExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 07807fefbff25484ba41b1d16911fb0e +timeCreated: 1591974498 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions.meta new file mode 100644 index 0000000..903af3e --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 15ac4befbee15d845ac289de3ab6d3d4 +folderAsset: yes +timeCreated: 1455486167 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs new file mode 100644 index 0000000..644ceed --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs @@ -0,0 +1,108 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections; +using System; + +namespace Spine.Unity { + /// + /// Use this as a condition-blocking yield instruction for Unity Coroutines. + /// The routine will pause until the AnimationState.TrackEntry fires any of the + /// configured events. + ///

+ /// See the Spine Unity Events documentation page + /// and + /// for more information on when track events will be triggered.

+ public class WaitForSpineAnimation : IEnumerator { + + [Flags] + public enum AnimationEventTypes + { + Start = 1, + Interrupt = 2, + End = 4, + Dispose = 8, + Complete = 16 + } + + bool m_WasFired = false; + + public WaitForSpineAnimation (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) { + SafeSubscribe(trackEntry, eventsToWaitFor); + } + + #region Reuse + /// + /// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure. + /// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete. + public WaitForSpineAnimation NowWaitFor (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) { + SafeSubscribe(trackEntry, eventsToWaitFor); + return this; + } + #endregion + + #region IEnumerator + bool IEnumerator.MoveNext () { + if (m_WasFired) { + ((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse + return false; + } + + return true; + } + void IEnumerator.Reset () { m_WasFired = false; } + object IEnumerator.Current { get { return null; } } + #endregion + + protected void SafeSubscribe (Spine.TrackEntry trackEntry, AnimationEventTypes eventsToWaitFor) { + if (trackEntry == null) { + // Break immediately if trackEntry is null. + Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately."); + m_WasFired = true; + } + else { + if ((eventsToWaitFor & AnimationEventTypes.Start) != 0) + trackEntry.Start += HandleComplete; + if ((eventsToWaitFor & AnimationEventTypes.Interrupt) != 0) + trackEntry.Interrupt += HandleComplete; + if ((eventsToWaitFor & AnimationEventTypes.End) != 0) + trackEntry.End += HandleComplete; + if ((eventsToWaitFor & AnimationEventTypes.Dispose) != 0) + trackEntry.Dispose += HandleComplete; + if ((eventsToWaitFor & AnimationEventTypes.Complete) != 0) + trackEntry.Complete += HandleComplete; + } + } + + void HandleComplete (TrackEntry trackEntry) { + m_WasFired = true; + } + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs.meta new file mode 100644 index 0000000..ac946e6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimation.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d9be5adcaf0003849a1d181173c19635 +timeCreated: 1566289729 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs new file mode 100644 index 0000000..39cf16a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs @@ -0,0 +1,62 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections; +using Spine; + +namespace Spine.Unity { + /// + /// Use this as a condition-blocking yield instruction for Unity Coroutines. + /// The routine will pause until the AnimationState.TrackEntry fires its Complete event. + /// It can be configured to trigger on the End event as well to cover interruption. + ///

+ /// See the Spine Unity Events documentation page + /// and + /// for more information on when track events will be triggered.

+ public class WaitForSpineAnimationComplete : WaitForSpineAnimation, IEnumerator { + + public WaitForSpineAnimationComplete (Spine.TrackEntry trackEntry, bool includeEndEvent = false) : + base(trackEntry, + includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete) + { + } + + #region Reuse + /// + /// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure. + /// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete. + public WaitForSpineAnimationComplete NowWaitFor (Spine.TrackEntry trackEntry, bool includeEndEvent = false) { + SafeSubscribe(trackEntry, + includeEndEvent ? (AnimationEventTypes.Complete | AnimationEventTypes.End) : AnimationEventTypes.Complete); + return this; + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs.meta new file mode 100644 index 0000000..0aabc3b --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationComplete.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a807dd9fb79db3545b6c2859a2bbfc0b +timeCreated: 1449704018 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs new file mode 100644 index 0000000..dbafcc6 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs @@ -0,0 +1,59 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections; +using Spine; + +namespace Spine.Unity { + /// + /// Use this as a condition-blocking yield instruction for Unity Coroutines. + /// The routine will pause until the AnimationState.TrackEntry fires its End event. + ///

+ /// See the Spine Unity Events documentation page + /// and + /// for more information on when track events will be triggered.

+ public class WaitForSpineAnimationEnd : WaitForSpineAnimation, IEnumerator { + + public WaitForSpineAnimationEnd (Spine.TrackEntry trackEntry) : + base(trackEntry, AnimationEventTypes.End) + { + } + + #region Reuse + /// + /// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure. + /// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationComplete. + public WaitForSpineAnimationEnd NowWaitFor (Spine.TrackEntry trackEntry) { + SafeSubscribe(trackEntry, AnimationEventTypes.End); + return this; + } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs.meta new file mode 100644 index 0000000..472b1f9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineAnimationEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3c5a5fe930d1ab24da154d76b24c2747 +timeCreated: 1566288961 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs new file mode 100644 index 0000000..1da2bcb --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs @@ -0,0 +1,159 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections; +using Spine; + +namespace Spine.Unity { + /// + /// Use this as a condition-blocking yield instruction for Unity Coroutines. + /// The routine will pause until the AnimationState fires an event matching the given event name or EventData reference. + public class WaitForSpineEvent : IEnumerator { + + Spine.EventData m_TargetEvent; + string m_EventName; + Spine.AnimationState m_AnimationState; + + bool m_WasFired = false; + bool m_unsubscribeAfterFiring = false; + + #region Constructors + void Subscribe (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribe) { + if (state == null) { + Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately."); + m_WasFired = true; + return; + } else if (eventDataReference == null) { + Debug.LogWarning("eventDataReference argument was null. Coroutine will continue immediately."); + m_WasFired = true; + return; + } + + m_AnimationState = state; + m_TargetEvent = eventDataReference; + state.Event += HandleAnimationStateEvent; + + m_unsubscribeAfterFiring = unsubscribe; + + } + + void SubscribeByName (Spine.AnimationState state, string eventName, bool unsubscribe) { + if (state == null) { + Debug.LogWarning("AnimationState argument was null. Coroutine will continue immediately."); + m_WasFired = true; + return; + } else if (string.IsNullOrEmpty(eventName)) { + Debug.LogWarning("eventName argument was null. Coroutine will continue immediately."); + m_WasFired = true; + return; + } + + m_AnimationState = state; + m_EventName = eventName; + state.Event += HandleAnimationStateEventByName; + + m_unsubscribeAfterFiring = unsubscribe; + } + + public WaitForSpineEvent (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) { + Subscribe(state, eventDataReference, unsubscribeAfterFiring); + } + + public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) { + // If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine. + Subscribe(skeletonAnimation.state, eventDataReference, unsubscribeAfterFiring); + } + + public WaitForSpineEvent (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) { + SubscribeByName(state, eventName, unsubscribeAfterFiring); + } + + public WaitForSpineEvent (SkeletonAnimation skeletonAnimation, string eventName, bool unsubscribeAfterFiring = true) { + // If skeletonAnimation is invalid, its state will be null. Subscribe handles null states just fine. + SubscribeByName(skeletonAnimation.state, eventName, unsubscribeAfterFiring); + } + #endregion + + #region Event Handlers + void HandleAnimationStateEventByName (Spine.TrackEntry trackEntry, Spine.Event e) { + m_WasFired |= (e.Data.Name == m_EventName); // Check event name string match. + if (m_WasFired && m_unsubscribeAfterFiring) + m_AnimationState.Event -= HandleAnimationStateEventByName; // Unsubscribe after correct event fires. + } + + void HandleAnimationStateEvent (Spine.TrackEntry trackEntry, Spine.Event e) { + m_WasFired |= (e.Data == m_TargetEvent); // Check event data reference match. + if (m_WasFired && m_unsubscribeAfterFiring) + m_AnimationState.Event -= HandleAnimationStateEvent; // Usubscribe after correct event fires. + } + #endregion + + #region Reuse + /// + /// By default, WaitForSpineEvent will unsubscribe from the event immediately after it fires a correct matching event. + /// If you want to reuse this WaitForSpineEvent instance on the same event, you can set this to false. + public bool WillUnsubscribeAfterFiring { get { return m_unsubscribeAfterFiring; } set { m_unsubscribeAfterFiring = value; } } + + public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, Spine.EventData eventDataReference, bool unsubscribeAfterFiring = true) { + ((IEnumerator)this).Reset(); + Clear(state); + Subscribe(state, eventDataReference, unsubscribeAfterFiring); + + return this; + } + + public WaitForSpineEvent NowWaitFor (Spine.AnimationState state, string eventName, bool unsubscribeAfterFiring = true) { + ((IEnumerator)this).Reset(); + Clear(state); + SubscribeByName(state, eventName, unsubscribeAfterFiring); + + return this; + } + + void Clear (Spine.AnimationState state) { + state.Event -= HandleAnimationStateEvent; + state.Event -= HandleAnimationStateEventByName; + } + #endregion + + #region IEnumerator + bool IEnumerator.MoveNext () { + if (m_WasFired) { + ((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse + return false; + } + + return true; + } + void IEnumerator.Reset () { m_WasFired = false; } + object IEnumerator.Current { get { return null; } } + #endregion + } +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs.meta new file mode 100644 index 0000000..72bbef7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineEvent.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fc166d883db083e469872998172f2d38 +timeCreated: 1449701857 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs new file mode 100644 index 0000000..dc62d43 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs @@ -0,0 +1,85 @@ +/****************************************************************************** + * Spine Runtimes License Agreement + * Last updated January 1, 2020. Replaces all prior versions. + * + * Copyright (c) 2013-2020, Esoteric Software LLC + * + * Integration of the Spine Runtimes into software or otherwise creating + * derivative works of the Spine Runtimes is permitted under the terms and + * conditions of Section 2 of the Spine Editor License Agreement: + * http://esotericsoftware.com/spine-editor-license + * + * Otherwise, it is permitted to integrate the Spine Runtimes into software + * or otherwise create derivative works of the Spine Runtimes (collectively, + * "Products"), provided that each user of the Products must obtain their own + * Spine Editor license and redistribution of the Products in any form must + * include this license and copyright notice. + * + * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, + * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *****************************************************************************/ + +using UnityEngine; +using System.Collections; +using Spine; + +namespace Spine.Unity { + /// + /// Use this as a condition-blocking yield instruction for Unity Coroutines. + /// The routine will pause until the AnimationState.TrackEntry fires its End event. + public class WaitForSpineTrackEntryEnd : IEnumerator { + + bool m_WasFired = false; + + public WaitForSpineTrackEntryEnd (Spine.TrackEntry trackEntry) { + SafeSubscribe(trackEntry); + } + + void HandleEnd (TrackEntry trackEntry) { + m_WasFired = true; + } + + void SafeSubscribe (Spine.TrackEntry trackEntry) { + if (trackEntry == null) { + // Break immediately if trackEntry is null. + Debug.LogWarning("TrackEntry was null. Coroutine will continue immediately."); + m_WasFired = true; + } else { + trackEntry.End += HandleEnd; + } + } + + #region Reuse + /// + /// One optimization high-frequency YieldInstruction returns is to cache instances to minimize GC pressure. + /// Use NowWaitFor to reuse the same instance of WaitForSpineAnimationEnd. + public WaitForSpineTrackEntryEnd NowWaitFor (Spine.TrackEntry trackEntry) { + SafeSubscribe(trackEntry); + return this; + } + #endregion + + #region IEnumerator + bool IEnumerator.MoveNext () { + if (m_WasFired) { + ((IEnumerator)this).Reset(); // auto-reset for YieldInstruction reuse + return false; + } + + return true; + } + void IEnumerator.Reset () { m_WasFired = false; } + object IEnumerator.Current { get { return null; } } + #endregion + + } + +} diff --git a/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs.meta b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs.meta new file mode 100644 index 0000000..afd6031 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/Runtime/spine-unity/Utility/YieldInstructions/WaitForSpineTrackEntryEnd.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8036c6c2897d2764db92f632d2aef568 +timeCreated: 1480672707 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/ver@spine-unity-3.8-2020-03-02.txt b/Assets/CrazyZoo/Plugins/Spine/ver@spine-unity-3.8-2020-03-02.txt new file mode 100644 index 0000000..e69de29 diff --git a/Assets/CrazyZoo/Plugins/Spine/ver@spine-unity-3.8-2020-03-02.txt.meta b/Assets/CrazyZoo/Plugins/Spine/ver@spine-unity-3.8-2020-03-02.txt.meta new file mode 100644 index 0000000..bdc384a --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/ver@spine-unity-3.8-2020-03-02.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b51a72e07bc6de44cbb03c37cc7bfbf0 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Spine/version.txt b/Assets/CrazyZoo/Plugins/Spine/version.txt new file mode 100644 index 0000000..3758191 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/version.txt @@ -0,0 +1,2 @@ +This Spine-Unity runtime works with data exported from Spine Editor version: 3.8.xx +Package version: spine-unity-3.8-2020-03-02.unitypackage diff --git a/Assets/CrazyZoo/Plugins/Spine/version.txt.meta b/Assets/CrazyZoo/Plugins/Spine/version.txt.meta new file mode 100644 index 0000000..d34c5b7 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Spine/version.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 80c06a67282e71043a4b1fad3e0c5654 +timeCreated: 1485965987 +licenseType: Free +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel.meta b/Assets/CrazyZoo/Plugins/Uni-Excel.meta new file mode 100644 index 0000000..3ad4be9 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 82ffb51e9b6c2bf49967dd12415ef66d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf b/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf new file mode 100644 index 0000000..0fcd929 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf.meta new file mode 100644 index 0000000..c0b6744 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Document.pdf.meta @@ -0,0 +1,6 @@ +fileFormatVersion: 2 +guid: 963c301078b38014282227dd6ff7e6f9 +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins.meta new file mode 100644 index 0000000..96707be --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ee40b263eb0b44a459c0531d715b2361 +folderAsset: yes +timeCreated: 1511317733 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll new file mode 100644 index 0000000..06c249b Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll.meta new file mode 100644 index 0000000..4524dae --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/Excel.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: f2ee9e045e5cdaa43aca7b6d7a548396 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll new file mode 100644 index 0000000..c6407d7 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll.meta new file mode 100644 index 0000000..270a117 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OOXML.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: 51a6137f7de387b438154afe2afa09bc +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll new file mode 100644 index 0000000..447c9cc Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll.meta new file mode 100644 index 0000000..ba7302c --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXml4Net.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: 9ba3b74950c6c2e4d9054c72773d94f9 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll new file mode 100644 index 0000000..dacbb28 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll.meta new file mode 100644 index 0000000..6141660 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.OpenXmlFormats.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: 485abd1a5b3ac86499e7fe2cb736508c +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll new file mode 100644 index 0000000..f412d2d Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll.meta new file mode 100644 index 0000000..fbd8f50 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/NPOI.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: 30bd36947cde7544fb874fe30b432d42 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll new file mode 100644 index 0000000..a386979 Binary files /dev/null and b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll differ diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll.meta new file mode 100644 index 0000000..2df3189 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Plugins/PersianFix.dll.meta @@ -0,0 +1,45 @@ +fileFormatVersion: 2 +guid: 4f605d0379db018439d439d694e553b2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts.meta new file mode 100644 index 0000000..b2715ed --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: eca50efccf99915479d4d42f425f3997 +folderAsset: yes +timeCreated: 1511317733 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs new file mode 100644 index 0000000..2fb9365 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs @@ -0,0 +1,181 @@ +#if UNITY_EDITOR +using UnityEngine; +using System.Collections.Generic; +using NPOI.HSSF.UserModel; +using NPOI.SS.UserModel; +using NPOI.HSSF.Util; +using System.IO; + +public class MyExcel : MonoBehaviour +{ + private string MySheetName = "Sheet_Test"; + + public List MyCellArray; + public List MyCellArray02; + + public List MyString; + + private bool ReadExcelEnable_NPOI = false; + private bool ReadExcelEnable_ExcelDataReader = false; + + void OnGUI() + { + GUIStyle style = new GUIStyle(); + + GUI.Label(new Rect(10, 10, 100, 30), "Sheet Name:"); + MySheetName = GUI.TextField(new Rect(90, 10, 200, 30), MySheetName, 25); + + style.richText = true; + + FileStream MyAddress = new FileStream(Application.dataPath + "/My First Excel.xls", FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.ReadWrite); + + if (GUI.Button(new Rect(300, 10, 200, 30), "Create Excel Files With " + "NPOI")) + { + HSSFWorkbook MyWorkbook = new HSSFWorkbook(); + + HSSFSheet Sheet01 = (HSSFSheet)MyWorkbook.CreateSheet(MySheetName); + + for (int i = 0; i < 5; i++) + { + HSSFRow Row = (HSSFRow)Sheet01.CreateRow((short)i); + + HSSFCell cell = (HSSFCell)Row.CreateCell((short)0); + + cell.SetCellValue(MyCellArray[i]); + + if (i < MyCellArray02.Count) + { + HSSFCell cell02 = (HSSFCell)Row.CreateCell((short)1); + + cell02.SetCellValue(MyCellArray02[i]); + } + else + { + HSSFCell cell02 = (HSSFCell)Row.CreateCell((short)1); + + cell02.SetCellValue(""); + } + + Row.RowStyle = MyWorkbook.CreateCellStyle(); + + Row.RowStyle.BorderBottom = BorderStyle.Double; + + cell.CellStyle = MyWorkbook.CreateCellStyle(); + + cell.CellStyle.BorderRight = BorderStyle.Thin; + cell.CellStyle.BorderBottom = BorderStyle.Dashed; + cell.CellStyle.BottomBorderColor = HSSFColor.Red.Index; + cell.CellStyle.FillPattern = FillPattern.SolidForeground; + cell.CellStyle.FillForegroundColor = HSSFColor.Red.Index; + //HSSFFont MyFont = (HSSFFont)MyWorkbook.CreateFont(); + + //MyFont.FontName = "Tahoma"; + //MyFont.FontHeightInPoints = 14; + //MyFont.Color = HSSFColor.Gold.Index; + //MyFont.Boldweight = (short)FontBoldWeight.Bold; + + //cell.CellStyle.SetFont(MyFont); + } + + MyWorkbook.Write(MyAddress); + + MyWorkbook.Close(); + } + + + //if (GUI.Button(new Rect(60, 120, 200, 30), "Reading Excel Files With " + "NPOI")) + //{ + + // ReadExcelEnable_NPOI = true; + + // ReadExcelEnable_ExcelDataReader = false; + + // MyString.Clear(); + + //} + + //if (ReadExcelEnable_NPOI == true) + //{ + + // HSSFWorkbook MyBook; + + // using (FileStream MyAddress_Read = new FileStream(Application.dataPath + "/My First Excel.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + // { + // MyBook = new HSSFWorkbook(MyAddress_Read); + // } + + // ISheet Sheet_Read = MyBook.GetSheet(MySheetName); + + // for (int row = 0; row <= Sheet_Read.LastRowNum; row++) + // { + + // IRow Row_Read = Sheet_Read.GetRow(row); + + // for (int cells = 0; cells < Row_Read.LastCellNum; cells++) + // { + + // GUI.Label(new Rect(400 + cells * 200, 100 + row * 40, 200, 20),Row_Read.GetCell(cells).ToString()); + + // //Arabic And Persian Support + // //GUI.Label(new Rect(400 + cells * 200,100+ row * 40, 200, 20),ArabicFixer.Fix(Row_Read.GetCell(cells).ToString())); + // } + + // } + //} + + //if (GUI.Button(new Rect(10, 160, 300, 30), "Reading Excel Files With " + "ExcelDataReader")) + //{ + + // ReadExcelEnable_ExcelDataReader = true; + + // ReadExcelEnable_NPOI = false; + + // MyString.Clear(); + + //} + + //if (ReadExcelEnable_ExcelDataReader == true) + //{ + + // IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(MyAddress); + + // DataSet Result = excelReader.AsDataSet(); + + // excelReader.IsFirstRowAsColumnNames = true; + + // int NumberOfRows = Result.Tables[0].Rows.Count; + + // int NumberOfCols = Result.Tables[0].Columns.Count; + + // for (int i = 0; i < NumberOfRows; i++) + // { + + // for (int j = 0; j < NumberOfCols; j++) + // { + + // if (i == NumberOfRows - 1 && j == NumberOfCols - 1) + // { + + // ReadExcelEnable_ExcelDataReader = false; + + // } + + // MyString.Add(Result.Tables[0].Rows[i][j].ToString()); + + // } + // } + //} + + //for (int b = 0; b < MyString.Count; b++) + //{ + + // GUI.Label(new Rect(400,100+ 20 * b, 200, 20),MyString[b]); + + // //Arabic And Persian Support + // //GUI.Label(new Rect(400, 100 + 20 * b, 200, 20), ArabicFixer.Fix(MyString[b])); + //} + } +} + +#endif \ No newline at end of file diff --git a/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs.meta b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs.meta new file mode 100644 index 0000000..0c884c3 --- /dev/null +++ b/Assets/CrazyZoo/Plugins/Uni-Excel/Scripts/MyExcel.cs.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6bd3778c90c456b488166ab5fbafc01e +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources.meta b/Assets/CrazyZoo/Resources.meta new file mode 100644 index 0000000..4054adf --- /dev/null +++ b/Assets/CrazyZoo/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 27011cabf25c32745964eb725c0f6d25 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI.meta b/Assets/CrazyZoo/Resources/FGUI.meta new file mode 100644 index 0000000..15aca48 --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 36fb98fc19f7b6741b04d8638b9365d9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png new file mode 100644 index 0000000..1ce6d60 Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png differ diff --git a/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png.meta b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png.meta new file mode 100644 index 0000000..4fca77f --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_atlas0.png.meta @@ -0,0 +1,135 @@ +fileFormatVersion: 2 +guid: 9205df25476e66148a8ab653a463ac0b +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMasterTextureLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes new file mode 100644 index 0000000..3ac070c Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes differ diff --git a/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes.meta b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes.meta new file mode 100644 index 0000000..451319f --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/A001_bigImg_fui.bytes.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5f72abc5ee04e45408487734b81c881f +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png new file mode 100644 index 0000000..d1ee23d Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png differ diff --git a/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png.meta b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png.meta new file mode 100644 index 0000000..8ed2249 --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_atlas0.png.meta @@ -0,0 +1,135 @@ +fileFormatVersion: 2 +guid: 17f13eb564aaae24a84c35d663dcdfa8 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMasterTextureLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes new file mode 100644 index 0000000..d752d6d Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes differ diff --git a/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes.meta b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes.meta new file mode 100644 index 0000000..275ac4e --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/CS608_loading_fui.bytes.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 173fa4ec201eb244bbf037ba02392665 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png b/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png new file mode 100644 index 0000000..d1ee23d Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png differ diff --git a/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png.meta b/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png.meta new file mode 100644 index 0000000..57a1956 --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/SLoading_atlas0.png.meta @@ -0,0 +1,135 @@ +fileFormatVersion: 2 +guid: 3292babfe30dfd44c8e66102a6d6430c +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMasterTextureLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes b/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes new file mode 100644 index 0000000..c576ee8 Binary files /dev/null and b/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes differ diff --git a/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes.meta b/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes.meta new file mode 100644 index 0000000..a341650 --- /dev/null +++ b/Assets/CrazyZoo/Resources/FGUI/SLoading_fui.bytes.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 832dccea66f24d042984c00b4205e8f5 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/bg.jpg b/Assets/CrazyZoo/Resources/bg.jpg new file mode 100644 index 0000000..a194155 Binary files /dev/null and b/Assets/CrazyZoo/Resources/bg.jpg differ diff --git a/Assets/CrazyZoo/Resources/bg.jpg.meta b/Assets/CrazyZoo/Resources/bg.jpg.meta new file mode 100644 index 0000000..0f3e270 --- /dev/null +++ b/Assets/CrazyZoo/Resources/bg.jpg.meta @@ -0,0 +1,135 @@ +fileFormatVersion: 2 +guid: 0e7c6df8e2fe8d4499924bda59ad7bd9 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMasterTextureLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Resources/yxjm_bg1.png b/Assets/CrazyZoo/Resources/yxjm_bg1.png new file mode 100644 index 0000000..1797b52 Binary files /dev/null and b/Assets/CrazyZoo/Resources/yxjm_bg1.png differ diff --git a/Assets/CrazyZoo/Resources/yxjm_bg1.png.meta b/Assets/CrazyZoo/Resources/yxjm_bg1.png.meta new file mode 100644 index 0000000..3be8a42 --- /dev/null +++ b/Assets/CrazyZoo/Resources/yxjm_bg1.png.meta @@ -0,0 +1,135 @@ +fileFormatVersion: 2 +guid: b5a8629c0738a9447b82b9d74e01a3a5 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 12 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMasterTextureLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 0 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Server + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime.meta b/Assets/CrazyZoo/Runtime.meta new file mode 100644 index 0000000..5d303db --- /dev/null +++ b/Assets/CrazyZoo/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0044db0a27436e54588fe823c471de83 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core.meta b/Assets/CrazyZoo/Runtime/Core.meta new file mode 100644 index 0000000..a4a691b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28085669128450d49829ad9c09bdb069 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/App.cs b/Assets/CrazyZoo/Runtime/Core/App.cs new file mode 100644 index 0000000..e667dee --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/App.cs @@ -0,0 +1,32 @@ +namespace ScrewsMaster +{ + public static class App + { + private static SApplication _sCurrSApplication = null; + + public static void InitApplication(SApplication sApplication) + { + _sCurrSApplication = sApplication; + _sCurrSApplication.Init(); + _sCurrSApplication.Enable(); + } + + private static float LoadingProgressDelayTime = 0f; + + public static void DisplayLoadingUI() + { + AppDispatcher.Instance.Dispatch(AppMsg.UI_DisplayLoadingUI); + } + + public static void HideLoadingUI(bool isDelay = false) + { + if (!isDelay) + { + AppDispatcher.Instance.Dispatch(AppMsg.UI_HideLoadingUI); + return; + } + + TimerHelper.mEasy.AddTimer(0.5f, () => { AppDispatcher.Instance.Dispatch(AppMsg.UI_HideLoadingUI); }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/App.cs.meta b/Assets/CrazyZoo/Runtime/Core/App.cs.meta new file mode 100644 index 0000000..55c9d6e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/App.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58141605cb271ab488578de8509d91e7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Async.meta b/Assets/CrazyZoo/Runtime/Core/Async.meta new file mode 100644 index 0000000..edc4062 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f45f78800937eda4280b97dc62745da6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs b/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs new file mode 100644 index 0000000..5009cca --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs @@ -0,0 +1,52 @@ +namespace ScrewsMaster +{ + public class AsyncDealData + { + public delegate void DealMethod(); + + + private float _currentTime; + + + public float DelayTime = 1f; + + + public DealMethod dealMethod; + + + public int RepeatCount = 1; + + + public bool IsComplete => RepeatCount == 0; + + + public void PassTime(float time) + { + _currentTime += time; + if (!(_currentTime >= DelayTime)) + { + return; + } + + _currentTime -= DelayTime; + Run(); + } + + + private void Run() + { + if (RepeatCount == -1) + { + dealMethod?.Invoke(); + } + else + { + if (RepeatCount > 0) + { + dealMethod?.Invoke(); + RepeatCount--; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs.meta b/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs.meta new file mode 100644 index 0000000..a58e285 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/AsyncDealData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4e51ff91679a44d1b1efe3438d508e74 +timeCreated: 1682577036 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs b/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs new file mode 100644 index 0000000..1ff1a46 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs @@ -0,0 +1,92 @@ +namespace ScrewsMaster +{ + using System; + using UnityEngine; + using System.Collections.Generic; + + internal class AsyncKitUnityBehaviour : SingletonUnity + { + private readonly Dictionary _asyncDataDict = new Dictionary(); + + + private readonly Dictionary _updateActionDict = new Dictionary(); + + private readonly List _keyClean = new List(); + + private void Update() + { + foreach (var temp in _asyncDataDict.Values) + { + temp.PassTime(Time.deltaTime); + } + + try + { + foreach (var temp in _updateActionDict.Values) + { + temp?.dealMethod?.Invoke(); + } + } + catch (Exception) + { + } + + + ClearFinished(); + + + ClearUpdateActionFinished(); + } + + + private void ClearFinished() + { + _keyClean.Clear(); + foreach (var dealData in _asyncDataDict) + { + if (dealData.Value.IsComplete) + { + _keyClean.Add(dealData.Key); + } + } + + foreach (var key in _keyClean) + { + _asyncDataDict.Remove(key); + } + } + + + public void AddAsyncData(string key, AsyncDealData asyncDealData) + { + RemoveAsyncData(key); + _asyncDataDict.Add(key, asyncDealData); + } + + + public void RemoveAsyncData(string key) + { + if (_asyncDataDict.ContainsKey(key)) + { + _asyncDataDict.Remove(key); + } + } + + public void ClearUpdateActionFinished() + { + _keyClean.Clear(); + foreach (var dealData in _updateActionDict) + { + if (dealData.Value.IsComplete) + { + _keyClean.Add(dealData.Key); + } + } + + foreach (var key in _keyClean) + { + _updateActionDict.Remove(key); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs.meta b/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs.meta new file mode 100644 index 0000000..fc3a678 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/AsyncKitUnityBehaviour.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 984d18c5a4974e729d72276896426930 +timeCreated: 1682577036 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs b/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs new file mode 100644 index 0000000..39762c2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs @@ -0,0 +1,61 @@ +namespace ScrewsMaster +{ + using UnityEngine; + using System.Collections; + + public static class CrazyAsyKit + { + private static AsyncKitUnityBehaviour sAsyncKitUnityBehaviour; + + + private static readonly object SynClock = new object(); + + private static AsyncKitUnityBehaviour mAsyncKitUnityBehaviour + { + get + { + if (sAsyncKitUnityBehaviour != null) + { + return sAsyncKitUnityBehaviour; + } + + lock (SynClock) + { + if (sAsyncKitUnityBehaviour != null) + { + return sAsyncKitUnityBehaviour; + } + + + sAsyncKitUnityBehaviour = AsyncKitUnityBehaviour.Instance; + if (sAsyncKitUnityBehaviour != null) + { + sAsyncKitUnityBehaviour.name = "[ CrazyAsyKit ]"; + } + } + + return sAsyncKitUnityBehaviour; + } + } + + public static Coroutine StartCoroutine(IEnumerator enumerator) + { + return mAsyncKitUnityBehaviour.StartCoroutine(enumerator); + } + + public static void StartAction(string key, AsyncDealData.DealMethod method, float delayTime, int repeat = 1) + { + var temp = new AsyncDealData { dealMethod = method, DelayTime = delayTime, RepeatCount = repeat }; + mAsyncKitUnityBehaviour.AddAsyncData(key, temp); + } + + public static void StopCoroutine(Coroutine enumerator) + { + mAsyncKitUnityBehaviour.StopCoroutine(enumerator); + } + public static void StopAction(string key) + { + mAsyncKitUnityBehaviour.RemoveAsyncData(key); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs.meta new file mode 100644 index 0000000..f5c6042 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Async/CrazyAsyKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 93122ca4429e463aba586a345558ed8e +timeCreated: 1682577036 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/BaseScene.cs b/Assets/CrazyZoo/Runtime/Core/BaseScene.cs new file mode 100644 index 0000000..2a2bad1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/BaseScene.cs @@ -0,0 +1,29 @@ +namespace ScrewsMaster +{ + public abstract class BaseScene + { + public abstract int SceneIdx { get; } + + public void Enter() + { + App.DisplayLoadingUI(); + OnEnter(); + } + + public void Leave() + { + OnLeave(); + } + + public void SwitchSceneComplete(object param) + { + OnSwitchSceneComplete(param); + } + + protected abstract void OnEnter(); + protected abstract void OnLeave(); + protected abstract void OnSwitchSceneComplete(object param); + + public abstract void Dispose(); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/BaseScene.cs.meta b/Assets/CrazyZoo/Runtime/Core/BaseScene.cs.meta new file mode 100644 index 0000000..2664839 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/BaseScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36208f1ae07fbee498389575991236b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs b/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs new file mode 100644 index 0000000..ff77928 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs @@ -0,0 +1,29 @@ +namespace ScrewsMaster +{ + public abstract class BaseSystem + { + public virtual void Init() + { + } + + public virtual void InitLate() + { + } + + public virtual void Dispose() + { + } + + public virtual void Update() + { + } + + public virtual void LateUpdate() + { + } + + public virtual void FixedUpdate() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs.meta b/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs.meta new file mode 100644 index 0000000..4dc4c2d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/BaseSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: db46851f313c4809855238569ed6cfac +timeCreated: 1692256359 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs b/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs new file mode 100644 index 0000000..c6e11f2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs @@ -0,0 +1,30 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class CrazyZooBoot : MonoBehaviour + { + public void Awake() + { + OnLauncher(); + var reqData = new RespLoginFunnelData + { + type = "bootstrap", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + +#if UNITY_EDITOR + // PlayerPrefs.DeleteAll(); +#endif + } + + public static void OnLauncher() + { + AppObjConst.FrameGo = new GameObject($"{AppObjConst.FrameGoName}"); + AppObjConst.FrameGo.AddComponent(); + DontDestroyOnLoad(AppObjConst.FrameGo); + App.InitApplication(SuperApplication.Instance); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs.meta b/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs.meta new file mode 100644 index 0000000..ef9f89e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CrazyZooBoot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 958cbcd088fb3bc4c826840c9648b64e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs b/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs new file mode 100644 index 0000000..7cf6b06 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs @@ -0,0 +1,7 @@ +namespace ScrewsMaster +{ + public class CrazyZooCore : SingletonUnity + { + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs.meta b/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs.meta new file mode 100644 index 0000000..b1643cc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CrazyZooCore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41b35f98275b2ce40ac58d230dba9d80 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs b/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs new file mode 100644 index 0000000..4e53513 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using ScrewsMaster; +using Spine.Unity; +using Unity.VisualScripting; +using UnityEngine; + +public class CreatSheepCard : MonoBehaviour +{ + + public static CreatSheepCard instance; + private List img_list; + + public Camera orthoCamera; // 这个变量应该被设置为您想要调整大小的正交相机 + + + private void Awake() + { + instance = this; + orthoCamera = GameObject.Find("Camera1").GetComponent(); + + orthoCamera.orthographicSize = (float)Math.Round(28.125f / ((float)Screen.width / Screen.height), 4); + + } + +} diff --git a/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs.meta b/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs.meta new file mode 100644 index 0000000..afc565d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/CreatSheepCard.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c892366728def834886c9f73f77e88f9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define.meta b/Assets/CrazyZoo/Runtime/Core/Define.meta new file mode 100644 index 0000000..385aa8f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: be8781ff9378e5345a9f6188e990a359 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant.meta new file mode 100644 index 0000000..0e03340 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e7146600e94b62843b388e234c8ce824 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs new file mode 100644 index 0000000..a6cf79c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs @@ -0,0 +1,8 @@ +namespace ScrewsMaster +{ + public static class AnimConst + { + public const float AnimFrameRate = 30; + public const float SecondRateUnit = 1 / AnimFrameRate; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs.meta new file mode 100644 index 0000000..b520395 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AnimConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db177b3a2887ce0498712919fed1ee4f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs new file mode 100644 index 0000000..da9415b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs @@ -0,0 +1,49 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public static class AppConst + { + #region Field + + public static bool IsEnabledEngineLog = true; + + public const LogType EnabledFilterLogType = + LogType.Log | LogType.Warning | LogType.Error | LogType.Assert | + LogType.Exception; + + public const bool IsRunInBG = true; + public const int SleepTimeoutMode = SleepTimeout.NeverSleep; + public const int AntiAliasing = 0; + public const int HighFrameRate = 120; + public const int LowFrameRate = 60; + public const float HDHighViewScale = 1f; + public const float HDLowViewScale = 0.9f; + public const float PixelsPerUnit = 100f; + + public static Vector2Int StandardResolution = new Vector2Int(1080, 1920); + + public static Vector2Int UIResolution = new Vector2Int(1080, 1920); + + public static bool UseInternalSetting = true; + + public static bool IsMultiLangue = true; + + public static string CurrMultiLangue = "en"; + + public static string DefaultLangue = "en"; + + public static string InternalLangue = "en"; + + public static List CtrlDisableList = new List(); + + #endregion + + public static bool isPt() + { + if (CurrMultiLangue == "pt") return true; + return false; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs.meta new file mode 100644 index 0000000..9d6200b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e2daa6b68221ec4f8e0b643de38afd1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs new file mode 100644 index 0000000..3a7e7ab --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs @@ -0,0 +1,38 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class AppObjConst + { + public const string FrameGoName = "[ Jarvis ]"; + public static GameObject FrameGo; + + public const string LauncherGoName = "[Launcher]"; + + public const string EngineEventSystemGoName = "[EngineEventSystem]"; + public static GameObject EngineEventSystemGo; + + public const string ApplicationGoName = "[ Application ]"; + public static GameObject ApplicationGo; + + public const string EngineSingletonGoName = "[EngineSingleton]"; + public static GameObject EngineSingletonGo; + public const string MonoManagerGoName = "[MonoManager]"; + public static GameObject MonoManagerGo; + public const string DispatcherGoName = "[Dispatcher]"; + public static GameObject DispatcherGo; + public const string LoaderGoName = "[Loader]"; + public static GameObject LoaderGo; + + public const string CameraGoName = "[Camera]"; + public static GameObject CameraGo; + + public const string UIGoName = "[UI]"; + public static GameObject UIGo; + public const string UICacheGoName = "[UICache]"; + public static GameObject UICacheGo; + + public const string DOTweenGoName = "[DOTween]"; + public const string SuperInvokeGoName = "[SuperInvoke]"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs.meta new file mode 100644 index 0000000..8698abb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AppObjConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce9826ccd786f9e46a1fb245b9fe4a04 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs new file mode 100644 index 0000000..fcb87db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs @@ -0,0 +1,22 @@ +namespace ScrewsMaster +{ + public static class AudioConst + { + public const string UIButtonDefault = "ui_ButtonDefault"; + public const string DailyBonusCollect = "dailyBonus_collect"; + public const string CoinFly = "coinfly"; + public const string MainBg = "hall_bgm"; + public const string PlayingBg = "twist_gamebgm"; + public const string dissolve = "dissolve"; + public const string fellshort = "fellshort"; + public const string Victoriously = "Victoriously"; + public const string MakeupDone = "makupdone"; + public const string Defeat = "Defeat"; + public const string Victory = "Victory"; + public const string Bonus = "Bonus"; + public const string SwitchBox = "SwitchBox"; + public const string FlyToCacheKong = "FlyToCacheKong"; + public const string PlayPrizeWheelAnim = "PlayPrizeWheelAnim"; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs.meta new file mode 100644 index 0000000..e572543 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/AudioConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbb65f81bcb66ff48abc55f1c1150765 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs new file mode 100644 index 0000000..497b757 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs @@ -0,0 +1,17 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class CameraConst + { + public const int MainDepth = 0; + public const int UICameraDepth = 10; + + public const int MainCameraPosValue = 100; + public const int MainCameraZPos = 0; + public const int UICameraPosValue = 10000; + + public static Vector3 MainCameraPos = new Vector3(MainCameraPosValue, MainCameraPosValue, MainCameraZPos); + public static Vector3 UICameraPos = new Vector3(UICameraPosValue, UICameraPosValue, MainCameraZPos); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs.meta new file mode 100644 index 0000000..988e50b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/CameraConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2555d38a702f494ca13aaf957846be9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs new file mode 100644 index 0000000..97f4c0e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class LayerMaskConst + { + public const string Default_Name = "Default"; + public const string UI_Name = "UI"; + + public readonly static int Default = LayerMask.NameToLayer(Default_Name); + public readonly static int UI = LayerMask.NameToLayer(UI_Name); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs.meta new file mode 100644 index 0000000..36fd0eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/LayerMaskConst.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8f53446f031c27d4eae9f0ff7d3e4565 +timeCreated: 1530670154 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs new file mode 100644 index 0000000..efbbaf1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs @@ -0,0 +1,10 @@ +namespace ScrewsMaster +{ + public static class PrefsConst + { + public const bool BoolDefault = false; + public const int IntDefault = 0; + public const int IntTrue = 1; + public const int IntFalse = 2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs.meta new file mode 100644 index 0000000..db19b03 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6cb940cabfde0ad4c8a849ca893d686c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs new file mode 100644 index 0000000..11d563f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs @@ -0,0 +1,21 @@ +namespace ScrewsMaster +{ + public static class PrefsKeyConst + { + public const string Application_isHDMode = "Application_isHDMode"; + public const string Application_isHFRMode = "Application_isHFRMode"; + public const string UIMgr_switchLanguage = "UIMgr_switchLanguage"; + public const string AudioMgr_isOpenBGM = "AudioMgr_isOpenBGM"; + public const string AudioMgr_isOpenEffect = "AudioMgr_isOpenEffect"; + public const string App_isNewInstall = "App_isNewInstall"; + public const string JarvisToken = "JarvisToken"; + public const string C_ThroughMaxToday = "C_ThroughMaxToday"; + public const string C_ThroughPop = "C_ThroughPop"; + public const string C_ThroughOnline = "C_ThroughOnline"; + + public const string C_ThroughHide = "C_ThroughHide"; + + public const string C_ThroughFly = "C_ThroughFly"; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs.meta new file mode 100644 index 0000000..c36ddaf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/PrefsKeyConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bec1a938462feda4eba6b162b9a387e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs new file mode 100644 index 0000000..ab1ec43 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class ScreenConst + { + public static Vector2 StandardResolution = new(AppConst.StandardResolution.x, AppConst.StandardResolution.y); + public static float StandardWidth => AppConst.StandardResolution.x; + public static float StandardHeight => AppConst.StandardResolution.y; + public static Vector2 RawResolution = new(Screen.width, Screen.height); + public static Vector2 CurrResolution = new(Screen.width, Screen.height); + public static float OrthographicSize_1280H = StandardHeight / 2 / AppConst.PixelsPerUnit; + public static float StandardAspectRatio = StandardHeight / StandardWidth; + public static float CurrAspectRatio = (float)Screen.height / Screen.width; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs.meta new file mode 100644 index 0000000..70be99b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/ScreenConst.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 76e7d3de03bd12a44b19e935ea71697a +timeCreated: 1534935298 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs new file mode 100644 index 0000000..9b6973b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs @@ -0,0 +1,41 @@ +namespace ScrewsMaster +{ + public static class UILayerConst + { + public const string Background = "Background"; + public const string Bottom = "Bottom"; + + public const string Normal = "Normal"; + public const string Top = "Top"; + + public const string FullScreen = "FullScreen"; + public const string Popup = "Popup"; + + public const string Highest = "Highest"; + public const string Animation = "Animation"; + public const string Tips = "Tips"; + + public const string Loading = "Loading"; + public const string System = "System"; + public const string NetworkError = "NetworkError"; + + public static readonly string[] AllUILayer = { + Background, + Bottom, + + Normal, + Top, + + FullScreen, + Popup, + + Highest, + Animation, + Tips, + + Loading, + System, + NetworkError + }; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs.meta new file mode 100644 index 0000000..2e27a28 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/UILayerConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a1cfef99d74aac943a6872498ec8fb4f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs new file mode 100644 index 0000000..11aa13e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs @@ -0,0 +1,11 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class VectorConst + { + public static Vector3 One = Vector3.one; + public static Vector3 PPUOne = One * AppConst.PixelsPerUnit; + public static Vector3 Half = new(0.5f, 0.5f, 0.5f); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs.meta new file mode 100644 index 0000000..c0a7933 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/VectorConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae89e346ddf1a584382a1deb4b78193a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs b/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs new file mode 100644 index 0000000..73d4cae --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class YieldConst + { + public const float Time10ms = 0.01f; + public const float Time100ms = 0.1f; + + public static WaitForEndOfFrame WaitForEndOfFrame = new WaitForEndOfFrame(); + public static WaitForSeconds WaitFor100ms = new WaitForSeconds(Time100ms); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs.meta new file mode 100644 index 0000000..604c270 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Constant/YieldConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6248774d8e1b69d46a89ad1ea46081ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message.meta b/Assets/CrazyZoo/Runtime/Core/Define/Message.meta new file mode 100644 index 0000000..d721a07 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f14f42c47ff29474bb4170a49c3bc8c1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs b/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs new file mode 100644 index 0000000..c7587ee --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs @@ -0,0 +1,12 @@ +namespace ScrewsMaster +{ + public static partial class CtrlMsg + { + public const string NAME = "CtrlMsg"; + public const uint BASE = 0; + private static uint Cursor_BASE = BASE; + public static readonly uint Login_Succeed = ++Cursor_BASE; + public static readonly uint Game_StartReady = ++Cursor_BASE; + public static readonly uint Game_Start = ++Cursor_BASE; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs.meta new file mode 100644 index 0000000..2b541db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/CtrlMsg_Base_0-9999.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19bfc133c0819ad4486cceca51c8a2e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs b/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs new file mode 100644 index 0000000..a7e1f63 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs @@ -0,0 +1,10 @@ +namespace ScrewsMaster +{ + public static partial class GameMsg + { + public const string NAME = "GameMsg"; + public const uint BASE = 0; + private static uint Cursor_BASE = BASE; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs.meta new file mode 100644 index 0000000..dc714bc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/GameMsg_Base_0-9999.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7d7b577419d940f468e1a95a9afb1dd9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs b/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs new file mode 100644 index 0000000..58d6f95 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs @@ -0,0 +1,9 @@ +namespace ScrewsMaster +{ + public static partial class UICtrlMsg + { + public const string NAME = "UICtrlMsg"; + public const uint BASE = 0; + private static uint Cursor_BASE = BASE; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs.meta new file mode 100644 index 0000000..1dc5fb6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Message/UICtrlMsg_Base_0-9999.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb50862938136744db6a10a950ab4a27 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Model.meta b/Assets/CrazyZoo/Runtime/Core/Define/Model.meta new file mode 100644 index 0000000..04f4582 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Model.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 05068ae3f93705047a7ad62030047667 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs b/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs new file mode 100644 index 0000000..c454654 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs @@ -0,0 +1,18 @@ +namespace ScrewsMaster +{ + public class ChangeValue + { + public T oldValue; + public T newValue; + + public ChangeValue() + { + } + + public ChangeValue(T oldValue, T newValue) + { + this.oldValue = oldValue; + this.newValue = newValue; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs.meta b/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs.meta new file mode 100644 index 0000000..9b32b34 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Define/Model/ChangeValue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c53b34a8fdfa77143b24d0660057d5a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher.meta new file mode 100644 index 0000000..c1e4884 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bb2dde3fe0fcf6c4cb36b2a465cb36d1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base.meta new file mode 100644 index 0000000..906a7b1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 10e424129050f3a4ab3fdc991bf91318 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs new file mode 100644 index 0000000..038c017 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs @@ -0,0 +1,132 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public abstract class BaseDispatcher : IDisposable where T : class, new() where Param : class + { + private static T m_instance; + + public static T Instance + { + get + { + if (m_instance == null) + { + m_instance = new T(); + } + + return m_instance; + } + } + + private Dictionary>> m_msgPriorityDict = new(); + private Dictionary>> m_msgDict = new(); + private Dictionary>> m_msgFinallyDict = new(); + private Dictionary>> m_msgOnceDict = new(); + + public void AddListener(Msg msgId, Action listener) + { + if (m_msgDict.TryGetValue(msgId, out var value)) + { + value.Add(listener); + } + else + { + var list = ListPool>.Get(); + list.Add(listener); + m_msgDict.Add(msgId, list); + } + } + + public void AddOnceListener(Msg msgId, Action listener) + { + if (m_msgOnceDict.TryGetValue(msgId, out var value)) + { + value.Add(listener); + } + else + { + var list = ListPool>.Get(); + list.Add(listener); + m_msgOnceDict.Add(msgId, list); + } + } + + public void RemoveListener(Msg msgId, Action listener) + { + if (m_msgDict.TryGetValue(msgId, out var list)) + { + if (list.Contains(listener)) + { + list.Remove(listener); + if (list.Count == 0) + { + ListPool>.Release(list); + m_msgDict.Remove(msgId); + } + } + } + } + + public void Dispatch(Msg msgId, Param param = null) + { + InvokeMethods(m_msgPriorityDict, msgId, param); + InvokeMethods(m_msgDict, msgId, param); + InvokeMethods(m_msgFinallyDict, msgId, param); + InvokeMethods(m_msgOnceDict, msgId, param); + + if (m_msgOnceDict.ContainsKey(msgId)) + { + ListPool>.Release(m_msgOnceDict[msgId]); + m_msgOnceDict.Remove(msgId); + } + } + + private void InvokeMethods(Dictionary>> msgDict, Msg msgId, Param param) + { + if (!msgDict.ContainsKey(msgId)) return; + + var rawList = msgDict[msgId]; + int funcCount = rawList.Count; + if (funcCount == 1) + { + Action onEvent = rawList[0]; + onEvent(param); + return; + } + + var invokeFuncs = ListPool>.Get(); + invokeFuncs.AddRange(rawList); + for (var i = 0; i < funcCount; i++) + { + try + { + var onEvent = invokeFuncs[i]; + onEvent(param); + } + catch (Exception e) + { + Debug.LogError(e); + } + } + + ListPool>.Release(invokeFuncs); + } + + public void Dispose() + { + m_instance = null; + + m_msgPriorityDict.Clear(); + m_msgDict.Clear(); + m_msgFinallyDict.Clear(); + m_msgOnceDict.Clear(); + m_msgPriorityDict = null; + m_msgDict = null; + m_msgFinallyDict = null; + m_msgOnceDict = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs.meta new file mode 100644 index 0000000..d1bd95e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4b55125cefc9754888cccfc76bee4c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs new file mode 100644 index 0000000..35f6d7f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace ScrewsMaster +{ + public class BaseMainThreadDispatcher : SingletonUnity + where T : SingletonUnity + where Param : class + { + private class MainThreadMsgClass + { + public Msg currMsgId; + public Param currParam; + } + + private Queue m_msgQueue = new Queue(); + private Dictionary>> m_msgPriorityDict = new Dictionary>>(); + private Dictionary>> m_msgDict = new Dictionary>>(); + private Dictionary>> m_msgOnceDict = new Dictionary>>(); + + private object m_queueLock = new object(); + + private void Update() + { + if (m_msgQueue.Count <= 0) return; + + while (m_msgQueue.Count > 0) + { + MainThreadMsgClass msg; + lock (m_queueLock) + { + msg = m_msgQueue.Dequeue(); + } + + AutoDispatch(msg.currMsgId, msg.currParam); + } + } + + public void Dispatch(Msg msgId, Param param = null) + { + if (!m_msgPriorityDict.ContainsKey(msgId) + && !m_msgDict.ContainsKey(msgId) + && !m_msgOnceDict.ContainsKey(msgId)) + return; + + MainThreadMsgClass msg = new MainThreadMsgClass + { + currMsgId = msgId, + currParam = param, + }; + lock (m_queueLock) + { + m_msgQueue.Enqueue(msg); + } + } + + private void AutoDispatch(Msg msgId, Param param) + { + InvokeMethods(m_msgPriorityDict, msgId, param); + InvokeMethods(m_msgDict, msgId, param); + InvokeMethods(m_msgOnceDict, msgId, param); + + if (m_msgOnceDict.ContainsKey(msgId)) + { + ListPool>.Release(m_msgOnceDict[msgId]); + m_msgOnceDict.Remove(msgId); + } + } + + private void InvokeMethods(Dictionary>> msgDict, Msg msgId, Param param) + { + if (!msgDict.ContainsKey(msgId)) return; + + List> rawList = msgDict[msgId]; + int funcCount = rawList.Count; + if (funcCount == 1) + { + Action onEvent = rawList[0]; + onEvent(param); + return; + } + + List> invokeFuncs = ListPool>.Get(); + invokeFuncs.AddRange(rawList); + for (int i = 0; i < funcCount; i++) + { + try + { + Action onEvent = invokeFuncs[i]; + onEvent(param); + } + catch (Exception e) + { + Debug.LogError(e); + } + } + + ListPool>.Release(invokeFuncs); + } + + protected override string ParentRootName + { + get { return AppObjConst.DispatcherGoName; } + } + + protected override void OnDestroy() + { + base.OnDestroy(); + + m_msgPriorityDict.Clear(); + m_msgDict.Clear(); + m_msgOnceDict.Clear(); + m_msgPriorityDict = null; + m_msgDict = null; + m_msgOnceDict = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs.meta new file mode 100644 index 0000000..cebc9bd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Base/BaseMainThreadDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e02321e1c5d556b4484a914fec6eafbd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic.meta new file mode 100644 index 0000000..1c5ec00 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7926ab78fe6049f3bff905262b9b4695 +timeCreated: 1682307945 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs new file mode 100644 index 0000000..6f96e4b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs @@ -0,0 +1,4 @@ +namespace ScrewsMaster +{ + public class AppDispatcher : BaseDispatcher { } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs.meta new file mode 100644 index 0000000..9db8f82 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/AppDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38ec268add4ac6743a27b7167bdcb36a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs new file mode 100644 index 0000000..f1fe753 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class CtrlDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs.meta new file mode 100644 index 0000000..ae575b7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/CtrlDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f627301519ad9ac43ba05e525564d3a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs new file mode 100644 index 0000000..942a850 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class DataDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs.meta new file mode 100644 index 0000000..c6bd7c5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/DataDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 080dce14c0be15a448f7a6f1d316700f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs new file mode 100644 index 0000000..ef6b5dc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class GameDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs.meta new file mode 100644 index 0000000..89372b1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/GameDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ab8a1624eafed174385147056385f287 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs new file mode 100644 index 0000000..6b1f387 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class MainThreadDispatcher : BaseMainThreadDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs.meta new file mode 100644 index 0000000..7d3f1c1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/MainThreadDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc759fa7eaebc574da1d3990ca6acfa5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs new file mode 100644 index 0000000..b88fa8c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class ModelDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs.meta new file mode 100644 index 0000000..bf8ea53 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/ModelDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 730ba6382f4f49444a8219f08543f431 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs new file mode 100644 index 0000000..c7a6752 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class NetworkDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs.meta new file mode 100644 index 0000000..8e86f84 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/NetworkDispatcher.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 81a02ff4d9ca458aa70fe26ab514bb99 +timeCreated: 1681977441 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs new file mode 100644 index 0000000..2422f41 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs @@ -0,0 +1,12 @@ +namespace ScrewsMaster +{ + public class PreferencesDispatcher : BaseDispatcher, string, ChangeValue> + { + public ChangeValue changeValue; + + public PreferencesDispatcher() + { + changeValue = new ChangeValue(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs.meta new file mode 100644 index 0000000..d658de3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/PreferencesDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9387267f575e6bb4ca279738a461ad61 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs new file mode 100644 index 0000000..6bdb3d2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class UICtrlDispatcher : BaseDispatcher + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs.meta new file mode 100644 index 0000000..d78a40a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Logic/UICtrlDispatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1a26910085caa349b769e0be54a023a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message.meta new file mode 100644 index 0000000..3d0da25 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 29aecd4f55584cddae5eb19c86727362 +timeCreated: 1682308355 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs new file mode 100644 index 0000000..d8bf7b3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs @@ -0,0 +1,26 @@ +public static class AppMsg +{ + public const uint BASE = 0; + private static uint Cursor_BASE = BASE; + public static readonly uint App_Quit = ++Cursor_BASE; + public static readonly uint App_Focus_False = ++Cursor_BASE; + public static readonly uint App_Pause_True = ++Cursor_BASE; + public static readonly uint App_GamePause = ++Cursor_BASE; + public static readonly uint App_GameResume = ++Cursor_BASE; + public static readonly uint App_SwitchLanguage = ++Cursor_BASE; + public static readonly uint UI_DisplayLoadingUI = ++Cursor_BASE; + public static readonly uint UI_HideLoadingUI = ++Cursor_BASE; + public static readonly uint UI_LoadingInitAsset = ++Cursor_BASE; + public static readonly uint AppManagerRegister = ++Cursor_BASE; + public static readonly uint InitUIMgr = ++Cursor_BASE; + public static readonly uint UIEvent_UIOpen = ++Cursor_BASE; + public static readonly uint UIEvent_UIClose = ++Cursor_BASE; + public static readonly uint UIEvent_UIDisplay = ++Cursor_BASE; + public static readonly uint UIEvent_UIHide = ++Cursor_BASE; + public static readonly uint KeyCode_Home = ++Cursor_BASE; + public static readonly uint KeyCode_Escape = ++Cursor_BASE; + public static readonly uint TimeScale_Change = ++Cursor_BASE; + public static readonly uint WorldRaycast_EnableChange = ++Cursor_BASE; + public static readonly uint App_Focus_True = ++Cursor_BASE; + public static readonly uint LoginInit = ++Cursor_BASE; +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs.meta new file mode 100644 index 0000000..dc110da --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/AppMsg_Frame_0-9999.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b87eaa2cadb1da4f8dba83b0b9d3731 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs new file mode 100644 index 0000000..1fd8fff --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs @@ -0,0 +1,7 @@ +public static class MainThreadMsg +{ + public const uint BASE = 0; + private static uint Cursor_BASE = BASE; + public static readonly uint App_Focus_True = ++Cursor_BASE; + public static readonly uint App_Pause_False = ++Cursor_BASE; +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs.meta b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs.meta new file mode 100644 index 0000000..009c45f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Dispatcher/Message/MainThreadMsg_Frame_0-9999.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0061a4ff521ce154c8ca284f91d1cf8f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs b/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs new file mode 100644 index 0000000..f699308 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs @@ -0,0 +1,46 @@ +using UnityEngine; +using System.Collections.Generic; +using ScrewsMaster; + + +public class ErrorLogger : MonoBehaviour +{ + // 用于存储报错信息的列表 + private List errorLogs = new List(); + + void OnEnable() + { + // 注册事件处理函数 + Application.logMessageReceived += HandleLog; + } + + void OnDisable() + { + // 注销事件处理函数 + Application.logMessageReceived -= HandleLog; + } + + // 事件处理函数 + void HandleLog(string logString, string stackTrace, LogType type) + { + // 只处理错误和异常类型的日志 + if (type == LogType.Error || type == LogType.Exception) + { + // 将报错信息和堆栈跟踪添加到列表中 + errorLogs.Add(logString); + errorLogs.Add(stackTrace); + + // 这里可以添加代码将报错信息发送给服务器 + SendErrorToServer(logString, stackTrace); + } + } + + // 如何将报错信息发送给服务器 + void SendErrorToServer(string error, string stackTrace) + { + // Debug.Log($"SendErrorToServer-----------error\n{error}"); + // Debug.Log($"SendErrorToServer-----------stackTrace\n{stackTrace}"); + // 这里填写将报错信息发送到服务器的代码 + GameHelper.SendErrorToServer(error, stackTrace); + } +} diff --git a/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs.meta b/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs.meta new file mode 100644 index 0000000..c65fb85 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ErrorLogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5a9adb6383d4d1846a5c1efee1e943ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Extend.meta b/Assets/CrazyZoo/Runtime/Core/Extend.meta new file mode 100644 index 0000000..0d60cb2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b5af2e719d8d8cd4891e2098b3dad9e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs b/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs new file mode 100644 index 0000000..7d0f84e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs @@ -0,0 +1,24 @@ +namespace ScrewsMaster +{ + public static class StringExtend + { + public static double ToDouble(this string str) + { + double temp = 0d; + double.TryParse(str, out temp); + return temp; + } + + public static float ToFloat(this string str) + { + float temp = 0; + float.TryParse(str, out temp); + return temp; + } + + public static bool IsNullOrWhiteSpace(this string str) + { + return string.IsNullOrWhiteSpace(str); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs.meta b/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs.meta new file mode 100644 index 0000000..503286d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend/StringExtend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79592f013fcf6dc439f2a2940770a250 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Extend/Unity.meta b/Assets/CrazyZoo/Runtime/Core/Extend/Unity.meta new file mode 100644 index 0000000..d61e3b0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend/Unity.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 07cf9660c4614ccca70ef0f5889aae92 +timeCreated: 1682316629 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs b/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs new file mode 100644 index 0000000..0d54836 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class GameObjectExtend + { + public static void SetParent(this GameObject gameObject, GameObject parentGo, bool worldPositionStays = false) + { + if (parentGo) + { + gameObject.transform.SetParent(parentGo.transform, worldPositionStays); + } + } + + public static void SetLayer(this GameObject gameObject, string layerName) + { + Transform[] transArr = gameObject.transform.GetComponentsInChildren(); + for (int i = 0; i < transArr.Length; i++) + { + transArr[i].gameObject.layer = LayerMask.NameToLayer(layerName); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs.meta b/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs.meta new file mode 100644 index 0000000..19b4787 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Extend/Unity/GameObjectExtend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f33a4adea56c7dc41944ee83d4ef3f84 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/GooglePay.meta b/Assets/CrazyZoo/Runtime/Core/GooglePay.meta new file mode 100644 index 0000000..18aff5e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/GooglePay.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6e61d44d2343c5f4589e13779ec5cb71 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs b/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs new file mode 100644 index 0000000..9cb9a0c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs @@ -0,0 +1,18 @@ + +using Unity.Services.Core; +using Unity.Services.Core.Environments; +using UnityEngine; + +public class InitializeUnityServices : MonoBehaviour +{ + public string environment = "prime-script-405407"; + async void Start() + { + + Debug.Log($"Start environment: {environment}"); + + var options = new InitializationOptions().SetEnvironmentName(environment); + await UnityServices.InitializeAsync(options); + } + +} diff --git a/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs.meta b/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs.meta new file mode 100644 index 0000000..daab125 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/InitializeUnityServices.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b88f4352f192a34ca4217a9f96f870e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC.meta b/Assets/CrazyZoo/Runtime/Core/MVC.meta new file mode 100644 index 0000000..f00709a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3f9cd760110665a41a7b4c4a96ae85e0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl.meta b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl.meta new file mode 100644 index 0000000..d1fcd94 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 45a53fe4413ebe44dbf670faf8651e3b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs new file mode 100644 index 0000000..788b205 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs @@ -0,0 +1,114 @@ +namespace ScrewsMaster +{ + public abstract class BaseCtrl + { + public string ctrlName; + public bool isEnable = true; + public bool IsNew { get; private set; } + + protected ModuleManager moduleManager; + + protected ModelDispatcher modelDispatcher; + protected CtrlDispatcher ctrlDispatcher; + protected UICtrlDispatcher uiCtrlDispatcher; + protected DataDispatcher dataDispatcher; + protected GameDispatcher gameDispatcher; + + public void New() + { + if (!isEnable) return; + + OnNew(); + IsNew = true; + } + + public virtual void Init() + { + if (!isEnable) return; + + Assignment(); + AddListener(); + AddServerListener(); + OnInit(); + } + + public virtual void StartUp() + { + if (!isEnable) return; + + OnStartUp(); + } + + public virtual void GameStart() + { + if (!isEnable) return; + + OnGameStart(); + } + + public virtual void Dispose() + { + if (!isEnable) return; + + RemoveListener(); + RemoveServerListener(); + OnDispose(); + UnAssignment(); + IsNew = false; + } + + protected virtual void Assignment() + { + moduleManager = ModuleManager.Instance; + + modelDispatcher = ModelDispatcher.Instance; + ctrlDispatcher = CtrlDispatcher.Instance; + uiCtrlDispatcher = UICtrlDispatcher.Instance; + dataDispatcher = DataDispatcher.Instance; + gameDispatcher = GameDispatcher.Instance; + } + + protected virtual void UnAssignment() + { + moduleManager = null; + + modelDispatcher = null; + ctrlDispatcher = null; + uiCtrlDispatcher = null; + dataDispatcher = null; + gameDispatcher = null; + } + + protected virtual void OnNew() + { + } + + protected abstract void OnInit(); + + protected virtual void OnStartUp() + { + } + + protected virtual void OnGameStart() + { + } + + protected abstract void OnDispose(); + + protected virtual void AddListener() + { + } + + protected virtual void RemoveListener() + { + } + + protected virtual void AddServerListener() + { + } + + protected virtual void RemoveServerListener() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs.meta new file mode 100644 index 0000000..e3d942a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b81051b63111ae24091f178cd25ab0a5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs new file mode 100644 index 0000000..b0c516c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs @@ -0,0 +1,33 @@ +namespace ScrewsMaster +{ + public abstract class BaseUICtrl : BaseCtrl + { + public virtual uint GetOpenUIMsg(string uiName) + { + return 0; + } + + public virtual uint GetCloseUIMsg(string uiName) + { + return 0; + } + + public void DispatchCloseUI(string uiName = null, object args = null) + { + uint msgId = GetCloseUIMsg(uiName); + if (msgId == 0) + { + CloseUI(args); + return; + } + + if (uiCtrlDispatcher != null) + { + uiCtrlDispatcher.Dispatch(msgId, args); + } + } + + public abstract void OpenUI(object args = null); + public abstract void CloseUI(object args = null); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs.meta new file mode 100644 index 0000000..1097d57 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Ctrl/BaseUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17086b56b8ce86e44a2a0e0f23b0f5ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Model.meta b/Assets/CrazyZoo/Runtime/Core/MVC/Model.meta new file mode 100644 index 0000000..510eb30 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Model.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eeb97e2ef9396894d8e09b5ac644433e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs b/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs new file mode 100644 index 0000000..b1a8288 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs @@ -0,0 +1,107 @@ +namespace ScrewsMaster +{ + public abstract class BaseModel + { + public string modelName; + private string localStorageKey; + + protected ModuleManager mOduleManager; + + protected ModelDispatcher modelDispatcher; + protected CtrlDispatcher ctrlDispatcher; + protected UICtrlDispatcher uiCtrlDispatcher; + protected DataDispatcher dataDispatcher; + protected GameDispatcher gameDispatcher; + + public void New() + { + OnNew(); + } + + public void Init() + { + Assignment(); + AddListener(); + AddServerListener(); + OnInit(); + } + + public void StartUp() + { + OnStartUp(); + } + + public void GameStart() + { + OnGameStart(); + } + + public void Reset() + { + Dispose(); + Init(); + } + + public void Dispose() + { + RemoveListener(); + RemoveServerListener(); + OnDispose(); + UnAssignment(); + } + + protected virtual void Assignment() + { + mOduleManager = ModuleManager.Instance; + + modelDispatcher = ModelDispatcher.Instance; + ctrlDispatcher = CtrlDispatcher.Instance; + uiCtrlDispatcher = UICtrlDispatcher.Instance; + dataDispatcher = DataDispatcher.Instance; + gameDispatcher = GameDispatcher.Instance; + } + + protected virtual void UnAssignment() + { + mOduleManager = null; + + modelDispatcher = null; + ctrlDispatcher = null; + uiCtrlDispatcher = null; + dataDispatcher = null; + gameDispatcher = null; + } + + protected virtual void OnNew() + { + } + + protected abstract void OnInit(); + + protected virtual void OnStartUp() + { + } + + protected virtual void OnGameStart() + { + } + + protected abstract void OnDispose(); + + protected virtual void AddListener() + { + } + + protected virtual void RemoveListener() + { + } + + protected virtual void AddServerListener() + { + } + + protected virtual void RemoveServerListener() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs.meta new file mode 100644 index 0000000..1f209fa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/Model/BaseModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ab9296c1feb18b42a12bbc53cdfc39b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View.meta b/Assets/CrazyZoo/Runtime/Core/MVC/View.meta new file mode 100644 index 0000000..7d1130b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e875f86aa27a545449f052c022fcd58c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI.meta b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI.meta new file mode 100644 index 0000000..b5ae00f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 350d8669cca7ae24282a784c6a857707 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs new file mode 100644 index 0000000..2b62799 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs @@ -0,0 +1,338 @@ +using FairyGUI; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public abstract class BaseUI + { + protected UIManager mUIManager; + protected ModuleManager moduleManager; + + protected ModelDispatcher modelDispatcher; + protected CtrlDispatcher ctrlDispatcher; + protected UICtrlDispatcher uiCtrlDispatcher; + protected DataDispatcher dataDispatcher; + protected GameDispatcher gameDispatcher; + + public string uiName; + public string rawGameObjectName; + public string gameObjectName; + public UIInfo uiInfo; + + public uint uiOpenCumsumId; + public int currLayer; + public BaseUICtrl baseUICtrl; + public object uiArgs; + + public GObject baseGObj; + public GComponent baseUI; + public Window windowUI; + public GGraph uiMask; + public List subUIs; + + public bool isOpen; + public bool isVisible; + public bool isClose; + + public GTweener openUiGTweener; + public GTweener closeUiGTweener; + + public BaseUI(BaseUICtrl baseUICtrl) + { + New(baseUICtrl); + } + + public void New(BaseUICtrl baseUICtrl) + { + this.baseUICtrl = baseUICtrl; + + Assignment(); + OnNew(); + Process_Init(); + } + + protected virtual void Assignment() + { + mUIManager = UIManager.Instance; + moduleManager = ModuleManager.Instance; + + modelDispatcher = ModelDispatcher.Instance; + ctrlDispatcher = CtrlDispatcher.Instance; + uiCtrlDispatcher = UICtrlDispatcher.Instance; + dataDispatcher = DataDispatcher.Instance; + gameDispatcher = GameDispatcher.Instance; + } + + protected virtual void UnAssignment() + { + mUIManager = null; + moduleManager = null; + + modelDispatcher = null; + ctrlDispatcher = null; + uiCtrlDispatcher = null; + dataDispatcher = null; + gameDispatcher = null; + } + + + public void Open(object args = null) + { + uiArgs = args; + mUIManager.Internal_OpenUI(this, args); + } + + public void Close() + { + if (isClose) return; + mUIManager.Internal_CloseUI(this); + } + + public void Hide() + { + mUIManager.Internal_HideUI(this); + } + + public void Display(object args = null) + { + uiArgs = args; + mUIManager.Internal_DisplayUI(this, args); + } + + + private void Process_Init() + { + isOpen = false; + isVisible = false; + isClose = false; + + uiInfo = new UIInfo(); + + SetUIInfo(uiInfo); + PostProcess_UIInfo(); + OnInit(); + } + + private void PostProcess_UIInfo() + { + } + + public void Process_Bind() + { + OnBind(); + } + + public void Process_OpenBefore(object args) + { + OnOpenBefore(args); + } + + public void Process_Open(object args) + { + OnOpen(args); + AddListener(); + AddServerListener(); + + isOpen = true; + } + + public void Process_OpenUIAnimEnd() + { + OnOpenUIAnimEnd(); + } + + public void Process_Close() + { + RemoveListener(); + RemoveServerListener(); + OnClose(); + + isClose = true; + } + + public void Process_CloseUIAnimEnd() + { + OnCloseUIAnimEnd(); + } + + public void Process_Destroy() + { + OnDestroy(); + UnAssignment(); + + isOpen = false; + isVisible = false; + isClose = true; + + baseGObj = null; + baseUI = null; + windowUI = null; + } + + public void Process_Hide() + { + isVisible = false; + baseUI.visible = isVisible; + OnHide(); + } + + public void Process_Display(object args) + { + isVisible = true; + baseUI.visible = isVisible; + OnDisplay(args); + } + + public void ProcessFunc_SwitchLanguage() + { + if (isClose) return; + if (baseUI == null) return; + if (baseUI.isDisposed) return; + + InternaProcesslFunc_GComponentSwitchLanguage(baseUI); + OnSwitchLanguage(); + } + + private void InternaProcesslFunc_GComponentSwitchLanguage(GComponent switchCom) + { + if (switchCom == null) return; + if (switchCom.isDisposed) return; + + for (int i = 0; i < switchCom.GetChildrenCount(); i++) + { + GObject gObject = switchCom.GetChildAt(i); + if (gObject == null || gObject.isDisposed) continue; + + GComponent childCom = gObject.asCom; + if (childCom != null) + { + InternaProcesslFunc_GComponentSwitchLanguage(childCom); + continue; + } + else + { + if (gObject.packageItem != null) continue; + if (gObject.parent == null) continue; + + string text = null; + if (gObject is GTextField) + { + GTextField gTextField = gObject.asTextField; + if (gTextField == null) continue; + if (!gTextField.Ex_IsAutoMultiLang) continue; + + text = gObject.Ex_GetMultiLangText(); + if (text != null) + { + gTextField.text = text; + continue; + } + } + } + } + } + + protected virtual void OnNew() + { + } + + protected abstract void SetUIInfo(UIInfo uiInfo); + + protected virtual void OnInit() + { + } + + protected virtual void OnBind() + { + } + + protected virtual void OnOpenBefore(object args) + { + } + + protected virtual void OnOpen(object args) + { + } + + protected virtual void OnOpenUIAnimEnd() + { + } + + protected virtual void OnClose() + { + } + + protected virtual void OnCloseUIAnimEnd() + { + } + + protected virtual void OnDestroy() + { + } + + protected virtual void OnHide() + { + } + + protected virtual void OnDisplay(object args) + { + } + + public virtual void OnUpdate() + { + } + + public virtual void OnSwitchLanguage() + { + } + + protected virtual void AddListener() + { + } + + protected virtual void RemoveListener() + { + } + + protected virtual void AddServerListener() + { + } + + protected virtual void RemoveServerListener() + { + } + + public void KillOpenUIAnim() + { + if (openUiGTweener != null) + { + if (!openUiGTweener.allCompleted) + { + openUiGTweener.Kill(complete: false); + } + + openUiGTweener = null; + } + } + + public void KillCloseUIAnim() + { + if (closeUiGTweener != null) + { + if (!closeUiGTweener.allCompleted) + { + closeUiGTweener.Kill(complete: false); + } + + closeUiGTweener = null; + } + } + + public void CtrlCloseUI() + { + if (baseUICtrl == null) return; + + baseUICtrl.DispatchCloseUI(uiName); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs.meta new file mode 100644 index 0000000..93d74ca --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/BaseUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2304886815d7ebc45aff43b801f57c13 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs new file mode 100644 index 0000000..08b18cc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs @@ -0,0 +1,24 @@ +using FairyGUI; + +namespace ScrewsMaster +{ + public class SubUI + { + public string uiName; + public string packageName; + public string assetName; + + public string rawGameObjectName; + public string gameObjectName; + + public GObject baseGObj; + public GComponent baseUI; + + public SubUI(string uiName, string packageName, string assetName) + { + this.uiName = uiName; + this.packageName = packageName; + this.assetName = assetName; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs.meta new file mode 100644 index 0000000..7341e72 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/SubUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bffd78e7d21b93a42a38ac88f77d3432 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs new file mode 100644 index 0000000..c9d39a5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs @@ -0,0 +1,52 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class UIInfoConst + { + public static Color DefaultUIMaskColor = new Color(0, 0, 0, 0.8f); + } + + public class UIInfo + { + public string packageName = null; + public string assetName = null; + public UILayerType layerType = UILayerType.Normal; + public UIGComType gComType = UIGComType.GComponent; + public uint closeUIMsgId = 0; + public bool isSwitchSceneCloseUI = false; + public bool isTickUpdate = false; + public bool isClosetWorldRaycast = false; + public bool isNeedOpenAnim = false; + public bool isNeedCloseAnim = false; + public bool isNeedUIMask = false; + public bool isNeedUIMaskCloseEvent = false; + public Color uiMaskCustomColor = UIInfoConst.DefaultUIMaskColor; + } + + public enum UILayerType : int + { + Background = 0, + Bottom = 1, + + Normal = 2, + Top = 3, + + FullScreen = 4, + Popup = 5, + + Highest = 6, + Animation = 7, + Tips = 8, + + Loading = 9, + System = 10, + NetworkError = 10, + } + + public enum UIGComType : int + { + GComponent = 0, + Window = 1, + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs.meta b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs.meta new file mode 100644 index 0000000..981b720 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/MVC/View/UI/UIInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aaef7fcebcd15164bb758addcacaef25 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager.meta b/Assets/CrazyZoo/Runtime/Core/Manager.meta new file mode 100644 index 0000000..6b19587 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9055b54ac909c09448c7707cd2760486 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Base.meta new file mode 100644 index 0000000..4ba6440 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 46cb2ee281f541848a34a54377ffab9f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs new file mode 100644 index 0000000..4252b02 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs @@ -0,0 +1,55 @@ +using System; + +namespace ScrewsMaster +{ + + public abstract class BaseInterfaceManager : IDisposable, InterfaceManager where T : BaseInterfaceManager, new() + { + public bool IsInit { get; private set; } + public bool IsStartUp { get; private set; } + public bool IsDispose { get; private set; } + + private static T m_instance; + + public static T Instance + { + get + { + if (m_instance == null) + { + m_instance = new T(); + m_instance.New(); + } + + return m_instance; + } + } + + protected virtual void New() + { + IsDispose = false; + } + + public virtual void Init() + { + IsInit = true; + } + + public virtual void StartUp() + { + IsStartUp = true; + } + + public virtual void DisposeBefore() + { + IsDispose = true; + IsInit = false; + IsStartUp = false; + } + + public virtual void Dispose() + { + m_instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs.meta new file mode 100644 index 0000000..3653eb4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseInterfaceManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0395f071bf7ad864083ee86433bcec9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs new file mode 100644 index 0000000..c01e43f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs @@ -0,0 +1,39 @@ +namespace ScrewsMaster +{ + + public abstract class BaseUnityManager : SingletonUnity, InterfaceManager + where T : BaseUnityManager + { + public bool IsInit { get; private set; } + public bool IsStartUp { get; private set; } + public bool IsDispose { get; private set; } + + protected override string ParentRootName + { + get { return AppObjConst.MonoManagerGoName; } + } + + protected override void New() + { + base.New(); + IsDispose = false; + } + + public virtual void Init() + { + IsInit = true; + } + + public virtual void StartUp() + { + IsStartUp = true; + } + + public virtual void DisposeBefore() + { + IsDispose = true; + IsInit = false; + IsStartUp = false; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs.meta new file mode 100644 index 0000000..d310ee3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/BaseUnityManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c01f68bc92a2b648a38f328f7e95ce6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs new file mode 100644 index 0000000..4ce84eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs @@ -0,0 +1,10 @@ +namespace ScrewsMaster +{ + public interface InterfaceManager + { + void Init(); + void StartUp(); + void DisposeBefore(); + void Dispose(); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs.meta new file mode 100644 index 0000000..9f2f199 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Base/InterfaceManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e53d06f42f51d84498ab4ffe80556de6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager.meta new file mode 100644 index 0000000..84e570f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 75c9b664059ad8548943c2dcce3e3b4e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs new file mode 100644 index 0000000..187ee15 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs @@ -0,0 +1,148 @@ +using FairyGUI; +using UnityEngine; +using UnityEngine.EventSystems; + +namespace ScrewsMaster +{ + public sealed class CameraManager : BaseInterfaceManager + { + public Transform mainCameraRoot; + public GameObject mainCameraGo; + public Camera mainCamera; + + public Transform fguiCameraRoot; + public GameObject fguiCameraGo; + public Camera fguiCamera; + + + public bool isEnabledWorldRaycast; + public Physics2DRaycaster physics2DRaycaster; + public PhysicsRaycaster physics3DRaycaster; + + private bool isMainCameraShakeing; + + #region Coordinate + + public Vector2 WorldPosToFGUIPos(Vector3 worldPos) + { + Vector3 screenPos = mainCamera.WorldToScreenPoint(worldPos); + + screenPos.y = ScreenConst.CurrResolution.y - screenPos.y; + Vector2 pt = GRoot.inst.GlobalToLocal(screenPos); + return pt; + } + + #endregion + + #region Func + + public void SetWorldRaycasterEnabled(bool enabled) + { + isEnabledWorldRaycast = enabled; + if (physics2DRaycaster != null) + { + EventKit.Set2DRaycasterEnabled(physics2DRaycaster, isEnabledWorldRaycast); + } + + if (physics3DRaycaster != null) + { + EventKit.Set3DRaycasterEnabled(physics3DRaycaster, isEnabledWorldRaycast); + } + + AppDispatcher.Instance.Dispatch(AppMsg.WorldRaycast_EnableChange, isEnabledWorldRaycast); + } + + #endregion + + #region Camera + + public void CreateMainCamera() + { + if (mainCamera) return; + + string name = "MainCamera"; + mainCameraGo = new GameObject(name); + mainCameraGo.tag = name; + mainCameraGo.layer = LayerMaskConst.Default; + mainCameraGo.transform.localPosition = Vector3.zero; + int cullingMask = LayerMask.GetMask(LayerMaskConst.Default_Name); + mainCamera = CreateCamera(mainCameraGo, cullingMask: cullingMask); + mainCamera.clearFlags = CameraClearFlags.SolidColor; + + mainCamera.forceIntoRenderTexture = false; + + GameObject root = new GameObject(name + "Root"); + root.transform.position = CameraConst.MainCameraPos; + root.SetParent(AppObjConst.CameraGo); + mainCameraGo.SetParent(root); + mainCameraRoot = root.transform; + + CameraAdaptive adaptiveCom = mainCamera.gameObject.AddComponent(); + adaptiveCom.DoAdaptive(isOrthographic: true, orthographicSize: ScreenConst.OrthographicSize_1280H); + } + + public void CreateFGUICamera() + { + if (fguiCamera) return; + + StageCamera.CheckMainCamera(); + fguiCamera = StageCamera.main; + fguiCamera.depth = CameraConst.UICameraDepth; + + fguiCamera.forceIntoRenderTexture = false; + fguiCameraGo = fguiCamera.gameObject; + + GameObject root = new GameObject("FGUICameraRoot"); + root.transform.position = CameraConst.UICameraPos; + root.SetParent(AppObjConst.CameraGo); + fguiCameraGo.SetParent(root); + fguiCameraRoot = root.transform; + } + + public Camera CreateCamera(GameObject cameraGo, int cullingMask) + { + Camera cameraCom = cameraGo.AddComponent(); + cameraCom.clearFlags = CameraClearFlags.Depth; + cameraCom.backgroundColor = Color.black; + cameraCom.cullingMask = cullingMask; + cameraCom.nearClipPlane = -30f; + cameraCom.farClipPlane = 30f; + cameraCom.rect = new Rect(0, 0, 1f, 1f); + cameraCom.depth = CameraConst.MainDepth; + cameraCom.renderingPath = RenderingPath.UsePlayerSettings; + cameraCom.useOcclusionCulling = false; + cameraCom.allowHDR = false; + cameraCom.allowMSAA = false; + cameraCom.orthographicSize = 9.6f; + cameraCom.forceIntoRenderTexture = false; + return cameraCom; + } + + #endregion + + #region Mgr + + public override void Init() + { + base.Init(); + InitCameraMgr(); + + CreateMainCamera(); + CreateFGUICamera(); + } + + private void InitCameraMgr() + { + AppObjConst.CameraGo = new GameObject(AppObjConst.CameraGoName); + AppObjConst.CameraGo.SetParent(AppObjConst.FrameGo); + } + + public override void Dispose() + { + base.Dispose(); + GeneralKit.Destroy(AppObjConst.CameraGo); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs.meta new file mode 100644 index 0000000..25c9d66 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/CameraManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45cef881d003bb84394180b075125699 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs new file mode 100644 index 0000000..ccf51a0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs @@ -0,0 +1,61 @@ +using System; + +namespace ScrewsMaster +{ + public sealed class DateTimeManager : BaseInterfaceManager + { + public static DateTime StartTimestampDT = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + private long HeartBeatInterval = 7; + public int ServerRTTOneWayTimeOffset { get; private set; } + + public long GetCurrTimestamp() + { + long timestamp = (long)(DateTime.Now - StartTimestampDT).TotalSeconds; + return timestamp; + } + + public long GetServerCurrTimestamp() + { + return GetCurrTimestamp() - ServerRTTOneWayTimeOffset; + } + + public DateTime GetCurrDateTime() + { + return DateTime.Now; + } + + public DateTime GetDateTime(long timestamp) + { + DateTime dt = StartTimestampDT.AddSeconds(timestamp); + return dt; + } + + public string DateTimeToYYYYMMDD(DateTime time) + { + return time.ToString("yyyyMMdd"); + } + + public string DateTimeToString(DateTime time) + { + return time.ToString("yyyy/MM/dd HH:mm:ss"); + } + + public string TimestampToString(long endTimestamp) + { + return DateTimeToString(GetDateTime(endTimestamp)); + } + public long GetCurrTimesTampByMillisecond() + { + long time = (long)(DateTime.Now - StartTimestampDT).TotalMilliseconds; + return time; + } + public string DateTimeToFFFString(DateTime time) + { + return time.ToString("HH:mm:ss ff"); + } + public long GetServerCurrTimestampByMillisecond() + { + return GetCurrTimesTampByMillisecond() - ServerRTTOneWayTimeOffset * 1000; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs.meta new file mode 100644 index 0000000..e83728d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/DateTimeManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c2ef349abda84fd42801a3062464921f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs new file mode 100644 index 0000000..f1fd4cf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs @@ -0,0 +1,50 @@ + +namespace ScrewsMaster +{ + public sealed class GameIManager : BaseInterfaceManager + { + private float pauseCacheTimeScale = 1; + + #region Scene + + public void InitialMain() + { + SceneManager.Instance.InitialMain(); + } + + public void EnterMain() + { + SceneManager.Instance.SwitchScene(SceneManager.DefaultMainSceneIdx); + } + + #endregion Scene + + #region Msg + + private void AddListener() + { + } + + private void RemoveListener() + { + } + + #endregion Msg + + #region Private + + public override void Init() + { + base.Init(); + AddListener(); + } + + public override void Dispose() + { + base.Dispose(); + RemoveListener(); + } + + #endregion Private + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs.meta new file mode 100644 index 0000000..d1a814d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/GameIManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 65948735d1d6a7249a4ee2778a8867b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs new file mode 100644 index 0000000..b6544bf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public sealed class ModuleManager : BaseInterfaceManager + { + private Dictionary modelDict = new(); + private Dictionary uiTypeDict = new(); + private Dictionary ctrlDict = new(); + private Dictionary uiCtrlDict = new(); + + public override void Init() + { + base.Init(); + InitAllModule(); + } + + private void InitAllModule() + { + List ctrlDisableList = AppConst.CtrlDisableList; + + foreach (BaseModel model in modelDict.Values) + { + model.New(); + } + + foreach (BaseCtrl ctrl in ctrlDict.Values) + { + if (!ctrl.isEnable) + { + continue; + } + + if (ctrlDisableList.Contains(ctrl.ctrlName)) + { + ctrl.isEnable = false; + continue; + } + + ctrl.isEnable = true; + ctrl.New(); + } + + foreach (BaseUICtrl uiCtrl in uiCtrlDict.Values) + { + if (!uiCtrl.isEnable) + { + continue; + } + + if (ctrlDisableList.Contains(uiCtrl.ctrlName)) + { + uiCtrl.isEnable = false; + continue; + } + + uiCtrl.isEnable = true; + uiCtrl.New(); + } + + + foreach (BaseModel model in modelDict.Values) + { + model.Init(); + } + + foreach (BaseCtrl ctrl in ctrlDict.Values) + { + ctrl.Init(); + } + + foreach (BaseUICtrl uiCtrl in uiCtrlDict.Values) + { + uiCtrl.Init(); + } + } + + public void StartUpAllModule() + { + foreach (BaseModel model in modelDict.Values) + { + model.StartUp(); + } + + foreach (BaseCtrl ctrl in ctrlDict.Values) + { + ctrl.StartUp(); + } + + foreach (BaseUICtrl uiCtrl in uiCtrlDict.Values) + { + uiCtrl.StartUp(); + } + } + + public void AllModuleGameStart() + { + foreach (BaseModel model in modelDict.Values) + { + model.GameStart(); + } + + foreach (BaseCtrl ctrl in ctrlDict.Values) + { + ctrl.GameStart(); + } + + foreach (BaseUICtrl uiCtrl in uiCtrlDict.Values) + { + uiCtrl.GameStart(); + } + } + + public BaseModel GetModel(string modelName) + { + BaseModel model = null; + if (!modelDict.TryGetValue(modelName, out model)) + { + } + + return model; + } + + public BaseUICtrl GetUICtrl(string uiCtrlName) + { + BaseUICtrl uiCtrl = null; + if (!uiCtrlDict.TryGetValue(uiCtrlName, out uiCtrl)) + { + } + + return uiCtrl; + } + + public void AddModel(string modelName, BaseModel model) + { + model.modelName = modelName; + modelDict[modelName] = model; + } + + public void AddUIType(string uiName, Type uiType) + { + uiTypeDict[uiName] = uiType; + } + + public void AddCtrl(string ctrlName, BaseCtrl ctrl) + { + ctrl.ctrlName = ctrlName; + ctrlDict[ctrlName] = ctrl; + } + + public void AddUICtrl(string ctrlName, BaseUICtrl uiCtrl) + { + uiCtrl.ctrlName = ctrlName; + uiCtrlDict[ctrlName] = uiCtrl; + } + + public void DisposeAllModel() + { + foreach (BaseModel model in modelDict.Values) + { + model.Dispose(); + } + + modelDict.Clear(); + } + + public void DisposeAllCtrl() + { + foreach (BaseCtrl ctrl in ctrlDict.Values) + { + ctrl.Dispose(); + } + + foreach (BaseUICtrl uiCtrl in uiCtrlDict.Values) + { + uiCtrl.Dispose(); + } + + ctrlDict.Clear(); + uiCtrlDict.Clear(); + } + + public void DisposeAllModule() + { + DisposeAllModel(); + DisposeAllCtrl(); + } + + public override void Dispose() + { + base.Dispose(); + + modelDict = null; + uiTypeDict = null; + ctrlDict = null; + uiCtrlDict = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs.meta new file mode 100644 index 0000000..7c3a48f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/ModuleManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eeedf720d335ccb4fa1e3d3497001ec3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs new file mode 100644 index 0000000..2dc0d01 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs @@ -0,0 +1,85 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public sealed class SceneManager : BaseInterfaceManager + { + public const int DefaultMainSceneIdx = 0; + + private Dictionary sceneDict = new(); + private BaseScene m_currScene; + + public void AddScene(BaseScene scene) + { + if (!sceneDict.ContainsKey(scene.SceneIdx)) + { + sceneDict[scene.SceneIdx] = scene; + } + } + + public void InitialMain(object param = null) + { + if (sceneDict.Count == 0) return; + + + BaseScene scene = GetScene(DefaultMainSceneIdx); + if (SetScene(scene)) + { + SceneSwitchManager.Instance.SwitchInitialScene(DefaultMainSceneIdx, scene.SwitchSceneComplete, param); + } + } + + public void SwitchScene(int sceneIdx, object param = null) + { + BaseScene scene = GetScene(sceneIdx); + if (SetScene(scene)) + { + UIManager.Instance.SwitchSceneCloseAllUI(); + SceneSwitchManager.Instance.SwitchScene(sceneIdx, scene.SwitchSceneComplete, param); + } + } + + private bool SetScene(BaseScene scene) + { + if (scene == null) + { + return false; + } + else if (scene == m_currScene) + { + return false; + } + + if (m_currScene != null) + { + m_currScene.Leave(); + } + + m_currScene = scene; + m_currScene.Enter(); + return true; + } + + private BaseScene GetScene(int sceneIdx) + { + BaseScene scene = null; + if (!sceneDict.TryGetValue(sceneIdx, out scene)) + { + } + + return scene; + } + + public override void Dispose() + { + base.Dispose(); + foreach (BaseScene scene in sceneDict.Values) + { + scene.Dispose(); + } + + sceneDict.Clear(); + sceneDict = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs.meta new file mode 100644 index 0000000..8ea6c90 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/Manager/SceneManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c5e07bf3e2b867c4b9d7776206acc020 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs new file mode 100644 index 0000000..3b35221 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public sealed class ManagerOfManager : Singleton + { + private List allManager = new(); + + public void Init() + { + foreach (var manager in allManager) + { + manager.Init(); + } + + foreach (var manager in allManager) + { + manager.StartUp(); + } + } + + public void AddManager(InterfaceManager interfaceManager) + { + if (!allManager.Contains(interfaceManager)) + { + allManager.Add(interfaceManager); + } + } + + public void DisposeAllManager() + { + foreach (var manager in allManager) + { + manager.DisposeBefore(); + } + + foreach (var manager in allManager) + { + manager.Dispose(); + } + + GeneralKit.Destroy(AppObjConst.MonoManagerGo); + allManager.Clear(); + } + + public override void Dispose() + { + base.Dispose(); + allManager.Clear(); + allManager = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs.meta new file mode 100644 index 0000000..ce7b9d3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/ManagerOfManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6a04b8a543c2964ab598fc4296d0c70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager.meta b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager.meta new file mode 100644 index 0000000..6a738c4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0a1d55654313a544b99ae81d86cf0e39 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs new file mode 100644 index 0000000..338d8f1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs @@ -0,0 +1,317 @@ +using FairyGUI; +using UnityEngine; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnityEngine.Events; + +namespace ScrewsMaster +{ + public sealed class AudioManager : BaseUnityManager + { + public const bool IsUnscaleTime = true; + private Dictionary audioClipCacheDict = new Dictionary(); + private GameObject newEffectSourcesRoot; + private GameObject dynamicEffectSourcesRoot; + [HideInInspector] public AudioListener audioListener; + [HideInInspector] public AudioSource bgmSource; + [HideInInspector] public AudioSource effectSource; + [HideInInspector] public List dynamicEffectSources = new List(); + [HideInInspector] public List unscaleTimeSounds = new List(); + [HideInInspector] public float currUISoundVolume = 1; + + private bool isOpenBGM; + + public bool IsOpenBGM + { + get { return isOpenBGM; } + set + { + isOpenBGM = value; + PlayerPrefsKit.WriteBool(PrefsKeyConst.AudioMgr_isOpenBGM, isOpenBGM); + if (!bgmSource) return; + + bgmSource.enabled = isOpenBGM; + if (isOpenBGM) + { + bgmSource.Play(); + } + else + { + bgmSource.Pause(); + } + } + } + + private bool isOpenEffect; + + public bool IsOpenEffect + { + get { return isOpenEffect; } + set + { + isOpenEffect = value; + PlayerPrefsKit.WriteBool(PrefsKeyConst.AudioMgr_isOpenEffect, isOpenEffect); + + + GRoot.inst.soundVolume = isOpenEffect ? currUISoundVolume : 0f; + if (isOpenEffect) + { + GRoot.inst.EnableSound(); + } + else + { + GRoot.inst.DisableSound(); + } + } + } + + private void InitAudioMode() + { + isOpenBGM = PlayerPrefsKit.ReadBool(PrefsKeyConst.AudioMgr_isOpenBGM, true); + isOpenEffect = PlayerPrefsKit.ReadBool(PrefsKeyConst.AudioMgr_isOpenEffect, true); + + GRoot.inst.soundVolume = 1; + currUISoundVolume = GRoot.inst.soundVolume; + GRoot.inst.soundVolume = isOpenEffect ? currUISoundVolume : 0f; + } + + public override void Init() + { + base.Init(); + AppDispatcher.Instance.AddListener(AppMsg.TimeScale_Change, OnTimeScaleChange); + + audioListener = gameObject.AddComponent(); + + bgmSource = gameObject.AddComponent(); + bgmSource.playOnAwake = false; + bgmSource.loop = true; + + effectSource = gameObject.AddComponent(); + effectSource.playOnAwake = false; + effectSource.loop = false; + + newEffectSourcesRoot = new GameObject("NewEffectSources"); + newEffectSourcesRoot.transform.SetParent(gameObject.transform, false); + dynamicEffectSourcesRoot = new GameObject("DynamicEffectSources"); + dynamicEffectSourcesRoot.transform.SetParent(gameObject.transform, false); + + InitAudioMode(); + } + + public override void Dispose() + { + base.Dispose(); + AppDispatcher.Instance.RemoveListener(AppMsg.TimeScale_Change, OnTimeScaleChange); + } + + public void InitDefaultButtonClickSound(string btnSound) + { + string defaultSound = AudioConst.UIButtonDefault; + if (!string.IsNullOrEmpty(btnSound)) + { + defaultSound = btnSound; + } + + LoadKit.Instance.LoadAudio("Audio", defaultSound, audioClip => + { + if (audioClip != null) + { + UIConfig.buttonSound = new NAudioClip(audioClip); + UIConfig.buttonSoundVolumeScale = 1; + } + }); + } + + private void OnTimeScaleChange(object value) + { + if (unscaleTimeSounds.Count != 0) + { + for (int i = 0; i < unscaleTimeSounds.Count; i++) + { + AudioSource audioSource = unscaleTimeSounds[i]; + if (audioSource) + { + audioSource.pitch = 1; + } + } + } + } + + public void PlayBGM(string audioName, bool isUnscaleTime = IsUnscaleTime) + { + if (string.IsNullOrEmpty(audioName)) return; + + string curName = bgmSource.clip == null ? null : bgmSource.clip.name; + + if (curName != audioName) + { + AudioClip currClip = null; + if (audioClipCacheDict.TryGetValue(audioName, out var value)) + { + currClip = value; + } + else + { + try + { + currClip = LoadKit.Instance.LoadAsset("Audio", audioName); + } + catch (System.Exception) + { + } + } + + + if (currClip != null) + { + bgmSource.clip = currClip; + if (!isOpenBGM) + { + return; + } + + if (isUnscaleTime) + { + if (!unscaleTimeSounds.Contains(bgmSource)) + { + unscaleTimeSounds.Add(bgmSource); + } + } + else + { + if (unscaleTimeSounds.Contains(bgmSource)) + { + unscaleTimeSounds.Remove(bgmSource); + } + } + + bgmSource.pitch = isUnscaleTime ? 1 : Time.timeScale; + bgmSource.Play(); + } + } + } + + public AudioSource PlayDynamicEffect(string audioName, float delay = 0, bool isLoop = false, + bool isUnscaleTime = IsUnscaleTime) + { + if (!isOpenEffect || string.IsNullOrEmpty(audioName)) return null; + + AudioSource effectSourceCom = null; + for (int i = 0; i < dynamicEffectSources.Count; i++) + { + AudioSource sourceItem = dynamicEffectSources[i]; + if (!sourceItem.isPlaying) + { + effectSourceCom = sourceItem; + break; + } + } + + if (effectSourceCom == null) + { + effectSourceCom = dynamicEffectSourcesRoot.AddComponent(); + effectSourceCom.playOnAwake = false; + dynamicEffectSources.Add(effectSourceCom); + } + + if (effectSourceCom.loop != isLoop) + { + effectSourceCom.loop = isLoop; + } + + + string curName; + AudioClip currClip = null; + if (effectSourceCom.clip == null) + { + curName = null; + } + else + { + currClip = effectSourceCom.clip; + curName = currClip.name; + } + + var playAction = new UnityAction(delegate + { + if (currClip != null) + { + effectSourceCom.clip = currClip; + + if (isUnscaleTime) + { + if (!unscaleTimeSounds.Contains(effectSourceCom)) + { + unscaleTimeSounds.Add(effectSourceCom); + } + } + else + { + if (unscaleTimeSounds.Contains(effectSourceCom)) + { + unscaleTimeSounds.Remove(effectSourceCom); + } + } + + effectSourceCom.pitch = + isUnscaleTime ? 1 : Time.timeScale; + if (delay == 0) + { + effectSourceCom.Play(); + } + else + { + effectSourceCom.PlayDelayed(delay); + } + } + }); + + if (curName != audioName) + { + if (audioClipCacheDict.ContainsKey(audioName)) + { + currClip = audioClipCacheDict[audioName]; + playAction(); + } + else + { + var path = new StringBuilder("Audio"); + var strs = audioName.Split('.'); + var assetName = strs.Last(); + if (strs.Length > 1) + { + var assetUrl = audioName.Replace($".{assetName}", string.Empty); + path.Append(".").Append(assetUrl); + } + + LoadKit.Instance.LoadAudio(path.ToString(), assetName, (clip) => + { + currClip = clip; + audioClipCacheDict[audioName] = clip; + playAction(); + }); + } + } + else + { + try + { + if (delay == 0) + { + effectSourceCom.Play(); + } + else + { + effectSourceCom.PlayDelayed(delay); + } + } + catch (System.Exception) + { + } + } + + return effectSourceCom; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs.meta new file mode 100644 index 0000000..fdba94f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/AudioManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 865f04198a097e941bd87d4c2716d517 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs new file mode 100644 index 0000000..978066c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs @@ -0,0 +1,53 @@ +using System; +using UnityEngine; +using System.Collections; +using UnityEngine.SceneManagement; + +namespace ScrewsMaster +{ + public sealed class SceneSwitchManager : BaseUnityManager + { + private const bool IsUseUnityScene = false; + + public delegate void LoadCallBack(object param); + + public void SwitchInitialScene(int idx, LoadCallBack loadHandler, object param) + { + StartCoroutine(OnLoadInitialScene(idx, loadHandler, param)); + } + + public void SwitchScene(int idx, LoadCallBack loadHandler, object param) + { + StartCoroutine(OnLoadScene(idx, loadHandler, param)); + } + + private IEnumerator OnLoadInitialScene(int idx, LoadCallBack loadHandle, object param) + { + yield return YieldConst.Time10ms; + + if (loadHandle != null) + { + loadHandle(param); + } + } + + private IEnumerator OnLoadScene(int idx, LoadCallBack loadHandle, object param) + { + yield return YieldConst.WaitFor100ms; + + GC.Collect(); + GC.WaitForPendingFinalizers(); + + if (IsUseUnityScene) + { + AsyncOperation asyncUnityScene = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(idx, LoadSceneMode.Single); + yield return asyncUnityScene; + } + + if (loadHandle != null) + { + loadHandle(param); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs.meta new file mode 100644 index 0000000..1920b99 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/SceneSwitchManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6503fa22efaefd542a68eccaa2f4e790 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs new file mode 100644 index 0000000..9ffb4e9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public enum TimerTimeType : int + { + Null = -1, + Time = 0, + UnscaledTime = 1, + RealtimeSinceStartup = 2, + } + + public sealed class TimerIManager : BaseUnityManager + { + private GameObject simpleTimersRoot; + private GameObject timersRoot; + private GameObject heavyTimersRoot; + + private void InitTimersRoot() + { + simpleTimersRoot = new GameObject("SimpleTimers"); + simpleTimersRoot.SetParent(gameObject); + + timersRoot = new GameObject("Timers"); + timersRoot.SetParent(gameObject); + + heavyTimersRoot = new GameObject("HeavyTimers"); + heavyTimersRoot.SetParent(gameObject); + } + + public EasyTimer CreateSimpleTimer(string name, TimerTimeType type) + { + EasyTimer easyTimer = simpleTimersRoot.AddComponent(); + easyTimer.SetTimer(name, type); + return easyTimer; + } + + public Timer CreateTimer(string name, TimerTimeType type) + { + Timer timer = timersRoot.AddComponent(); + timer.SetTimer(name, type); + return timer; + } + + #region Mgr + + public override void Init() + { + base.Init(); + InitTimersRoot(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs.meta new file mode 100644 index 0000000..3bc5560 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/TimerIManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f02ecdb607607114abbe6750658a9225 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs new file mode 100644 index 0000000..659e0bb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs @@ -0,0 +1,886 @@ +using System; +using FairyGUI; +using System.IO; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.EventSystems; +using System.Collections.Generic; +using System.Linq; + +namespace ScrewsMaster +{ + public class UISequenceInfo + { + public BaseUI ui; + public object args; + public bool isLaunch; + } + + public class UIParentInfo + { + public GComponent parent; + public int index; + } + + public static class UIMgrConst + { + public static bool IsEnableOpenUIAnim = true; + public static bool IsEnableCloseUIAnim = true; + public static Vector2 OpenUIAnimEffectScale = new Vector2(0.8f, 0.8f); + public static float OpenUIAnimEffectTime = 0.3f; + public static float ClickDownAnimEffectScale = 0.9f; + } + + public sealed class UIManager : BaseUnityManager + { + private const bool IsUseSafeAreaAdaptive = false; + private const bool IsSetButtonPivotCenter = false; + + private GameObject eventSystemGo; + private EventSystem eventSystem; + private StandaloneInputModule inputModule; + + private string uiDefaultFontName; + private List commonPackageList = new List(); + private Queue uiMaskCacheQueue = new Queue(); + private Dictionary tempGObjectParentDict = new Dictionary(); + + private Dictionary uiLayerWindowDict = new Dictionary(); + private List existDynamicUIs = new List(); + private List tickUpdateUIs = new List(); + private List normalUIRecord = new List(); + + private List uiSequenceQueue = new List(); + private ObjectPool uiSequencePool = new ObjectPool(); + + private Vector2 uiCenterPos; + private uint currUIOpenCumsumId; + private int closeWorldRaycastRefCount; + + public void RegisterCommonPackage(string commonPackage) + { + if (!commonPackageList.Contains(commonPackage)) + { + commonPackageList.Add(commonPackage); + } + } + + public void RegisterCommonPackages(List commonPackages) + { +#if UNITY_EDITOR + if (!UnityEngine.Application.isPlaying) + { + for (int i = 0; i < commonPackages.Count; i++) + { + string pakName = commonPackages[i]; + if (UIPackage.GetByName(pakName) == null) + { + string packagePath = GetPackageUIPath(pakName); + UIPackage.AddPackage(packagePath); + } + } + + return; + } +#endif + for (int i = 0; i < commonPackages.Count; i++) + { + RegisterCommonPackage(commonPackages[i]); + } + } + + public void RegisterDefaultFont(string defaultFontName) + { + uiDefaultFontName = defaultFontName; + + LoadKit.Instance.LoadAsset("Font", defaultFontName, (font) => + { + if (font != null) + { + FontManager.RegisterFont(new DynamicFont(defaultFontName, font), defaultFontName); + InitFguiConfig(); + } + }); + } + + public void RegisterFont(params string[] otherFontNames) + { + for (int i = 0; i < otherFontNames.Length; i++) + { + string fontName = otherFontNames[i]; + LoadKit.Instance.LoadAsset("Font", fontName, (font) => + { + if (font != null) + { + FontManager.RegisterFont(new DynamicFont(fontName, font), fontName); + } + }); + } + } + + public void DisposeAllUI() + { + while (existDynamicUIs != null && existDynamicUIs.Count != 0) + { + BaseUI ui = existDynamicUIs[existDynamicUIs.Count - 1]; + Internal_CloseUI(ui, true); + } + + UIPackage.RemoveAllPackages(); + } + + public void SwitchSceneCloseAllUI() + { + for (int i = existDynamicUIs.Count - 1; i >= 0; i--) + { + if (existDynamicUIs.Count == 0) return; + + if (i >= existDynamicUIs.Count) + { + i = existDynamicUIs.Count; + } + + BaseUI ui = existDynamicUIs[i]; + if (ui.uiInfo.isSwitchSceneCloseUI) + { + Internal_CloseUI(ui); + } + } + } + + public void Internal_OpenUI(BaseUI ui, object args = null) + { + if (!IsStartUp) return; + + LoadUI(ui, args, OpenUIProcess); + } + + private void OpenUIProcess(BaseUI ui, object args) + { + existDynamicUIs.Add(ui); + + ui.Process_Bind(); + ui.Process_OpenBefore(args); + ui.Process_Open(args); + + AddNormalBaseUI(ui); + NotificationEvent(AppMsg.UIEvent_UIOpen, ui); + + if (ui.uiInfo.isTickUpdate) + { + tickUpdateUIs.Add(ui); + } + + if (ui.uiInfo.isClosetWorldRaycast) + { + SetWorldRaycasterEnabled(false); + } + + if (UIMgrConst.IsEnableOpenUIAnim && ui.uiInfo.isNeedOpenAnim) + { + ui.KillOpenUIAnim(); + OpenUIAnim(ui); + } + } + + public void Internal_CloseUI(BaseUI ui, bool isImmediatelyDispose = false) + { + if (existDynamicUIs.Contains(ui)) + { + existDynamicUIs.Remove(ui); + RemoveNormalBaseUI(ui); + + if (ui.uiInfo.isTickUpdate) + { + tickUpdateUIs.Remove(ui); + } + + ui.Process_Close(); + + if (UIMgrConst.IsEnableOpenUIAnim && ui.uiInfo.isNeedOpenAnim) + { + ui.KillOpenUIAnim(); + } + + if (UIMgrConst.IsEnableCloseUIAnim && ui.uiInfo.isNeedCloseAnim) + { + ui.KillCloseUIAnim(); + CloseUIAnim(ui, () => DestroyUI(ui, isImmediatelyDispose)); + } + else + { + DestroyUI(ui, isImmediatelyDispose); + } + } + } + + public void Internal_HideUI(BaseUI ui) + { + ui.Process_Hide(); + NotificationEvent(AppMsg.UIEvent_UIHide, ui); + } + + public void Internal_DisplayUI(BaseUI ui, object args = null) + { + ui.Process_Display(args); + NotificationEvent(AppMsg.UIEvent_UIDisplay, ui); + } + + private void Update() + { + if (tickUpdateUIs.Count <= 0) return; + + for (int i = tickUpdateUIs.Count - 1; i >= 0; i--) + { + BaseUI ui = tickUpdateUIs[i]; + if (ui == null) continue; + if (ui.isClose) continue; + if (!ui.uiInfo.isTickUpdate) continue; + + ui.OnUpdate(); + } + } + + private void LoadUI(BaseUI ui, object args, Action completeFunc) + { + AddUIPackage(ui.uiInfo.packageName, () => { CreateUI(ui, args, completeFunc); }); + } + + private void CreateUI(BaseUI ui, object args, Action completeFunc) + { + if (string.IsNullOrEmpty(ui.uiName)) + { + return; + } + + GObject gObject = UIPackage.CreateObject(ui.uiInfo.packageName, ui.uiInfo.assetName); + + string rawGoName = gObject.gameObjectName; + string uiGoName = string.Format("({0}){1}", ui.uiName, rawGoName); + gObject.gameObjectName = uiGoName; + gObject.displayObject.name = uiGoName; + + ui.baseGObj = gObject; + ui.baseUI = ui.baseGObj.asCom; + + ui.baseUI.fairyBatching = true; + + ui.baseUI.name = rawGoName; + ui.rawGameObjectName = rawGoName; + ui.gameObjectName = uiGoName; + + ui.baseUI.MakeFullScreen(); + ui.baseUI.SetSize(GRoot.inst.width, GRoot.inst.height, false); + if (IsUseSafeAreaAdaptive) + { + Rect safeArea = Screen.safeArea; + ui.baseUI.SetPivot(0.5f, 0.5f, false); + ui.baseUI.SetSize(GRoot.inst.width, GRoot.inst.height - (Screen.height - safeArea.height), false); + // ui.baseUI.y = GRoot.inst.height - safeArea.height; + // ui.baseUI.y = ui.baseUI.y + (Screen.height - safeArea.height) * 0.5f; + } + + SetButtonClickDownEffect(ui.baseUI); + + if (ui.uiInfo.gComType == UIGComType.Window) + { + Window gWindowUI = new Window(); + gWindowUI.contentPane = ui.baseUI; + ui.windowUI = gWindowUI; + ui.windowUI.fairyBatching = true; + ui.windowUI.Show(); + } + + if (ui.uiInfo.isNeedUIMask) + { + GGraph uiMask = CreateUIMask(ui.uiInfo.uiMaskCustomColor); + ui.uiMask = uiMask; + ui.baseUI.AddChildAt(ui.uiMask, 0); + if (ui.uiInfo.isNeedUIMaskCloseEvent) + { + ui.uiMask.onClick.Add(ui.CtrlCloseUI); + } + } + + ui.uiOpenCumsumId = ++currUIOpenCumsumId; + ui.currLayer = (int)ui.uiInfo.layerType; + uiLayerWindowDict[ui.currLayer].AddChild(ui.baseUI); + completeFunc(ui, args); + } + + private void AddUIPackage(string packageName, UnityAction onCompleted = null) + { + if (UIPackage.GetByName(packageName) == null) + { + //if (packageName.Contains("CS608_loading") || packageName.Contains("A001_bigImg")) + //{ + // var resUIPath = Path.Combine("FGUI", packageName); + // UIPackage.AddPackage(resUIPath); + // onCompleted?.Invoke(); + //} + //else + //{ + LoadKit.Instance.LoadAsset("FGUI", $"{packageName}_fui.bytes", textAsset => + { + UIPackage.AddPackage(textAsset.bytes, packageName, + delegate (string s, string extension, Type type, out DestroyMethod destroyMethod) + { + destroyMethod = DestroyMethod.Unload; + return LoadKit.Instance.LoadAsset("FGUI", $"{s}{extension}"); + }); + onCompleted?.Invoke(); + }); + //} + } + else + { + onCompleted?.Invoke(); + } + } + + private string GetPackageUIPath(string packageName) + { + return string.Format("FGUI/{0}", packageName); + } + + private void SetButtonClickDownEffect(GComponent gComponent) + { + GObject[] gObjects = gComponent.GetChildren(); + for (int i = 0; i < gObjects.Length; i++) + { + GObject gObject = gObjects[i]; + GButton gButton = gObject.asButton; + if (gButton != null && gButton.mode == ButtonMode.Common) + { + if (!gButton.name.StartsWith("obtn_")) + { + if (IsSetButtonPivotCenter) + { + gButton.SetPivot(0.5f, 0.5f, false); + } + + gButton.SetClickDownEffect(UIMgrConst.ClickDownAnimEffectScale); + } + + continue; + } + + GComponent otherGComponent = gObject.asCom; + if (otherGComponent != null) + { + SetButtonClickDownEffect(otherGComponent); + continue; + } + } + } + + private GGraph CreateUIMask(Color color) + { + GGraph uiMask = null; + if (uiMaskCacheQueue.Count > 0) + { + uiMask = GetUIMaskFormPool(); + uiMask.color = color; + uiMask.visible = true; + } + else + { + uiMask = new GGraph(); + uiMask.gameObjectName = "UIMask"; + uiMask.name = uiMask.gameObjectName; + + uiMask.SetPivot(0.5f, 0.5f, true); + uiMask.SetXY(uiCenterPos.x, uiCenterPos.y); + uiMask.DrawRect(5000, 5000, 0, Color.black, color); + } + + return uiMask; + } + + private GGraph GetUIMaskFormPool() + { + if (uiMaskCacheQueue.Count == 0) return null; + return uiMaskCacheQueue.Dequeue(); + } + + private void ReleaseUIMaskToPool(BaseUI ui) + { + if (ui.uiMask == null) return; + + GGraph uiMask = ui.uiMask; + ui.baseUI.RemoveChild(uiMask); + ui.uiMask = null; + + uiMask.onClick.Clear(); + uiMask.visible = false; + uiMaskCacheQueue.Enqueue(uiMask); + } + + private void DestroyUI(BaseUI ui, bool isImmediatelyDispose) + { + if (ui.uiInfo.isNeedUIMask) + { + ReleaseUIMaskToPool(ui); + } + + if (ui.uiInfo.isClosetWorldRaycast) + { + SetWorldRaycasterEnabled(true); + } + + CloseAllSubUI(ui); + DisposeUI(ui); + ui.Process_Destroy(); + NotificationEvent(AppMsg.UIEvent_UIClose, ui); + + QuitUISequence(ui); + UnloadAsset(ui.uiInfo.packageName, ui.uiInfo.assetName); + } + + private void UnloadAsset(string packageName, string assetName) + { + if (UIPackage.GetByName(packageName) != null) + { + LoadKit.Instance.RecycleAsset(packageName); + } + } + + private void DisposeUI(BaseUI ui) + { + uiLayerWindowDict[ui.currLayer].RemoveChild(ui.baseUI); + if (ui.uiInfo.gComType == UIGComType.Window) + { + if (ui.windowUI != null) + { + ui.windowUI.Dispose(); + ui.windowUI = null; + } + } + + ui.baseUI.Dispose(); + ui.baseUI = null; + } + + private void NotificationEvent(uint msgId, BaseUI ui) + { + AppDispatcher.Instance.Dispatch(msgId, ui); + } + + private void OpenUIAnim(BaseUI ui) + { + GObject gObj = ui.baseUI; + gObj.pivot = VectorConst.Half; + gObj.SetScale(UIMgrConst.OpenUIAnimEffectScale.x, UIMgrConst.OpenUIAnimEffectScale.y); + ui.openUiGTweener = gObj.TweenScale(Vector3.one, UIMgrConst.OpenUIAnimEffectTime).OnComplete(() => + { + ui.openUiGTweener = null; + ui.Process_OpenUIAnimEnd(); + }).SetIgnoreEngineTimeScale(true).SetEase(EaseType.BackOut); + } + + private void CloseUIAnim(BaseUI ui, Action animEndCB) + { + GObject gObj = ui.baseUI; + ui.closeUiGTweener = gObj.TweenScale(UIMgrConst.OpenUIAnimEffectScale, UIMgrConst.OpenUIAnimEffectTime) + .OnComplete(() => + { + ui.Process_CloseUIAnimEnd(); + animEndCB(); + }).SetIgnoreEngineTimeScale(true).SetEase(EaseType.BackIn); + } + + private void SetWorldRaycasterEnabled(bool enabled) + { + if (enabled) + { + closeWorldRaycastRefCount--; + } + else + { + closeWorldRaycastRefCount++; + } + + if (closeWorldRaycastRefCount > 0) + { + CameraManager.Instance.SetWorldRaycasterEnabled(false); + } + else + { + CameraManager.Instance.SetWorldRaycasterEnabled(true); + } + } + + + public BaseUI GetDynamicUI(string uiName) + { + foreach (BaseUI ui in existDynamicUIs) + { + if (ui.uiName == uiName) + { + return ui; + } + } + + return null; + } + + public bool IsExistUI(string uiName) + { + foreach (BaseUI ui in existDynamicUIs) + { + if (ui.uiName == uiName) + { + return true; + } + } + + return false; + } + + public void SetGObjectUILayer(UILayerType toLayer, params GObject[] objs) + { + foreach (GObject item in objs) + { + if (item.parent != null) + { + GComponent defaultParent = item.parent; + int idx = defaultParent.GetChildIndex(item); + + if (!tempGObjectParentDict.ContainsKey(item)) + { + tempGObjectParentDict.Add(item, new UIParentInfo() + { + parent = defaultParent, + index = idx, + }); + } + } + + uiLayerWindowDict[(int)toLayer].AddChild(item); + + Vector2 pos = item.LocalToRoot(Vector2.zero, GRoot.inst); + item.position = pos; + } + } + + public void ResetGObjectUILayer(params GObject[] objs) + { + foreach (GObject item in objs) + { + if (tempGObjectParentDict.ContainsKey(item)) + { + UIParentInfo parentInfo = tempGObjectParentDict[item]; + int itemIndex = parentInfo.index; + int parentCount = parentInfo.parent.GetChildrenCount(); + if (parentCount != 0 && parentCount >= itemIndex) + { + parentInfo.parent.AddChildAt(item, itemIndex); + } + else + { + parentInfo.parent.AddChild(item); + } + + + Vector2 pos = parentInfo.parent.RootToLocal(item.position, GRoot.inst); + item.position = pos; + + tempGObjectParentDict.Remove(item); + } + } + } + + public bool AddNormalBaseUI(BaseUI ui) + { + if (ui.uiInfo.layerType != UILayerType.Normal) return false; + BaseUI nowUI = GetNowBaseUI(); + if (nowUI == null) + { + normalUIRecord.Add(ui); + return true; + } + + + if (ui.uiInfo.packageName == nowUI.uiInfo.packageName && + ui.uiInfo.assetName == nowUI.uiInfo.assetName) return false; + + normalUIRecord.Add(ui); + + return true; + } + + public bool RemoveNormalBaseUI(BaseUI ui) + { + if (ui.uiInfo.layerType != UILayerType.Normal) return false; + + + { + normalUIRecord.Remove(ui); + return true; + } + } + + public BaseUI GetNowBaseUI() + { + if (normalUIRecord.Count > 0) + { + return normalUIRecord[normalUIRecord.Count - 1]; + } + + return null; + } + + private void ExecuteOpenUISequence() + { + if (uiSequenceQueue.Count == 0) return; + + UISequenceInfo sequenceInfo = uiSequenceQueue[0]; + if (sequenceInfo.isLaunch) return; + + sequenceInfo.isLaunch = true; + BaseUI ui = sequenceInfo.ui; + ui.Open(sequenceInfo.args); + } + + private void QuitUISequence(BaseUI ui) + { + if (uiSequenceQueue.Count == 0) return; + + UISequenceInfo sequenceInfo = uiSequenceQueue[0]; + if (sequenceInfo.ui != ui) return; + + uiSequenceQueue.Remove(sequenceInfo); + uiSequencePool.Release(sequenceInfo); + ExecuteOpenUISequence(); + } + + public void CloseSubUI(BaseUI mainUI, SubUI subUI) + { + mainUI.subUIs.Remove(subUI); + mainUI.baseUI.RemoveChild(subUI.baseGObj); + + subUI.baseUI.Dispose(); + subUI.baseUI = null; + } + + public void CloseAllSubUI(BaseUI mainUI) + { + List subUIs = mainUI.subUIs; + if (subUIs == null) return; + for (int i = subUIs.Count - 1; i >= 0; i--) + { + CloseSubUI(mainUI, subUIs[i]); + } + + mainUI.subUIs.Clear(); + mainUI.subUIs = null; + } + + private void InitUIMgr() + { + GameObject uiRootParent = new GameObject(AppObjConst.UIGoName); + uiRootParent.layer = LayerMaskConst.UI; + AppObjConst.UIGo = uiRootParent; + AppObjConst.UIGo.SetParent(AppObjConst.FrameGo); + AppObjConst.UIGo.transform.position = new Vector3(CameraConst.UICameraPos.x, CameraConst.UICameraPos.y, 0); + + InitFguiConfig(); + InitFguiSettings(); + InitFguiLayers(); + + + } + + private void InitFguiConfig() + { + UIPackage.branch = null; + AppObjConst.UIGo.AddComponent(); + UIConfig.defaultFont = uiDefaultFontName; + UIConfig.enhancedTextOutlineEffect = true; + UIConfig.bringWindowToFrontOnClick = false; + UIConfig.modalLayerColor = new Color(0f, 0f, 0f, (255f / 2f) / 255f); + UIConfig.buttonSoundVolumeScale = 1; + } + + private void InitFguiSettings() + { + AppObjConst.UICacheGo = new GameObject(AppObjConst.UICacheGoName); + AppObjConst.UICacheGo.SetParent(AppObjConst.FrameGo); + + DisplayObject.CreateUICacheRoot(AppObjConst.UICacheGo.transform); + Stage.Instantiate(); + Stage.inst.gameObject.transform.SetParent(AppObjConst.UIGo.transform, false); + + Vector2Int uiResolution = AppConst.UIResolution; + GRoot.inst.SetContentScaleFactor(uiResolution.x, uiResolution.y, + UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + uiCenterPos = new Vector2(GRoot.inst.width / 2f, GRoot.inst.height / 2f); + } + + private void InitFguiLayers() + { + GRoot.inst.fairyBatching = false; + for (int i = 0; i < UILayerConst.AllUILayer.Length; i++) + { + Window uiLayerWindow = new Window(); + string name = UILayerConst.AllUILayer[i]; + uiLayerWindow.fairyBatching = false; + uiLayerWindow.name = name; + uiLayerWindow.displayObject.name = name; + uiLayerWindow.gameObjectName = uiLayerWindow.name; + uiLayerWindow.sortingOrder = i * 100; + uiLayerWindow.Show(); + uiLayerWindow.fairyBatching = false; + uiLayerWindowDict.Add(i, uiLayerWindow); + } + } + + private void InitFguiCommonPackages() + { + foreach (string commonPackage in commonPackageList) + { + Debug.Log($"Load Common Package: {commonPackage}"); + LoadKit.Instance.LoadAsset("FGUI", $"{commonPackage}_fui.bytes", + textAsset => + { + UIPackage.AddPackage(textAsset.bytes, commonPackage, + delegate (string s, string extension, Type type, out DestroyMethod destroyMethod) + { + destroyMethod = DestroyMethod.Unload; + return LoadKit.Instance.LoadAsset("FGUI", $"{s}{extension}"); + }); + }); + } + } + + private void InitFguiMultiLanguage() + { + if (AppConst.IsMultiLangue) + { + Stage.inst.currLang = AppConst.InternalLangue; + } + } + + public override void Init() + { + base.Init(); + AppDispatcher.Instance.AddListener(AppMsg.InitUIMgr, (obj) => + { + // InitReporterGo(); + InitFguiCommonPackages(); + InitFguiMultiLanguage(); + }); + InitUIMgr(); + } + + public override void DisposeBefore() + { + base.DisposeBefore(); + DisposeAllUI(); + } + + protected override void OnDestroy() + { + base.OnDestroy(); + GeneralKit.Destroy(AppObjConst.UIGo); + + commonPackageList.Clear(); + existDynamicUIs.Clear(); + tickUpdateUIs.Clear(); + commonPackageList = null; + existDynamicUIs = null; + tickUpdateUIs = null; + + uiSequencePool.Dispose(); + uiSequenceQueue.Clear(); + uiSequencePool = null; + uiSequenceQueue = null; + } + + public void SetEventSystemGo(GameObject go) + { + eventSystemGo = go; + eventSystem = eventSystemGo.GetComponent(); + inputModule = eventSystemGo.GetComponent(); + } + + public void SetSwitchLanguage(string switchLang) + { + if (AppConst.IsMultiLangue) + { + var multiLangueConfig = + LoadKit.Instance.LoadAsset("TextAsset.I18N", "#JarvisI18N"); + if (!multiLangueConfig) return; + if (string.IsNullOrWhiteSpace(multiLangueConfig.text)) return; + var multiLangueConfigList = SerializeUtil.ToObject>(multiLangueConfig.text); + if (multiLangueConfigList == null || multiLangueConfigList.Count == 0) return; + + if (string.IsNullOrWhiteSpace(switchLang)) return; + if (switchLang == Stage.inst.currLang && switchLang == AppConst.InternalLangue) return; + if (!multiLangueConfigList.Contains(switchLang)) return; + + var switchLangXML = LoadKit.Instance.LoadAsset("TextAsset.I18N", switchLang); + if (!switchLangXML) return; + if (string.IsNullOrWhiteSpace(switchLangXML.text)) return; + + var xml = new FairyGUI.Utils.XML(switchLangXML.text); + UIPackage.SetStringsSource(xml); + Stage.inst.currLang = switchLang; + + AppConst.CurrMultiLangue = switchLang; + PlayerPrefsKit.WriteObject(PrefsKeyConst.UIMgr_switchLanguage, AppConst.CurrMultiLangue); + AppDispatcher.Instance.Dispatch(AppMsg.App_SwitchLanguage); + + var uiPackageList = UIPackage.GetPackages(); + foreach (var packageItem in uiPackageList.Select(uiPackage => uiPackage.GetItems()).SelectMany( + packageItemList => packageItemList.Where(packageItem => packageItem.translated))) + { + packageItem.translated = false; + } + + for (var i = existDynamicUIs.Count - 1; i >= 0; i--) + { + var ui = existDynamicUIs[i]; + if (ui == null) continue; + if (ui.isClose) continue; + + ui.ProcessFunc_SwitchLanguage(); + } + } + } + + public void AdaptSafeArea() + { + // Rect safeArea = Screen.safeArea; + // 设置内容缩放因子 + // float scaleX = safeArea.width / Screen.width; + // float scaleY = safeArea.height / Screen.height; + // GRoot.inst.SetContentScaleFactor((int)scaleX, (int)scaleY, FairyGUI.UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + + +// 获取 UI 的显示范围 + // float topMargin = Screen.height - safeArea.yMax; + // float bottomMargin = safeArea.yMin; + // float leftMargin = safeArea.xMin; + // float rightMargin = Screen.width - safeArea.xMax; + +// 设置 FairyGUI 的 UI 边界 + // GRoot.inst.dragBounds = new Rect(topMargin, bottomMargin, rightMargin, topMargin); + // GRoot.inst.dragBounds = safeArea; + // GRoot.inst.SetContentScaleFactor(Screen.width, Screen.height, FairyGUI.UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + + + // var screenWidth = Screen.width; + // var screenHeight = Screen.height; + // GRoot.inst.SetContentScaleFactor((int)safeArea.width, (int)safeArea.height, FairyGUI.UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + // Margin margin = new Margin(); + // margin.left = (int)safeArea.xMin; + // margin.right = (int)(screenWidth - safeArea.xMax); + // margin.top = (int)safeArea.yMin; + // margin.bottom = (int)(screenHeight - safeArea.yMax); + + // GRoot.inst.margin = margin; // 设置GRoot的边距 + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs.meta b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs.meta new file mode 100644 index 0000000..e10f2bd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Manager/UnityManager/UIManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46e1248ba381a29489bc7e8d2ed09cc4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool.meta b/Assets/CrazyZoo/Runtime/Core/Pool.meta new file mode 100644 index 0000000..fa428da --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dc316eee5d74b1748a03f356e91afa19 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool.meta b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool.meta new file mode 100644 index 0000000..d8d4501 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 22593bf013269694ea57d36cc1159151 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs new file mode 100644 index 0000000..c2d8e1a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs @@ -0,0 +1,123 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class GObjectPool + { + private Transform m_prefabRoot; + private Transform m_releaseRoot; + private Transform m_getRoot; + + private Action m_onNew; + private Action m_onGet; + private Action m_onRelease; + + private List m_objects; + private GameObject m_prefab; + + public int CountAll { get; private set; } + public int CountInactive { get; private set; } + + public void Init(string prefabPath, string assetName, Transform releaseRoot = null, Transform getRoot = null) + { + m_objects = new List(); + m_prefab = LoadKit.Instance.LoadGameObject(prefabPath, assetName); + + m_prefabRoot = m_prefab.transform.parent; + m_releaseRoot = releaseRoot; + m_getRoot = getRoot; + } + + public void InitCallBack(Action onNew, Action onGet, Action onRelease) + { + m_onNew = onNew; + m_onGet = onGet; + m_onRelease = onRelease; + } + + public GameObject Get() + { + GameObject obj = null; + for (int i = m_objects.Count - 1; i >= 0; i--) + { + GameObject objItem = m_objects[i]; + if (!objItem) + { + m_objects.Remove(objItem); + CountAll--; + continue; + } + + if (!objItem.activeSelf) + { + obj = objItem; + CountInactive--; + break; + } + } + + if (obj == null) + { + obj = GeneralKit.Instantiate(m_prefab); + m_objects.Add(obj); + CountAll++; + + if (m_onNew != null) + { + m_onNew(obj); + } + } + + if (m_getRoot) + { + obj.transform.SetParent(m_getRoot, false); + } + else + { + if (m_prefabRoot) + { + obj.transform.SetParent(m_prefabRoot, false); + } + } + + if (m_onGet != null) + { + m_onGet(obj); + } + + obj.SetActive(true); + return obj; + } + + public void Release(GameObject obj) + { + if (Contains(obj)) + { + if (m_releaseRoot) + { + obj.transform.SetParent(m_releaseRoot, false); + } + + obj.SetActive(false); + CountInactive++; + + if (m_onRelease != null) + { + m_onRelease(obj); + } + } + } + + public bool Contains(GameObject obj) + { + return m_objects.Contains(obj); + } + + private void DestroyObj(GameObject obj) + { + GeneralKit.Destroy(obj.gameObject); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs.meta b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs.meta new file mode 100644 index 0000000..33cde15 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eea317353b47da1469658e1c85c9750c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs new file mode 100644 index 0000000..c31922f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class GObjectsPool + { + private Transform m_releaseRoot; + private Transform m_getRoot; + private Action m_onNew; + private Action m_onGet; + private Action m_onRelease; + + private Dictionary m_pools = new(); + + public GameObject Get(string prefabPath, string assetName) + { + var poolName = $"{prefabPath} | {assetName}"; + if (!m_pools.ContainsKey(poolName)) + { + RegisterNew(prefabPath, assetName); + } + + GObjectPool pool = m_pools[poolName]; + return pool.Get(); + } + + private void RegisterNew(string prefabPath, string assetName) + { + GObjectPool pool = new GObjectPool(); + pool.Init(prefabPath, assetName, m_releaseRoot, m_getRoot); + pool.InitCallBack(m_onNew, m_onGet, m_onRelease); + m_pools.Add($"{prefabPath} | {assetName}", pool); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs.meta b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs.meta new file mode 100644 index 0000000..8173cc0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/GObjectPool/GObjectsPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bee36af719023d5418e02e67aa18ba0f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool.meta b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool.meta new file mode 100644 index 0000000..abb4135 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ae1c8a81733497d4c8640487571d4772 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs new file mode 100644 index 0000000..63a980e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public static class ListPool + { + private static readonly ObjectPool> s_ListPool = new(null, Clear); + + private static void Clear(List l) + { + l.Clear(); + } + + public static List Get() + { + return s_ListPool.Get(); + } + + public static void Release(List toRelease) + { + s_ListPool.Release(toRelease); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs.meta b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs.meta new file mode 100644 index 0000000..c8d33f3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ListPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f2d8e7c78227e3f43bffd43d95be542d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs new file mode 100644 index 0000000..d3006e6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class ObjectPool where T : new() + { + private Stack m_Stack = new(); + + private Action m_ActionOnNew; + private Action m_ActionOnGet; + private Action m_ActionOnRelease; + + public int CountAll { get; private set; } + + public ObjectPool() + { + } + + public ObjectPool(Action actionOnGet, Action actionOnRelease) + { + m_ActionOnGet = actionOnGet; + m_ActionOnRelease = actionOnRelease; + } + + public T Get() + { + T element; + if (m_Stack.Count == 0) + { + element = new T(); + CountAll++; + + if (m_ActionOnNew != null) + { + m_ActionOnNew(element); + } + } + else + { + element = m_Stack.Pop(); + } + + if (m_ActionOnGet != null) + m_ActionOnGet(element); + + return element; + } + + public void Release(T element) + { + if (m_ActionOnRelease != null) + { + m_ActionOnRelease(element); + } + + m_Stack.Push(element); + } + + public void Dispose() + { + m_Stack.Clear(); + m_Stack = null; + + m_ActionOnNew = null; + m_ActionOnGet = null; + m_ActionOnRelease = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs.meta b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs.meta new file mode 100644 index 0000000..fcb2b74 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Pool/ObjectPool/ObjectPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a28a8a5d75b01a048af3d789b3c0f265 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/SApplication.cs b/Assets/CrazyZoo/Runtime/Core/SApplication.cs new file mode 100644 index 0000000..8a7d0dc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/SApplication.cs @@ -0,0 +1,80 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class SApplication : MonoBehaviour + { + public static bool IsAppQuit { get; private set; } + + public bool IsRestart { get; private set; } + public int RestartCount { get; private set; } + public bool IsAppFocus { get; private set; } + public bool IsAppPause { get; private set; } + public long LastFocusFlaseTime { get; private set; } + + public virtual void Init() + { + IsAppFocus = true; + } + + public virtual void Enable() + { + CreateEnvironment(); + } + + private void CreateEnvironment() + { + AppObjConst.ApplicationGo = gameObject; + AppObjConst.EngineSingletonGo = new GameObject(AppObjConst.EngineSingletonGoName); + AppObjConst.EngineSingletonGo.SetParent(AppObjConst.FrameGo); + } + + private void CloseApp() + { + if (UIManager.Instance != null) + { + UIManager.Instance.DisposeAllUI(); + } + + ModuleManager.Instance.DisposeAllModule(); + ManagerOfManager.Instance.DisposeAllManager(); + ManagerOfManager.Instance.Dispose(); + } + + private void OnApplicationFocus(bool focus) + { + IsAppFocus = focus; + if (focus) + { + AppDispatcher.Instance.Dispatch(MainThreadMsg.App_Focus_True, focus); + } + else + { + LastFocusFlaseTime = DateTimeManager.Instance.GetServerCurrTimestamp(); + AppDispatcher.Instance.Dispatch(AppMsg.App_Focus_False, focus); + } + } + + private void OnApplicationPause(bool pause) + { + IsAppPause = pause; + if (pause) + { + AppDispatcher.Instance.Dispatch(AppMsg.App_Pause_True, pause); + } + else + { + MainThreadDispatcher.Instance.Dispatch(MainThreadMsg.App_Pause_False, pause); + } + } + + private void OnApplicationQuit() + { + IsAppQuit = true; + + CloseApp(); + AppDispatcher.Instance.Dispatch(AppMsg.App_Quit); + AssetBundle.UnloadAllAssetBundles(true); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/SApplication.cs.meta b/Assets/CrazyZoo/Runtime/Core/SApplication.cs.meta new file mode 100644 index 0000000..df630f9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/SApplication.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f456d9a76e898ac4db489cb8c7fcb3b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton.meta b/Assets/CrazyZoo/Runtime/Core/Singleton.meta new file mode 100644 index 0000000..7bdc653 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 78add5b715de46640a0fb9396b85e0c7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs b/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs new file mode 100644 index 0000000..e65c971 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs @@ -0,0 +1,7 @@ +namespace ScrewsMaster +{ + public interface ISingleton + { + void OnSingletonInit(); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs.meta b/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs.meta new file mode 100644 index 0000000..bc61f32 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/ISingleton.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9ee67e6ba4fa478bb8b260f227b6cc33 +timeCreated: 1686105364 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs b/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs new file mode 100644 index 0000000..0fad8da --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs @@ -0,0 +1,34 @@ +using System; + +namespace ScrewsMaster +{ + public class Singleton : ISingleton, IDisposable where T : Singleton, new() + { + private static T mInstance; + + private static readonly object LockObject = new(); + + public static T Instance + { + get + { + lock (LockObject) + { + mInstance ??= new T(); + mInstance.OnSingletonInit(); + } + + return mInstance; + } + } + + public virtual void Dispose() + { + mInstance = null; + } + + public void OnSingletonInit() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs.meta b/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs.meta new file mode 100644 index 0000000..a1ca224 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/Singleton.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3a4250ff340d9034da1d59b2f9cffb46 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs b/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs new file mode 100644 index 0000000..0e4f70f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs @@ -0,0 +1,100 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public abstract class SingletonUnity : MonoBehaviour, ISingleton where T : SingletonUnity + { + private static T mInstance; + + public static T Instance + { + get + { + if (mInstance != null) + { + return mInstance; + } + + if (ApplicationIsQuitting) + { + return null; + } + + GameObject instanceGO = new GameObject(typeof(T).Name); + mInstance = instanceGO.AddComponent(); + SetSelfParentRoot(instanceGO, mInstance.ParentRootName); + mInstance.OnSingletonInit(); + return mInstance; + } + } + + private static bool ApplicationIsQuitting; + protected virtual string ParentRootName { get; private set; } + + private static void SetSelfParentRoot(GameObject go, string parentRootName) + { + if (!AppObjConst.EngineSingletonGo) return; + + if (parentRootName == null) + { + go.transform.SetParent(AppObjConst.EngineSingletonGo.transform, false); + } + else + { + Transform sinleonRoot = AppObjConst.EngineSingletonGo.transform; + Transform rootTF = sinleonRoot.Find(parentRootName); + if (rootTF == null) + { + GameObject rootGo = new GameObject(parentRootName); + switch (parentRootName) + { + case AppObjConst.MonoManagerGoName: + AppObjConst.MonoManagerGo = rootGo; + break; + case AppObjConst.DispatcherGoName: + AppObjConst.DispatcherGo = rootGo; + break; + case AppObjConst.LoaderGoName: + AppObjConst.LoaderGo = rootGo; + break; + } + + rootTF = rootGo.transform; + rootTF.transform.SetParent(sinleonRoot, false); + } + + go.transform.SetParent(rootTF.transform, false); + } + } + + protected virtual void New() + { + } + + public virtual void Dispose() + { + mInstance = null; + } + + protected virtual void OnDestroy() + { + mInstance = null; + } + + private void OnApplicationQuit() + { + ApplicationIsQuitting = true; + if (mInstance == null) + { + return; + } + + Destroy(mInstance.gameObject); + } + + public void OnSingletonInit() + { + mInstance.New(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs.meta b/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs.meta new file mode 100644 index 0000000..37adea1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/Singleton/SingletonUnity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 04ea3647f7ad1b4448f7ba33061ab319 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs b/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs new file mode 100644 index 0000000..fc5ee4e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs @@ -0,0 +1,190 @@ +namespace ScrewsMaster +{ + using UnityEngine; + using System.Collections; + + public class SuperApplication : SApplication + { + private static SuperApplication m_instance; + + public string attribution = "organic"; + + public static SuperApplication Instance + { + get + { + if (m_instance == null) + { + if (IsAppQuit) + { + return null; + } + + AppObjConst.ApplicationGo = new GameObject(AppObjConst.ApplicationGoName); + AppObjConst.ApplicationGo.SetParent(AppObjConst.FrameGo); + m_instance = AppObjConst.ApplicationGo.AddComponent(); + } + + return m_instance; + } + } + + public override void Init() + { + base.Init(); + if (!PlayerPrefsKit.HasKey(PrefsKeyConst.App_isNewInstall)) + { + PlayerPrefsKit.WriteInt(PrefsKeyConst.App_isNewInstall, 1); + } + + AppDispatcher.Instance.AddListener(AppMsg.AppManagerRegister, + (obj) => { AppManagerRegister.RegisterData(); }); + } + + public override void Enable() + { + base.Enable(); + + InitPlugin(); + InitAppSetting(); + + ManagerRegister.Register(); + AppManagerRegister.Register(); + ManagerRegister.RegisterData(); + + ManagerOfManager.Instance.Init(); + ModuleManager.Instance.StartUpAllModule(); + + InitSettingMode(); + StartUpGameMain(); + } + + private void OnDestroy() + { + m_instance = null; + } + + #region Enable + + private void InitPlugin() + { + DOTweenHelper.Init(); + } + + private void InitAppSetting() + { + if (!AppConst.UseInternalSetting) return; + + Physics.autoSimulation = false; + Physics.autoSyncTransforms = false; + Physics2D.simulationMode = SimulationMode2D.FixedUpdate; + Physics2D.autoSyncTransforms = false; + Debug.unityLogger.logEnabled = AppConst.IsEnabledEngineLog; + Debug.unityLogger.filterLogType = AppConst.EnabledFilterLogType; + Screen.sleepTimeout = AppConst.SleepTimeoutMode; + Application.runInBackground = AppConst.IsRunInBG; + QualitySettings.vSyncCount = 0; + QualitySettings.lodBias = 1; + QualitySettings.antiAliasing = AppConst.AntiAliasing; + Application.targetFrameRate = AppConst.HighFrameRate; + } + + private void StartUpGameMain() + { + if (!IsRestart) + { + GameIManager.Instance.InitialMain(); + } + else + { + GameIManager.Instance.EnterMain(); + } + } + + #endregion Enable + + #region SettingMode + + private void InitSettingMode() + { + if (!AppConst.UseInternalSetting) return; + InitResolutionMode(); + InitFrameRateMode(); + } + + private bool isHDMode; + private bool isHFRMode; + + private void InitResolutionMode() + { + isHDMode = PlayerPrefsKit.ReadBool(PrefsKeyConst.Application_isHDMode, true); + SetResolutionMode(isHDMode); + } + + private void InitFrameRateMode() + { + isHFRMode = PlayerPrefsKit.ReadBool(PrefsKeyConst.Application_isHFRMode, true); + SetFrameRateMode(isHFRMode); + } + + private void SetResolutionMode(bool isHDMode) + { + if (isHDMode) + { + ScreenConst.CurrResolution.x = ScreenConst.RawResolution.x * AppConst.HDHighViewScale; + ScreenConst.CurrResolution.y = ScreenConst.RawResolution.y * AppConst.HDHighViewScale; + } + else + { + ScreenConst.CurrResolution.x = ScreenConst.RawResolution.x * AppConst.HDLowViewScale; + ScreenConst.CurrResolution.y = ScreenConst.RawResolution.y * AppConst.HDLowViewScale; + } + + SetScreenResolution(ScreenConst.CurrResolution.x, ScreenConst.CurrResolution.y, true); + } + + private void SetFrameRateMode(bool isHFRMode) + { + Application.targetFrameRate = isHFRMode ? AppConst.HighFrameRate : AppConst.LowFrameRate; + + QualitySettings.vSyncCount = 0; + QualitySettings.lodBias = 1; + } + + private void SetScreenResolution(float width, float height, bool isFullScreen) + { + StartCoroutine(OnSetScreenResolution(width, height, isFullScreen)); + } + + private IEnumerator OnSetScreenResolution(float width, float height, bool isFullScreen) + { + yield return YieldConst.WaitForEndOfFrame; + var allCams = Camera.allCameras; + if (allCams == null) + { + yield break; + } + + foreach (var cam in allCams) + { + cam.enabled = false; + } + + Screen.SetResolution((int)width, (int)height, isFullScreen); + Screen.fullScreen = true; + + yield return YieldConst.WaitForEndOfFrame; + if (allCams == null) + { + yield break; + } + + foreach (var cam in allCams) + { + cam.enabled = true; + } + } + + #endregion SettingMode + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs.meta b/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs.meta new file mode 100644 index 0000000..e749363 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/SuperApplication.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e34e769b3926fa24eb9398b230d7c31b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit.meta new file mode 100644 index 0000000..01f672b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d187d59225cef3147b20b9592c42e62b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs new file mode 100644 index 0000000..aeb6f08 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs @@ -0,0 +1,121 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class AndroidKit + { + + public const string AndroidClassName = "com.unity3d.player.UnityPlayer"; + + private static string className; + private static AndroidJavaClass androidClass; + private static AndroidJavaObject androidObject; + + public static void InitAndroidObject() + { + className = AndroidClassName; + + + if (Application.platform == RuntimePlatform.Android) + { + androidClass = new AndroidJavaClass(className); + string sdkClassName = "com.unity3d.player.UnityPlayer"; + if (className.Contains(sdkClassName)) + { + androidObject = androidClass.GetStatic("currentActivity"); + } + else + { + androidObject = androidClass.GetStatic("Instance"); + if (androidObject != null) + { + androidObject.Call("init"); + } + } + } + } + + public static void CallVoidApi(string apiFunc, params object[] args) + { + try + { +#if !UNITY_EDITOR && UNITY_ANDROID + androidObject.Call(apiFunc, args); +#endif + } + catch (System.Exception) + { + } + } + + public static T CallReturnApi(string apiFunc, params object[] args) + { + try + { + return androidObject.Call(apiFunc, args); + } + catch (System.Exception) + { + return default; + } + } + + public static void webViewInit(int left, int top, int right, int bottom) + { + CallVoidApi("InitWebView", left, top, right, bottom); + } + + + protected static bool m_FirstLoadUrl = true; + + + public static void webViewLoadUrl(string url) + { + if (m_FirstLoadUrl) + { + webViewLoadUrl(int.MaxValue, url); + m_FirstLoadUrl = false; + return; + } + + webViewRefreshUrl(int.MaxValue, url, true); + } + + + public static void webViewLoadUrl(int _index, string url) + { + CallVoidApi("LoadWebView", url); + } + + + public static void webViewRefreshUrl(int _index, string url, bool isTop) + { + CallVoidApi("LoadWebView", url); + } + + + public static void webViewSetVisibility(int visibility) + { + CallVoidApi("SetWebViewShow", visibility); + } + + + public static void webViewSetLayerTop(int _index) + { + } + + + public static void webViewSetEvent(bool needEvent) + { + CallVoidApi("SetWebViewClickable", needEvent); + } + + + public static void webViewShieldEvent(int placementId, int width, int height, int left, int top) + { + CallVoidApi("SetWebViewShield", placementId, width, height, left, top); + } + + } +} + diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs.meta new file mode 100644 index 0000000..8340caf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/AndroidKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a33a5932c0aae4349a6f3da83f0d2db8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs new file mode 100644 index 0000000..6dbdc4e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs @@ -0,0 +1,83 @@ +using System.Text; +using FutureCore; +using ScrewsMaster; + +public class Base64Kit +{ + public static string Encode(string data) + { + var key = NetworkManager.DomainRelease; + var keyMD5 = MD5Kit.MD5String1(key); + var str = Base64EncodeUtil.Base64Encode(data + keyMD5); + + var bytes = Encoding.UTF8.GetBytes(str); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) + { + if (i % 2 == 0) + { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var loginData = Encoding.UTF8.GetString(bytes); + return loginData; + } + + public static string Encode(string data, bool is_google_pay = false) + { + var key = NetworkManager.DomainRelease; + if (is_google_pay) key = "com.happygames.animalteaparty"; + + var keyMD5 = MD5Kit.MD5String1(key); + var str = Base64EncodeUtil.Base64Encode(data + keyMD5); + + var bytes = Encoding.UTF8.GetBytes(str); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) + { + if (i % 2 == 0) + { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var loginData = Encoding.UTF8.GetString(bytes); + return loginData; + } + + public static string Decode(string data) + { + var bytes = Encoding.UTF8.GetBytes(data); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) + { + if (i % 2 == 0) + { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var str = Encoding.UTF8.GetString(bytes); + var str1 = Base64EncodeUtil.Base64Decode(str); + var key = NetworkManager.DomainRelease; + var keyMD5 = MD5Kit.MD5String1(key); + var result = str1.Replace(keyMD5, string.Empty); + return result; + } + public static string Decode(string data, string key) + { + var bytes = Encoding.UTF8.GetBytes(data); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) + { + if (i % 2 == 0) + { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var str = Encoding.UTF8.GetString(bytes); + var str1 = Base64EncodeUtil.Base64Decode(str); + // var key = NetworkManager.DomainRelease; + var keyMD5 = MD5Kit.MD5String1(key); + var result = str1.Replace(keyMD5, string.Empty); + return result; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs.meta new file mode 100644 index 0000000..5ab8f6c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Base64Kit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 37576943a7ef4dfb8a513089cc4fd50b +timeCreated: 1699346255 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs new file mode 100644 index 0000000..c9427ee --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs @@ -0,0 +1,85 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class CameraAdaptive : MonoBehaviour + { + private bool isOrthographic; + private float orthographicSize; + + private Camera cameraCom; + + public void DoAdaptive(bool isOrthographic, float orthographicSize) + { + this.isOrthographic = isOrthographic; + this.orthographicSize = orthographicSize; + this.cameraCom = GetComponent(); + + Adaptive(); + } + +#if UNITY_EDITOR + private float currScreenHeight; + private float currScreenWidth; + + private void Update() + { + if (currScreenHeight != Screen.height || currScreenWidth != Screen.width) + { + currScreenHeight = Screen.height; + currScreenWidth = Screen.width; + ScreenConst.CurrAspectRatio = (float)Screen.height / Screen.width; + Adaptive(); + } + } +#endif + + private void Adaptive() + { + if (cameraCom == null) return; + + cameraCom.orthographic = isOrthographic; + if (isOrthographic) + { + if (ScreenConst.CurrAspectRatio > ScreenConst.StandardAspectRatio) + { + float computeHeight = Screen.width * ScreenConst.StandardAspectRatio; + float heightRatio = Screen.height / computeHeight; + cameraCom.orthographicSize = orthographicSize * heightRatio; + } + else + { + cameraCom.orthographicSize = orthographicSize; + } + } + else + { + float fov = Get3DFOV(); + cameraCom.fieldOfView = fov; + } + } + + private float Get3DFOV() + { + float defaultFOV = 60; + float standardWidth = ScreenConst.StandardWidth; + float standardHeight = ScreenConst.StandardHeight; + float currWidth = Screen.width; + float currHeight = Screen.height; + float nowHeight; + + if (ScreenConst.CurrAspectRatio > ScreenConst.StandardAspectRatio) + { + nowHeight = Mathf.RoundToInt(standardWidth / currWidth * currHeight); + } + else + { + nowHeight = standardHeight; + } + + float heightScale = nowHeight / standardHeight; + float fov = defaultFOV * heightScale; + return fov; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs.meta new file mode 100644 index 0000000..9b3706b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/CameraAdaptive.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c34ee27814511ae4e9278c1978c55d11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs new file mode 100644 index 0000000..552800a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs @@ -0,0 +1,41 @@ +using UnityEngine; +using UnityEngine.EventSystems; + +namespace ScrewsMaster +{ + public class EngineEventSystem : MonoBehaviour + { + public static EngineEventSystem Instance { get; private set; } + + [HideInInspector] public GameObject eventObj; + [HideInInspector] public EventSystem eventSystem; + [HideInInspector] public StandaloneInputModule inputModule; + + private void Awake() + { + Instance = this; + DontDestroyOnLoad(gameObject); + + Init(); + } + + private void OnDestroy() + { + Instance = null; + } + + private void Init() + { + LoadKit.Instance.LoadGameObjectAndClone("Prefab", "EngineEventSystem", eventObj1 => + { + eventObj = eventObj1; + eventObj.transform.SetParent(transform, false); + eventSystem = eventObj.GetComponent(); + inputModule = eventObj.GetComponent(); + AppObjConst.EngineEventSystemGo = Instance.eventObj.transform.parent.gameObject; + AppObjConst.EngineEventSystemGo.name = AppObjConst.EngineEventSystemGoName; + UIManager.Instance.SetEventSystemGo(eventObj); + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs.meta new file mode 100644 index 0000000..a8181f4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/EngineEventSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 441822cef8fef8d439736a08304713e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs new file mode 100644 index 0000000..335ef8d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs @@ -0,0 +1,23 @@ +using UnityEngine.EventSystems; + +namespace ScrewsMaster +{ + public static class EventKit + { + public static void Set2DRaycasterEnabled(Physics2DRaycaster com, bool enabled) + { + if (com.enabled != enabled) + { + com.enabled = enabled; + } + } + + public static void Set3DRaycasterEnabled(PhysicsRaycaster com, bool enabled) + { + if (com.enabled != enabled) + { + com.enabled = enabled; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs.meta new file mode 100644 index 0000000..02793f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/EventKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f8abc2dbceeabe47a4ad3b9e9748f89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs new file mode 100644 index 0000000..6b8fd8a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs @@ -0,0 +1,25 @@ +using UObject = UnityEngine.Object; + +namespace ScrewsMaster +{ + public static class GeneralKit + { + #region Engine + + public static T Instantiate(T original) where T : UObject + { + T obj = UObject.Instantiate(original); + return obj; + } + + public static void Destroy(UObject obj) + { + if (obj) + { + UObject.Destroy(obj); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs.meta new file mode 100644 index 0000000..30a05e1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18cfc4767ce56ed429bc8ac74bbd0a72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.meta new file mode 100644 index 0000000..ffe1b09 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 93c4fa506ccad6b4db60f2d5b9e55ffd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs new file mode 100644 index 0000000..400b1f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs @@ -0,0 +1,49 @@ +using System; +using Newtonsoft.Json; + +public static class SerializeUtil +{ + static SerializeUtil() + { + JsonConvert.DefaultSettings = new Func(() => { return DefaultUseJsonSettings; }); + } + + private static JsonSerializerSettings DefaultUseJsonSettings = new JsonSerializerSettings + { + Formatting = Formatting.None, + DateFormatHandling = DateFormatHandling.MicrosoftDateFormat, + DateFormatString = "yyyy/MM/dd hh:mm:ss", + }; + + private static JsonSerializerSettings JsonIndentedSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.MicrosoftDateFormat, + DateFormatString = "yyyy/MM/dd hh:mm:ss", + }; + + public static string ToJson(object obj) + { + return JsonConvert.SerializeObject(obj, DefaultUseJsonSettings); + } + + public static string ToJsonIndented(object obj) + { + return JsonConvert.SerializeObject(obj, JsonIndentedSettings); + } + + public static string ToJson(object obj, Type type) + { + return JsonConvert.SerializeObject(obj, type, DefaultUseJsonSettings); + } + + public static string ToJson(object obj) + { + return ToJson(obj, typeof(T)); + } + + public static T ToObject(string json) + { + return JsonConvert.DeserializeObject(json); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs.meta new file mode 100644 index 0000000..69f9b66 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/SerializeUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 094e748a04f77844d960e9e2d87e6559 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs new file mode 100644 index 0000000..53896b6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class TaskSequence + { + public Action onFinish; + private List taskList; + private bool isCancel = false; + + public int Count => taskList.Count; + + public TaskSequence Add(Action taskFunc) + { + TaskProcedure task = new TaskProcedure(); + task.taskSequence = this; + task.onTaskFunc = taskFunc; + taskList.Add(task); + return this; + } + + public TaskSequence Add(bool result, Action trueTaskFunc) + { + if (!result) return this; + return Add(trueTaskFunc); + } + + public TaskSequence Run() + { + if (isCancel) + return null; + for (int i = 0; i < taskList.Count - 1; i++) + { + int index = i; + int nextIndex = index + 1; + taskList[index].onComplete = () => taskList[nextIndex].onTaskFunc(taskList[nextIndex]); + } + + if (taskList.Count > 0) + { + taskList[taskList.Count - 1].onComplete = onFinish; + taskList[0].onTaskFunc(taskList[0]); + } + + return this; + } + + public TaskSequence Clear() + { + onFinish = null; + if (taskList != null) + { + foreach (TaskProcedure task in taskList) + { + task?.Dispose(); + } + + taskList.Clear(); + } + else + { + taskList = new List(); + } + + return this; + } + } + + public class TaskProcedure + { + public TaskSequence taskSequence; + public Action onTaskFunc; + public Action onComplete; + + public void InvokeComplete() + { + if (onComplete != null) + { + onComplete(); + } + } + + public void Dispose() + { + taskSequence = null; + onTaskFunc = null; + onComplete = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs.meta new file mode 100644 index 0000000..ce05d95 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/TaskSequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa7436b18ddf94d44b141a67425a0759 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer.meta new file mode 100644 index 0000000..9e4dc40 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8f071f4f98482cb4ea09fbf4ed3bbfe4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs new file mode 100644 index 0000000..807a643 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs @@ -0,0 +1,78 @@ +using System; +using System.Linq; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class EasyTimer : MonoBehaviour + { + private Dictionary mIntervalDic = new(); + private List triggers = new(); + + [SerializeField] private string timerName; + private TimerTimeType type = TimerTimeType.Null; + + public void SetTimer(string name, TimerTimeType type) + { + this.timerName = name + "_" + type; + this.type = type; + } + + private float GetTime() + { + return type switch + { + TimerTimeType.Time => Time.time, + TimerTimeType.UnscaledTime => Time.unscaledTime, + TimerTimeType.RealtimeSinceStartup => Time.realtimeSinceStartup, + _ => 0 + }; + } + + private void Update() + { + if (mIntervalDic.Count > 0) + { + triggers.Clear(); + foreach (var keyValue in mIntervalDic.Where(keyValue => keyValue.Value <= GetTime())) + { + triggers.Add(keyValue.Key); + } + + foreach (var func in triggers) + { + mIntervalDic.Remove(func); + func(); + } + } + } + + public void AddTimer(float interval, Action func) + { + if (null != func) + { + if (interval <= 0) + { + func(); + return; + } + + mIntervalDic[func] = GetTime() + interval; + } + } + + public void ClearAll() + { + mIntervalDic.Clear(); + triggers.Clear(); + } + + private void OnDestroy() + { + ClearAll(); + mIntervalDic = null; + triggers = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs.meta new file mode 100644 index 0000000..50ce666 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/EasyTimer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cccc8c2ef81a9c04c99cc97fdf07a8a2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs new file mode 100644 index 0000000..829428a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs @@ -0,0 +1,157 @@ +using System; +using System.Linq; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class NormalTimer : MonoBehaviour + { + private class TimerTask + { + private NormalTimer mNormalTimer; + + private string name; + private TimerMode mode; + private float startTime; + private float duration; + + private bool isBreak = false; + private float breakStart; + private float breakDuration = 0; + + private Action timerEvent; + private Action timerArgsEvent; + private object[] args = null; + + public float TimeLeft => Mathf.Max(0f, duration - (mNormalTimer.GetTime() - startTime) + breakDuration); + + public void Run() + { + if (isBreak) + { + return; + } + + if (TimeLeft > 0f) + { + return; + } + + if (mode == TimerMode.Normal) + { + mNormalTimer.RemoveTimer(name); + } + else + { + startTime = mNormalTimer.GetTime(); + breakDuration = 0; + } + + timerEvent?.Invoke(); + timerArgsEvent?.Invoke(args); + } + + public static implicit operator bool(TimerTask timerTask) + { + return null != timerTask; + } + } + + private enum TimerMode + { + Normal, + Repeat, + } + + private Dictionary addTimerList = new(); + private Dictionary timerList = new(); + private List destroyTimerList = new(); + + [SerializeField] private string timerName; + private TimerTimeType type = TimerTimeType.Null; + + public void SetTimer(string name, TimerTimeType type) + { + timerName = name + "_" + type; + this.type = type; + } + + private float GetTime() + { + return type switch + { + TimerTimeType.Time => Time.time, + TimerTimeType.UnscaledTime => Time.unscaledTime, + TimerTimeType.RealtimeSinceStartup => Time.realtimeSinceStartup, + _ => 0 + }; + } + + private void Update() + { + if (destroyTimerList.Count > 0) + { + foreach (var i in destroyTimerList) + { + timerList.Remove(i); + } + + destroyTimerList.Clear(); + } + + if (addTimerList.Count > 0) + { + foreach (var i in addTimerList.Where(i => i.Value != null)) + { + timerList[i.Key] = i.Value; + } + + addTimerList.Clear(); + } + + if (timerList.Count > 0) + { + foreach (var timer in timerList.Values) + { + if (timer == null) + { + return; + } + + timer.Run(); + } + } + } + + public bool RemoveTimer(string key) + { + if (!timerList.ContainsKey(key)) + { + return false; + } + + if (!destroyTimerList.Contains(key)) + { + destroyTimerList.Add(key); + } + + return true; + } + + public void ClearAll() + { + addTimerList.Clear(); + timerList.Clear(); + destroyTimerList.Clear(); + } + + private void OnDestroy() + { + ClearAll(); + addTimerList = null; + timerList = null; + destroyTimerList = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs.meta new file mode 100644 index 0000000..11a449a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/NormalTimer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fefb9ed2ef0fffd409b6ea3e113cb153 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs new file mode 100644 index 0000000..8b18e09 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +namespace ScrewsMaster +{ + public class TimerTask + { + private Timer timer; + + public int repeatCount; + public float interval; + private Action onCallBack; + public object[] args; + public float time; + public bool isActive = true; + public bool isFrameUpdate = false; + + public TimerTask(Timer timer, float interval, Action onCallBack, params object[] args) + { + this.timer = timer; + + repeatCount = 1; + this.interval = interval; + this.onCallBack = onCallBack; + this.args = args; + time = timer.GetTriggerTime(interval); + } + + public TimerTask(Timer timer, int repeatCount, float interval, Action onCallBack, + params object[] args) + { + this.timer = timer; + + this.repeatCount = repeatCount; + this.interval = interval; + this.onCallBack = onCallBack; + this.args = args; + time = timer.GetTriggerTime(interval); + } + + public TimerTask(Timer timer, Action onCallBack, params object[] args) + { + this.timer = timer; + + this.onCallBack = onCallBack; + this.args = args; + } + + public void CallFunc() + { + onCallBack?.Invoke(this); + } + + public static implicit operator bool(TimerTask timerTask) + { + return null != timerTask; + } + } + + public class Timer : MonoBehaviour + { + public const int INFINITE_LOOP = -1; + + private List timerTaskList = new(); + private List timerTaskTriggers = new(); + + [SerializeField] private string timerName; + private TimerTimeType type = TimerTimeType.Null; + + public void SetTimer(string name, TimerTimeType type) + { + this.timerName = name + "_" + type; + this.type = type; + } + + private float GetTime() + { + return type switch + { + TimerTimeType.Time => Time.time, + TimerTimeType.UnscaledTime => Time.unscaledTime, + TimerTimeType.RealtimeSinceStartup => Time.realtimeSinceStartup, + _ => 0 + }; + } + + private void Update() + { + if (timerTaskList.Count > 0) + { + timerTaskTriggers.Clear(); + foreach (var timerTask in timerTaskList.Where(timerTask => timerTask.isActive)) + { + if (timerTask.isFrameUpdate) + { + timerTaskTriggers.Add(timerTask); + } + else + { + if (timerTask.time <= GetTime()) + { + timerTaskTriggers.Add(timerTask); + } + } + } + + foreach (var triggerTimerTask in timerTaskTriggers) + { + if (triggerTimerTask.repeatCount != INFINITE_LOOP) + { + triggerTimerTask.repeatCount--; + } + + if (triggerTimerTask.repeatCount == 0) + { + timerTaskList.Remove(triggerTimerTask); + } + else + { + if (!triggerTimerTask.isFrameUpdate) + { + triggerTimerTask.time = GetTriggerTime(triggerTimerTask.interval); + } + } + + triggerTimerTask.CallFunc(); + } + } + } + + public TimerTask AddLoopTimer(float interval, Action onCallBack, params object[] args) + { + var timeTask = new TimerTask(this, INFINITE_LOOP, interval, onCallBack, args); + AddTimer(timeTask); + return timeTask; + } + + public void AddTimer(TimerTask timerTask) + { + if (null != timerTask) + { + if (!timerTask.isFrameUpdate) + { + if (timerTask.interval <= 0) + { + timerTask.CallFunc(); + return; + } + } + + timerTaskList.Add(timerTask); + } + } + + public void ClearAll() + { + timerTaskList.Clear(); + timerTaskTriggers.Clear(); + } + + public float GetTriggerTime(float interval) + { + return GetTime() + interval; + } + + private void OnDestroy() + { + ClearAll(); + timerTaskList = null; + timerTaskTriggers = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs.meta new file mode 100644 index 0000000..ba902e7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/Timer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1af09b65e6897dd4e8adcb89203638d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs new file mode 100644 index 0000000..1a92b47 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs @@ -0,0 +1,57 @@ +namespace ScrewsMaster +{ + public static class TimerHelper + { + private static string name = "TimerHelper"; + + #region Time + + private static EasyTimer sEasyTimer; + private static Timer _Timer; + private static NormalTimer sNormalTimer; + + public static EasyTimer mEasy + { + get + { + if (sEasyTimer == null) + { + sEasyTimer = TimerIManager.Instance.CreateSimpleTimer(name, TimerTimeType.Time); + } + + return sEasyTimer; + } + } + + #endregion + + #region UnscaledTime + + private static EasyTimer sUnscaledEasyTimer; + private static Timer _UnscaledTimer; + private static NormalTimer sUnscaledNormalTimer; + + public static Timer UnscaleGeneral + { + get + { + if (_UnscaledTimer == null) + { + _UnscaledTimer = TimerIManager.Instance.CreateTimer(name, TimerTimeType.UnscaledTime); + } + + return _UnscaledTimer; + } + } + + #endregion + + #region RealtimeSinceStartup + + private static EasyTimer sRealEasyTimer; + private static Timer _RealTimer; + private static NormalTimer sRealNormalTimer; + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs.meta new file mode 100644 index 0000000..af8e79b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/Timer/TimerHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 889a363446c9d38489732b45d60696c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs new file mode 100644 index 0000000..4a91955 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs @@ -0,0 +1,102 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class UnitConvertUtil + { + public static string[] UnitSuffixs = + { + "", "K", "M", "B", "T", "aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj ", "ak", "al", "am", "an", + "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az", "ba", "bb", "bc", "bd", "be", "bf", + "bg", "bh", "bi", "bj", "bk", "bl", "bm", "bn", "bo", "bp", "bq", "br", "bs", "bt", "bu", "bv", "bw", "bx", + "by", "bz", "ca", "cb", "cc", "cd", "ce", "cf", "cg", "ch", "ci", "cj", "ck", "cl", "cm", "cn", "co", "cp", + "cq", "cr", "cs", "ct", "cu", "cv", "cw", "cx", "cy", "da", "db", "dc", "dd", "de", "df", "dg", "dh", "di", + "dj", "dk", "dl", "dm", "dn", "do", "dp", "dq", "dr", "ds", "dt", "du", "dv", "dw", "dx", "dy" + }; + + + public static string ConvertIntUnitStr(double value) + { + int count = GetDigitNumber(value); + int unitNum = 0; + while (count > 3) + { + count -= 3; + value /= 1000; + unitNum++; + } + + return (int)value + UnitSuffixs[unitNum]; + } + + public static int GetDigitNumber(double value) + { + int count = 0; + while (value > 1) + { + count++; + value = value / 10; + } + + return count; + } + + + public static string ConvertUnit(int value) + { + int unit = GetDigitNumber(value); + if (unit > 0) + { + unit--; + } + + int unitIdx = 0; + if (unit >= 6) + { + unitIdx = (int)Mathf.Ceil(unit / 3) - 1; + } + + unitIdx = Mathf.Min(unitIdx, UnitSuffixs.Length - 1); + + float baseNum = Mathf.Pow(10, unitIdx * 3); + string numToShow = Mathf.Ceil(value / baseNum).ToString(); + string numToShowString = string.Empty; + int j = 0; + for (int i = numToShow.Length - 1; i >= 0; i--) + { + j++; + numToShowString = numToShow[i] + numToShowString; + if (i != 0 && j % 3 == 0) + { + numToShowString = "," + numToShowString; + } + } + + return numToShowString + UnitSuffixs[unitIdx]; + } + + public static string ConvertNoDecimalUnit(double value, string symbol = ".") + { + int count = GetDigitNumber(value); + int unitNum = 0; + while (count > 7) + { + count -= 3; + value /= 1000; + unitNum++; + } + + string valueStr = value.ToString("f0"); + string unitStr = UnitSuffixs[unitNum]; + for (int i = 0; i < (valueStr.Length - 1) / 3; i++) + { + int index = valueStr.Length % 3 + i * ((valueStr.Length - 1) / 3) + i; + valueStr = valueStr.Insert(index, symbol); + } + + if (valueStr.StartsWith(symbol)) + valueStr = valueStr.Remove(0, 1); + return valueStr + unitStr; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs.meta new file mode 100644 index 0000000..49f8ef2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/GeneralKit/UnitConvertUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d812f124e53f2548bc7aba6bf278bc7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper.meta new file mode 100644 index 0000000..2aec733 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 54a881205c54bff4d850da7972e5cb09 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs new file mode 100644 index 0000000..326a691 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs @@ -0,0 +1,23 @@ +using DG.Tweening; + +namespace ScrewsMaster +{ + public static class DOTweenHelper + { + public static void Init() + { + var doTweenInit = DOTween.Init(); + doTweenInit?.SetCapacity(1024, 1024); + + DOTween.SetTweensCapacity(1024, 1024); + + DOTween.defaultEaseType = Ease.Linear; + + DOTween.defaultEaseOvershootOrAmplitude = 1.70158f; + + DOTween.defaultEasePeriod = 0f; + + DOTween.logBehaviour = LogBehaviour.Verbose; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs.meta new file mode 100644 index 0000000..8dc9345 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/DOTweenHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0519ac96dec7c074eb2ab4191049c0e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs new file mode 100644 index 0000000..c402063 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs @@ -0,0 +1,23 @@ +using FairyGUI; + +namespace ScrewsMaster +{ + public static class FGUIHelper + { + public static void AddFguiTimer(float interval, int repeat, TimerCallback callback, object callbackParam) + { + Timers.inst.Add(interval, repeat, callback, callbackParam); + } + + public static string SetGLoaderUrl(GLoader gLoader, string pkgName, string resName) + { + var url = UIPackage.GetItemURL(pkgName, resName); + if (url != null) + { + gLoader.url = url; + } + + return url; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs.meta new file mode 100644 index 0000000..77be1d2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/Helper/FGUIHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed9a746e29efffb49a34ccaa28fad0bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs new file mode 100644 index 0000000..9a98b38 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs @@ -0,0 +1,34 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class ParticleUnscaledTime : MonoBehaviour + { + private float lastTime; + private ParticleSystem particle; + + private void Awake() + { + InitData(); + } + + private void Update() + { + OnUpdateParticleTime(); + } + + private void InitData() + { + particle = GetComponent(); + lastTime = Time.realtimeSinceStartup; + } + + private void OnUpdateParticleTime() + { + var realtimeSinceStartup = Time.realtimeSinceStartup; + var deltaTime = realtimeSinceStartup - lastTime; + particle.Simulate(deltaTime, true, false); + lastTime = realtimeSinceStartup; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs.meta new file mode 100644 index 0000000..041bbae --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/ParticleUnscaledTime.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3aea4fd60c51439408f557406144c842 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs new file mode 100644 index 0000000..c5e5f00 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class PlayerPrefsKit + { + public static void WriteInt(string key, int data) + { + PlayerPrefs.SetInt(key, data); + } + + public static void WriteBool(string key, bool data) + { + PlayerPrefs.SetInt(key, data ? PrefsConst.IntTrue : PrefsConst.IntFalse); + } + + public static void WriteString(string key, string data) + { + PlayerPrefs.SetString(key, data); + } + + public static void WriteObject(string key, object data) + { + string dataStr = SerializeUtil.ToJson(data); + PlayerPrefs.SetString(key, dataStr); + } + + public static bool ReadBool(string key, bool defalutValue = PrefsConst.BoolDefault) + { + if (!HasKey(key)) + { + return defalutValue; + } + + bool data = PlayerPrefs.GetInt(key) == PrefsConst.IntTrue ? true : false; + return data; + } + + public static string ReadString(string key) + { + string data = PlayerPrefs.GetString(key, string.Empty); + return data; + } + + public static bool HasKey(string key) + { + return PlayerPrefs.HasKey(key); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs.meta new file mode 100644 index 0000000..bf46d4e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/PlayerPrefsKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76dcbe5a9e849b04792146811da649cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK.meta new file mode 100644 index 0000000..0bb8e77 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: da918a8bb74e48a39f4b2bf158d7a90d +timeCreated: 1703490994 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs new file mode 100644 index 0000000..13fbe02 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs @@ -0,0 +1,121 @@ +using System.Collections; +using UnityEngine; +using AppsFlyerSDK; +using System.Collections.Generic; + +#if UNITY_IOS && !UNITY_EDITOR +using Unity.Advertisement.IosSupport; +#endif + +namespace ScrewsMaster +{ + + + internal class AppsFlyerObjectScript1 : MonoBehaviour, IAppsFlyerConversionData + { + public string appID = null; + public bool is_init = false; + void Start() + { + + + AppsFlyer.setIsDebug(true); +#if UNITY_IOS && !UNITY_EDITOR + appID = "6723880120"; + StartCoroutine("loopWaitInitAf"); + +#endif + + +#if UNITY_EDITOR + NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login); +#endif + + + } + +#if UNITY_IOS && !UNITY_EDITOR + public IEnumerator loopWaitInitAf() + { + var reqData = new RespLoginFunnelData + { + type = "afSend", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + float a = 0; + if (ATTrackingStatusBinding.GetAuthorizationTrackingStatus() == + ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED) + { + ATTrackingStatusBinding.RequestAuthorizationTracking(); + } + + + while ((ATTrackingStatusBinding.GetAuthorizationTrackingStatus() == + ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED) && (a < 5.0f)) + { + a += 0.5f; + yield return new WaitForSeconds(0.5f); + } + + AppsFlyer.initSDK("Qrv4wCq6shkTP6x5SBtuZT", appID, this); + AppsFlyer.startSDK(); + AppsFlyer.AFLog("8888888888888888888", ATTrackingStatusBinding.GetAuthorizationTrackingStatus().ToString()); + //yield return new WaitForSeconds(0.5f); + + } +#endif + + public void onConversionDataSuccess(string conversionData) + { + if (is_init) return; + is_init = true; + AppsFlyer.AFLog("onConversionDataSuccess", conversionData); + Debug.Log("hunxiao0000000000000000000000-1"); + var conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData); + var json = SerializeUtil.ToJsonIndented(conversionDataDictionary); + Debug.Log("hunxiao0000000000000000000000-2"); + + SuperApplication.Instance.attribution = + conversionDataDictionary.TryGetValue("af_status", out var afStatus1) + ? afStatus1.ToString().ToLower() + : "organic"; + + // Debug.Log("hunxiao0000000000000000000000"); + NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login); + + var reqData = new RespLoginFunnelData + { + type = "afRecv", + payload = "true" + }; + NetworkKit.PostFunnelLogin(reqData); + } + + public void onConversionDataFail(string error) + { + if (is_init) return; + is_init = true; + AppsFlyer.AFLog("onConversionDataFail", error); + NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login); + var reqData = new RespLoginFunnelData + { + type = "afRecv", + payload = "false" + }; + NetworkKit.PostFunnelLogin(reqData); + } + + public void onAppOpenAttribution(string attributionData) + { + AppsFlyer.AFLog("onAppOpenAttribution", attributionData); + Dictionary attributionDataDictionary = + AppsFlyer.CallbackStringToDictionary(attributionData); + } + + public void onAppOpenAttributionFailure(string error) + { + AppsFlyer.AFLog("onAppOpenAttributionFailure", error); + } + } +} diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs.meta new file mode 100644 index 0000000..e7601a3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/AppsFlyerObjectScript1.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 03245a515d1e47a8ab5720b508bef85b +timeCreated: 1730188598 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs new file mode 100644 index 0000000..fee9adb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using AppsFlyerSDK; +using UnityEngine; +using UnityEngine.Events; +using static ScrewsMaster.NetworkKit; + +namespace ScrewsMaster +{ + public class MaxADKit + { + public static string SDKKey = + "oXM0CzVDi7P1HstOpKvFMInPMOzpQ9uA6t3x75q5f5wQvsEy9vuiiiM94ZJCJSV7PcZGroSSInQCTGsu04QEiE"; + + public static string interstitialADUnitID = "c1d96170d3f02c0e"; + + + public static string rewardedADUnitID = "f9cf204de101065b"; + + + private const float RevenueThreshold = 0.1f; + + public static Dictionary adCallbackInfo; + + private static UnityAction _rewardedAdPlayCallback; + private static UnityAction _interstitialAdPlayCallback; + + public static string user_id = ""; + + public static void Init() + { + MaxSdkCallbacks.OnSdkInitializedEvent += sdkConfiguration => + { + InitializeRewardedAds(); + InitializeInterstitialAds(); + }; + + + MaxSdk.SetSdkKey(SDKKey); + + var loginModel = GameHelper.GetLoginModel(); + user_id = loginModel.uid.ToString(); + + MaxSdk.SetUserId(user_id); + // MaxSdk.SetIsAgeRestrictedUser(false); + MaxSdk.SetHasUserConsent(true); + MaxSdk.SetDoNotSell(false); + + MaxSdk.InitializeSdk(); +#if !JarvisRelease + MaxSdk.ShowMediationDebugger(); +#endif + adCallbackInfo = new Dictionary(); + } + + #region 插屏广告相关 + + public static void ShowInterstitial(string placement = "DefaultInterstitial", + UnityAction onCompleted = null) + { + _interstitialAdPlayCallback = onCompleted; + if (MaxSdk.IsInterstitialReady(interstitialADUnitID)) + { + // Debug.Log($"广告已经准备好,播放"); + MaxSdk.ShowInterstitial(interstitialADUnitID, placement); + // onCompleted?.Invoke(true); + } + else + { + // Debug.Log($"广告未准备好,不播放"); + + _interstitialAdPlayCallback?.Invoke(false); + } + } + + static int retryAttemptInterstitial; + + public static void InitializeInterstitialAds() + { + + MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnInterstitialLoadedEvent; + MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnInterstitialLoadFailedEvent; + MaxSdkCallbacks.Interstitial.OnAdDisplayedEvent += OnInterstitialDisplayedEvent; + MaxSdkCallbacks.Interstitial.OnAdClickedEvent += OnInterstitialClickedEvent; + MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnInterstitialHiddenEvent; + MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnInterstitialAdFailedToDisplayEvent; + MaxSdkCallbacks.Interstitial.OnAdRevenuePaidEvent += OnAdRevenuePaidEvent; + + + LoadInterstitial(); + } + + private static void LoadInterstitial() + { + MaxSdk.LoadInterstitial(interstitialADUnitID); + } + + private static void OnInterstitialLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + retryAttemptInterstitial = 0; + } + + private static void OnInterstitialLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo) + { + retryAttemptInterstitial++; + double retryDelay = Math.Pow(2, Math.Min(6, retryAttemptInterstitial)); + + CrazyAsyKit.StartAction("LoadInterstitial", LoadInterstitial, (float)retryDelay); + } + + private static void OnInterstitialDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + } + + private static void OnInterstitialAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, + MaxSdkBase.AdInfo adInfo) + { + _interstitialAdPlayCallback?.Invoke(false); + LoadInterstitial(); + } + + private static void OnInterstitialClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + } + + private static void OnInterstitialHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + _interstitialAdPlayCallback?.Invoke(true); + OnInterstitialAdRevenuePaidEvent(adUnitId, adInfo); + LoadInterstitial(); + } + + private static void OnInterstitialAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + string countryCode = "USD";//MaxSdk.GetSdkConfiguration().CountryCode; // "US" for the United States, etc - Note: Do not confuse this with currency code which is "USD" + // //string networkName = adInfo.NetworkName; // Display name of the network that showed the ad + // // string adUnitIdentifier = adInfo.AdUnitIdentifier; // The MAX Ad Unit ID + // //string placement = adInfo.Placement; // The placement this ad's postbacks are tied to + // // string networkPlacement = adInfo.NetworkPlacement; // The placement ID from the network that showed the ad + adCallbackInfo.Clear(); + var loginModel = GameHelper.GetLoginModel(); + adCallbackInfo.Add("customer_user_id", loginModel.uid.ToString()); + adCallbackInfo.Add("af_revenue", adInfo.Revenue.ToString()); + adCallbackInfo.Add("af_currency", countryCode); + adCallbackInfo.Add("eventValue", ""); + // //AppsFlyer.sendEvent("af_pay", adCallbackInfo); + + double revenue = Convert.ToDouble(PlayerPrefs.GetString($"adInfoRevenue_{loginModel.uid}", "0")); revenue += adInfo.Revenue; + + if (revenue >= RevenueThreshold) + { + adCallbackInfo["af_revenue"] = revenue.ToString(); + //AppsFlyer.sendEvent("af_revenue", adCallbackInfo); + PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", "0"); + + bool isToday = CommonHelper.IsToday(loginModel.reg_time); + if (isToday) + { + adCallbackInfo["af_new_revenue"] = revenue.ToString(); + //AppsFlyer.sendEvent("af_purchase", adCallbackInfo); + } + } + else + { + PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", revenue.ToString()); + } + } + + #endregion + + #region 激励视频广告相关 + + public static void ShowVideo(string placement = "DefaultVideo", UnityAction onCompleted = null) + { + _rewardedAdPlayCallback = onCompleted; +#if UNITY_EDITOR + _rewardedAdPlayCallback?.Invoke(true); +#else + if (MaxSdk.IsRewardedAdReady(rewardedADUnitID)) + { + MaxSdk.ShowRewardedAd(rewardedADUnitID, placement); + // onCompleted?.Invoke(true); + } + else + { + _rewardedAdPlayCallback?.Invoke(false); + } +#endif + } + + static int retryAttempt; + + public static void InitializeRewardedAds() + { + MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedAdLoadedEvent; + MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedAdLoadFailedEvent; + MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedAdDisplayedEvent; + MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedAdClickedEvent; + MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedAdRevenuePaidEvent; + MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedAdHiddenEvent; + MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedAdFailedToDisplayEvent; + MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedAdReceivedRewardEvent; + + MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnAdRevenuePaidEvent; + Debug.Log("InitializeRewardedAds"); + + LoadRewardedAd(); + } + + private static void LoadRewardedAd() + { + MaxSdk.LoadRewardedAd(rewardedADUnitID); + } + + private static void OnAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + string countryCode = "USD"; + + adCallbackInfo.Clear(); + adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId()); + adCallbackInfo.Add("customer_user_id", user_id); + adCallbackInfo.Add("af_currency", countryCode); + + //广告收益上传(扣量)((用户累计收益大于0.1上报50%,50%可配置)) + double revenue = Convert.ToDouble(PlayerPrefs.GetString($"adInfoRevenue_{user_id}", "0")); + revenue += adInfo.Revenue; + + // Debug.Log($"revenue: {revenue} \n adInfo.Revenue: {adInfo.Revenue}"); + + if (revenue >= RevenueThreshold) + { + adCallbackInfo.Add("af_revenue", revenue.ToString()); + AppsFlyer.sendEvent("af_ad_revenue", adCallbackInfo); + PlayerPrefs.SetString($"adInfoRevenue_{user_id}", "0"); + + int adrate = ConfigSystem.GetConfig().adrate / 100; + double revenueAdrate = revenue * adrate; + adCallbackInfo["af_revenue"] = revenueAdrate.ToString(); + AppsFlyer.sendEvent("Af_new_ad_revenue", adCallbackInfo); + } + else + { + PlayerPrefs.SetString($"adInfoRevenue_{user_id}", revenue.ToString()); + } + + int highSend; + if (!PlayerPrefs.HasKey($"sendHighRevenue_{user_id}")) + { + highSend = 0; // 如果不存在,则初始化为 0 + } + else + { + highSend = PlayerPrefs.GetInt($"sendHighRevenue_{user_id}", 0); // 从 PlayerPrefs 中获取 + } + // 判断是否需要发送高收入事件 + // Debug.Log($"highSend=====: {highSend}"); + if (highSend == 0) + { + float limitNum = GameHelper.GetCommonModel().afSendLimit; + var totalNum = Convert.ToDouble(PlayerPrefs.GetString($"adRevenueTotal_{user_id}", "0")); + totalNum += adInfo.Revenue; + // Debug.Log($"totalNum=====: {totalNum} {limitNum}"); + if (totalNum >= limitNum) + { + GameHelper.sendHighRevenueToAF(); // 发送高收入事件 + PlayerPrefs.SetInt($"sendHighRevenue_{user_id}", 1); // 标记已发送 + } + else + { + PlayerPrefs.SetString($"adRevenueTotal_{user_id}", totalNum.ToString()); + } + } + } + + private static void OnRewardedAdLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + retryAttempt = 0; + } + + private static void OnRewardedAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo) + { + retryAttempt++; + double retryDelay = Math.Pow(2, Math.Min(6, retryAttempt)); + + CrazyAsyKit.StartAction("LoadRewardedAd", LoadRewardedAd, (float)retryDelay); + } + + private static void OnRewardedAdDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + } + + private static void OnRewardedAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, + MaxSdkBase.AdInfo adInfo) + { + LoadRewardedAd(); + } + + private static void OnRewardedAdClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + } + + private static void OnRewardedAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + LoadRewardedAd(); + + if (GameHelper.IsGiftSwitch() && !SaveData.GetSaveobject().is_get_removead && (UnityEngine.Random.Range(0, 100) < GameHelper.GetCommonModel().rewardinsertion)) + { + NetworkKit.androidPointObject.@event = BuriedPointEvent.Apple_AD_event; + NetworkKit.androidPointObject.property = BuriedPointEvent.afterRewardAdShow; + NetworkKit.androidPointObject.n = 1; + NetworkKit.PostWithHeader("/event/incrN", androidPointObject, (isSuccess, obj) => + { + }); + + GameHelper.ShowInterstitial("AfterReward"); + } + } + + private static void OnRewardedAdReceivedRewardEvent(string adUnitId, MaxSdk.Reward reward, + MaxSdkBase.AdInfo adInfo) + { + + _rewardedAdPlayCallback?.Invoke(true); + _rewardedAdPlayCallback = null; + + string countryCode = "USD";//MaxSdk.GetSdkConfiguration().CountryCode; // "US" for the United States, etc - Note: Do not confuse this with currency code which is "USD" + // //string networkName = adInfo.NetworkName; // Display name of the network that showed the ad + // // string adUnitIdentifier = adInfo.AdUnitIdentifier; // The MAX Ad Unit ID + // //string placement = adInfo.Placement; // The placement this ad's postbacks are tied to + // // string networkPlacement = adInfo.NetworkPlacement; // The placement ID from the network that showed the ad + adCallbackInfo.Clear(); + var loginModel = GameHelper.GetLoginModel(); + adCallbackInfo.Add("customer_user_id", loginModel.uid.ToString()); + adCallbackInfo.Add("af_revenue", adInfo.Revenue.ToString()); + adCallbackInfo.Add("af_currency", countryCode); + adCallbackInfo.Add("eventValue", ""); + // //AppsFlyer.sendEvent("af_pay", adCallbackInfo); + + double revenue = Convert.ToDouble(PlayerPrefs.GetString($"adInfoRevenue_{loginModel.uid}", "0")); + revenue += adInfo.Revenue; + + if (revenue >= RevenueThreshold) + { + adCallbackInfo["af_revenue"] = revenue.ToString(); + //AppsFlyer.sendEvent("af_revenue", adCallbackInfo); + PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", "0"); + + bool isToday = CommonHelper.IsToday(loginModel.reg_time); + if (isToday) + { + adCallbackInfo["af_new_revenue"] = revenue.ToString(); + //AppsFlyer.sendEvent("af_purchase", adCallbackInfo); + } + } + else + { + PlayerPrefs.SetString($"adInfoRevenue_{loginModel.uid}", revenue.ToString()); + } + + } + + private static void OnRewardedAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) + { + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs.meta b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs.meta new file mode 100644 index 0000000..a8edd34 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Core/ToolKit/SDK/MaxADKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d3991d0dfc5a46ddbb4a020f0c5e0abf +timeCreated: 1704883729 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic.meta b/Assets/CrazyZoo/Runtime/Logic.meta new file mode 100644 index 0000000..2c4d8d8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e0977b17938db43449bb18a44c9b23f4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define.meta b/Assets/CrazyZoo/Runtime/Logic/Define.meta new file mode 100644 index 0000000..cea8f3d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f0b31d98ce0c3cc4bb7c662d2e356e1d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Const.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Const.meta new file mode 100644 index 0000000..a13b66d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Const.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9d32c964d4a8de44f9c204731a2c0e61 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs new file mode 100644 index 0000000..96542fe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs @@ -0,0 +1,11 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class PlayerPrefsConst + { + public static string IsFaceBookLogin = "IsFaceBookLogin"; + public static string FacebookAvatarUrl = "FacebookAvatarUrl"; + public static string CachePath = Application.persistentDataPath + "/Cache/CacheLocalPreferences.super"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs.meta new file mode 100644 index 0000000..faa5356 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Const/PlayerPrefsConst.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ecc423687b5944a2a7970936527d39f6 +timeCreated: 1684204951 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data.meta new file mode 100644 index 0000000..8004260 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3a3ef8829eecb8e4785f903060bb3061 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs new file mode 100644 index 0000000..336df07 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class AdTaskData + { + public int videoCount; + public AdTaskState state = AdTaskState.None; + } + + public enum AdTaskState + { + None, + Ready, + Done, + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs.meta new file mode 100644 index 0000000..81518ed --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/AdTaskData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a88a3ba768a5dd643ab8232366a630cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs new file mode 100644 index 0000000..7c35d08 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs @@ -0,0 +1,6 @@ +namespace ScrewsMaster +{ + public class InviteData + { + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs.meta new file mode 100644 index 0000000..fb4d9b8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 655aee83afce67c40b9f14df6e45aaf1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs new file mode 100644 index 0000000..3ad3092 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs @@ -0,0 +1,29 @@ +namespace ScrewsMaster +{ + public enum InviteMakeupStatus + { + None = 0, + Fail = 1, + Processing = 2, + Success = 3, + } + + public class InviteMakeUpHistory + { + public int id; + + public float amount; + + public string method; + + public long makeupTimestamp; + + public string email; + + public string phone; + + public InviteMakeupStatus status; + + public int serverOrderId; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs.meta new file mode 100644 index 0000000..51b6ee5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteMakeUpHistory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ff48a75ef486564bbf5425f2bfdfde3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs new file mode 100644 index 0000000..1bd492d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs @@ -0,0 +1,18 @@ +namespace ScrewsMaster +{ + public enum InviteRecordOrigin + { + InvitePlayer, + InviteBonus, + } + + public class InviteRecord + { + public float amount; + public long time_stamp; + public string title; + public long uid; + public InviteRecordOrigin origin; + public string icon; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs.meta new file mode 100644 index 0000000..e234c8a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/InviteRecord.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 28d57e0821234a75ae07aff540f7f638 +timeCreated: 1681804569 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs new file mode 100644 index 0000000..6329959 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs @@ -0,0 +1,8 @@ +namespace ScrewsMaster +{ + public class KeyValue + { + public string key; + public object value; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs.meta new file mode 100644 index 0000000..dc610a0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/KeyValue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b290bcee76f7b6f46b7f0df698139902 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs new file mode 100644 index 0000000..1b0f23d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs @@ -0,0 +1,65 @@ +namespace ScrewsMaster +{ + public class MakeupTaskData + { + public int tableId; + + + public int id; + + + public string amountStr; + + + public decimal amount; + + + public long makeupTime; + + + public int videoCount; + + + public int inlineInitNum; + + + public int inlineNum; + + + public string orderID; + + + public MakeupTaskStatus status; + + public long order_time = 0; + public int WatchVideoSpeedNum = 0; + public int loginSpeedNum = 0; + public int activeMinute = 0; + public int activeSpeedNum = 0; + + + public void SetStatus(MakeupTaskStatus _status) + { + status = _status; + } + + public string GetAmountStr() + { + if (amount <= 0) + { + return amountStr; + } + else + { + return GameHelper.Get102Str(amount); + } + } + } + + public enum MakeupTaskStatus + { + None, + Task, + Inline, + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs.meta new file mode 100644 index 0000000..d8e7893 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Data/MakeupTaskData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fad037054f584d4db231c2ecdba0491 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Message.meta new file mode 100644 index 0000000..3c5d092 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ddaa1d23092578e41b7ce0a701a6cc33 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs new file mode 100644 index 0000000..ee9bf5b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs @@ -0,0 +1,22 @@ +namespace ScrewsMaster +{ + public static partial class CtrlMsg + { + private static uint CtrlMsgLogic = 200000; + public static uint NewDays = ++CtrlMsgLogic; + public static uint WatchVideoFinish = ++CtrlMsgLogic; + public static uint ConsumeResources = ++CtrlMsgLogic; + public static uint GameNewDays = ++CtrlMsgLogic; + public static uint WatchIntVideoFinish = ++CtrlMsgLogic; + + public static readonly uint Preferences_InitComplete = ++CtrlMsgLogic; + public static readonly uint Game_StartBefore = ++CtrlMsgLogic; + public static readonly uint Module_GiftSwitchChange = ++CtrlMsgLogic; + public static readonly uint Webview_PageState = ++CtrlMsgLogic; + public static readonly uint Webview_PageFinish = ++CtrlMsgLogic; + public static readonly uint Webview_Open = ++CtrlMsgLogic; + public static uint ServerNewDays = ++CtrlMsgLogic; + public static readonly uint NewConfigRead = ++CtrlMsgLogic; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs.meta new file mode 100644 index 0000000..f919a06 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/CtrlMsg_Logic.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ac4e4915625e4e5bbf86dde8b9bbe00b +timeCreated: 1681804977 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs new file mode 100644 index 0000000..43c5bb2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs @@ -0,0 +1,65 @@ +namespace ScrewsMaster +{ + public static partial class GameMsg + { + public static readonly uint OpenGame = ++Cursor_BASE; + public static readonly uint Update111Completed = ++Cursor_BASE; + public static readonly uint BackMainScene = ++Cursor_BASE; + public static readonly uint Update102Completed = ++Cursor_BASE; + public static uint Slot_refresh = ++Cursor_BASE; + public static uint Remake_state = ++Cursor_BASE; + public static readonly uint MakeupSuccess = ++Cursor_BASE; + + public static uint Ad_success = ++Cursor_BASE; + public static uint UpdateHotFixMax = ++Cursor_BASE; + public static uint UpdateHotFixProgress = ++Cursor_BASE; + public static readonly uint RefreshTodoUI = ++Cursor_BASE; + public static readonly uint RefreshMakeupData = ++Cursor_BASE; + public static uint Gold_refresh = ++Cursor_BASE; + public static uint Sheep_item_refresh = ++Cursor_BASE; + public static uint card_click = ++Cursor_BASE; + + public static uint RefreshADTask = ++Cursor_BASE; + public static readonly uint GetReward = ++Cursor_BASE; + public static readonly uint ProcessReward = ++Cursor_BASE; + + public static readonly uint Update101 = ++Cursor_BASE; + public static readonly uint MakeUpConfirmUIClosed = ++Cursor_BASE; + + public static readonly uint Update111 = ++Cursor_BASE; + public static uint reset_game = ++Cursor_BASE; + public static uint GetTaskReward = ++Cursor_BASE; + public static uint google_pay_success = ++Cursor_BASE; + public static uint apple_pay_success = ++Cursor_BASE; + public static uint pack_close = ++Cursor_BASE; + public static uint PaySuccess = ++Cursor_BASE; + public static uint resetH5progress = ++Cursor_BASE; + public static uint GotoH5 = ++Cursor_BASE; + public static uint RefreshGame = ++Cursor_BASE; + public static uint FlyGold = ++Cursor_BASE; + public static uint RefreshLookAd = ++Cursor_BASE; + + + public static uint RefreshItemCount = ++Cursor_BASE; + + public static readonly uint H5ViewClickBtn = ++Cursor_BASE; + + + public static uint BattleLevelUp = ++Cursor_BASE;//通行证等级提升 + public static uint PayBattlePass = ++Cursor_BASE;//购买通行证 + public static uint AdWatchCountUpdated = ++Cursor_BASE;//看广告次数变化 + public static uint AdRewardClaimed = ++Cursor_BASE;//广告奖励已领取 + public static uint BuyRemoveAdPack = ++Cursor_BASE;//购买免广告礼包 + public static uint BuyPack = ++Cursor_BASE;//购买普通礼包 + public static uint resurgence = ++Cursor_BASE; + public static uint resurgence_close = ++Cursor_BASE; + public static uint RefreshSaveingPot = ++Cursor_BASE; + public static uint hideBroadCast = ++Cursor_BASE; + public static uint showBroadCast = ++Cursor_BASE; + public static uint updateRecordList = ++Cursor_BASE; + public static uint rewardMul_close = ++Cursor_BASE; + public static uint ThreeDaysGiftUIClose = ++Cursor_BASE; + public static uint three_days_gift = ++Cursor_BASE; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs.meta new file mode 100644 index 0000000..26a1263 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/GameMsg_Logic.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e353f03ecaf641c788d83ecb0c4c8f97 +timeCreated: 1681804796 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs new file mode 100644 index 0000000..750b333 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs @@ -0,0 +1,11 @@ +namespace ScrewsMaster +{ + public partial class NetworkMsg + { + private static uint MsgRootLogic = 100000; + public static uint GetConfig = ++MsgRootLogic; + public static uint Login = ++MsgRootLogic; + public static uint SavePlayData = ++MsgRootLogic; + public static uint GetPlayData = ++MsgRootLogic; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs.meta new file mode 100644 index 0000000..fda35b7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/NetworkMsg_Logic.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9cc437c270f9432a8f58536fd2ab3cad +timeCreated: 1681977528 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs new file mode 100644 index 0000000..4f3317a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs @@ -0,0 +1,127 @@ +namespace ScrewsMaster +{ + public static partial class UICtrlMsg + { + private static uint cursor_OpenClose = 130000; + + public static uint GameLoginUI_Close = ++cursor_OpenClose; + + public static uint MaskUI_Open = ++cursor_OpenClose; + public static uint MaskUI_Close = ++cursor_OpenClose; + public static uint FirstRewardUI_Open = ++cursor_OpenClose; + public static uint FirstRewardUI_Close = ++cursor_OpenClose; + public static uint RateUsDialogUI_Open = ++cursor_OpenClose; + public static uint RateUsDialogUI_Close = ++cursor_OpenClose; + public static uint OpenBgUI_Open = ++cursor_OpenClose; + public static uint OpenBgUI_Close = ++cursor_OpenClose; + public static uint FXWndUI_Open = ++cursor_OpenClose; + public static uint FXWndUI_Close = ++cursor_OpenClose; + public static uint RewardAniUI_Open = ++cursor_OpenClose; + public static uint RewardAniUI_Close = ++cursor_OpenClose; + public static uint NetLoadingUI_Open = ++cursor_OpenClose; + public static uint NetLoadingUI_Close = ++cursor_OpenClose; + public static uint SCTipsUI_Open = ++cursor_OpenClose; + public static uint SCTipsUI_Close = ++cursor_OpenClose; + public static uint GameLoginUI_Open = ++cursor_OpenClose; + public static uint RewardboxUI_Open = ++cursor_OpenClose; + public static uint RewardboxUI_Close = ++cursor_OpenClose; + + public static uint RewardUI_Open = ++cursor_OpenClose; + public static uint RewardUI_Close = ++cursor_OpenClose; + public static uint H5UI_Open = ++cursor_OpenClose; + + public static uint NewTaskUI_Open = ++cursor_OpenClose; + public static uint MakeupConfirmUI_Open = ++cursor_OpenClose; + + public static uint MenuUI_Open = ++cursor_OpenClose; + public static uint MenuUI_Close = ++cursor_OpenClose; + public static uint PlayUI_Close = ++cursor_OpenClose; + public static uint H5UI_Close = ++cursor_OpenClose; + public static uint NewTaskUI_Close = ++cursor_OpenClose; + public static uint RegulationUI_Open = ++cursor_OpenClose; + public static uint RegulationUI_Close = ++cursor_OpenClose; + public static uint LanguageWinUI_Open = ++cursor_OpenClose; + public static uint LanguageWinUI_Close = ++cursor_OpenClose; + + public static uint ProfileUI_Open = ++cursor_OpenClose; + public static uint ProfileUI_Close = ++cursor_OpenClose; + public static uint PackrewardUI_Open = ++cursor_OpenClose; + public static uint PackrewardUI_Close = ++cursor_OpenClose; + + public static uint PrivacyUI_Open = ++cursor_OpenClose; + public static uint PrivacyUI_Close = ++cursor_OpenClose; + public static uint PlayUIFX = ++cursor_OpenClose; + + public static uint ADTaskUI_Open = ++cursor_OpenClose; + public static uint ADTaskUI_Close = ++cursor_OpenClose; + public static uint SheepPlayUI_Open = ++cursor_OpenClose; + public static uint SheepPlayUI_Close = ++cursor_OpenClose; + public static uint OpenGameUI_Open = ++cursor_OpenClose; + public static uint OpenGameUI_Close = ++cursor_OpenClose; + public static uint OpenGameUI_PlayAnim = ++cursor_OpenClose; + + public static uint CoinWnd_newUI_Open = ++cursor_OpenClose; + public static uint CoinWnd_newUI_Close = ++cursor_OpenClose; + public static uint SheepwindowUI_Open = ++cursor_OpenClose; + public static uint SheepwindowUI_Close = ++cursor_OpenClose; + public static uint BuyslotUI_Open = ++cursor_OpenClose; + public static uint BuyslotUI_Close = ++cursor_OpenClose; + public static uint BuygoldUI_Open = ++cursor_OpenClose; + public static uint BuygoldUI_Close = ++cursor_OpenClose; + public static uint LevelSuccessUI_Open = ++cursor_OpenClose; + public static uint LevelSuccessUI_Close = ++cursor_OpenClose; + public static uint RemakeUI_Open = ++cursor_OpenClose; + public static uint RemakeUI_Close = ++cursor_OpenClose; + public static uint ScreenViewUI_Open = ++cursor_OpenClose; + public static uint ScreenViewUI_Close = ++cursor_OpenClose; + public static uint AdcomingUI_Open = ++cursor_OpenClose; + public static uint AdcomingUI_Close = ++cursor_OpenClose; + + public static uint PassunlockUI_Open = ++cursor_OpenClose; + public static uint PassunlockUI_Close = ++cursor_OpenClose; + public static uint GetTaskRewardUI_Open = ++cursor_OpenClose; + public static uint GetTaskRewardUI_Close = ++cursor_OpenClose; + public static uint MakeupConfirmUI_Close = ++cursor_OpenClose; + public static uint MakeupStepUI_Open = ++cursor_OpenClose; + public static uint MakeupStepUI_Close = ++cursor_OpenClose; + public static uint MakeupRecordUI_Open = ++cursor_OpenClose; + public static uint MakeupRecordUI_Close = ++cursor_OpenClose; + public static uint PixPayUI_Open = ++cursor_OpenClose; + public static uint PixPayUI_Close = ++cursor_OpenClose; + public static uint PayloadingUI_Open = ++cursor_OpenClose; + public static uint PayloadingUI_Close = ++cursor_OpenClose; + + + public static uint ReviveUI_Open = ++cursor_OpenClose; + public static uint ReviveUI_Close = ++cursor_OpenClose; + public static uint PropUI_Open = ++cursor_OpenClose; + public static uint PropUI_Close = ++cursor_OpenClose; + public static uint TipsUI_Open = ++cursor_OpenClose; + public static uint TipsUI_Close = ++cursor_OpenClose; + + //2024年9月12日添加 + //签到界面 + public static uint SignInUI_Open = ++cursor_OpenClose; + public static uint SignInUI_Close = ++cursor_OpenClose; + + + public static uint PrizeWheelUI_Open = ++cursor_OpenClose; + public static uint PrizeWheelUI_Close = ++cursor_OpenClose; + public static uint GameHomeUI_Open = ++cursor_OpenClose; + public static uint GameHomeUI_Close = ++cursor_OpenClose; + public static uint RankUI_Open = ++cursor_OpenClose; + public static uint RankUI_Close = ++cursor_OpenClose; + public static uint ResurgenceUI_Open = ++cursor_OpenClose; + public static uint ResurgenceUI_Close = ++cursor_OpenClose; + public static uint SaveingPotUI_Open = ++cursor_OpenClose; + public static uint SaveingPotUI_Close = ++cursor_OpenClose; + public static uint BroadcastUI_Open = ++cursor_OpenClose; + public static uint BroadcastUI_Close = ++cursor_OpenClose; + public static uint RecordViewUI_Open = ++cursor_OpenClose; + public static uint RecordViewUI_Close = ++cursor_OpenClose; + public static uint ThreeDaysGiftUI_Open = ++cursor_OpenClose; + public static uint ThreeDaysGiftUI_Close = ++cursor_OpenClose; + public static uint RewardMulNewUI_Open = ++cursor_OpenClose; + public static uint RewardMulNewUI_Close = ++cursor_OpenClose; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs.meta new file mode 100644 index 0000000..c6826db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Message/UICtrlMsg_OpenClose.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 060fde138e1047d2b0d1b1b0f19574ea +timeCreated: 1681803677 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model.meta new file mode 100644 index 0000000..f555487 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4f279610afe14f24a93632de790e1bb2 +timeCreated: 1685009402 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config.meta new file mode 100644 index 0000000..b971dc6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a9d4b8f1e3f240a29b60fb5ac95bc802 +timeCreated: 1692603096 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game.meta new file mode 100644 index 0000000..4b75391 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ad3273bae87648ac8ff70eb4d402ae33 +timeCreated: 1692760582 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs new file mode 100644 index 0000000..b4fb651 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class AchieveModel:IDataList + { + public List dataList { get; set; } + } + + public class Achieve + { + public int id; + public bool is_com_reward; + public bool is_double; + public string text_read_ru; + public string text_read; + public string desc; + public int[] tol_num; + public int[] reward_num; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs.meta new file mode 100644 index 0000000..7540ac4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/AchieveModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c1d26b15267f4418b5e5e65377aab02e +timeCreated: 1692761155 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs new file mode 100644 index 0000000..d979937 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs @@ -0,0 +1,115 @@ +namespace ScrewsMaster +{ + public class CommonModel + { + public int answerTime; + + + public int InitialNum; + + + public int openReward; + + + public int[] quiznum; + + public int[] ThroughReward; + + public int ThroughRewardCD; + public int ThroughRewardType; + + + public float[] flyReward; + + + public int[] flyAdTime; + + + public int flyCD; + + + public int inviteReward; + + + public int inviteeToken; + + + public int[] videoTaskGiftNum; + + + public int[] inlineInitNum; + + + public int[] inlineLoginDown; + + + public int inlineMin; + + + public int naviequiz; + + + public string contactUs; + + public int watchAdCD; + public int[] propCoord; + public int flyCtRate; + public int lobbyrewrdtime; + public int roomrewardrate; + public int interstitialtype; + public int otherH5switch; + public int H5Refreshtime; + public int Dailyrefreshtimes; + + public int purchase1; + public int purchase2; + public int loginhallrate; + public int backhallrate; + public int darkThoughProbability; + public int darkH5Refreshtime; + public int darkDailyrefreshtimes; + + public float addspace; + public float Passportgift; + public int Purchaseprops; + public int Smallrewardsrate; + public int rewardrate; + public int RevivalCoins; + public int Activetimes; + public int playtimes; + public int WithdrawalaccelerationCD; + public int HideDailyrefreshtimes; + + public int[] darkWVRefreshtime; + public int[] darkWVDailyrefreshtimes; + + public int rewardinsertion; + + public int flytimes; + public int[] tiers; + public int[] patterntypes; + public int[] patternnumber; + public int[] wheelTimes; + public int exchangeCD; + public int flyswitch; + public int propswitch; + public int WVswitch; + + public float afSendLimit; + public int adrate; + public float afSendNum; + public int[] WVClickAddTime; + public int PassTimes; + public int FailedGiftProgress; + public int PiggyBankSwitch; + public int[] WVOffset; + public int FailedGiftCD; + public int[] darkWVRefreshtime2; + public float[] WVClickCTAddTime1; + public float[] WVClickCTAddTime2; + public int PayRate; + public float Passportgift2; + public float addspace2; + public int roomrate; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs.meta new file mode 100644 index 0000000..a9ba2b4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/CommonModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 954729fa345c44828d10b961f984abec +timeCreated: 1692604823 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs new file mode 100644 index 0000000..9d31177 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class DurationtasksModel:IDataList + { + public List dataList { get; set; } + } + + public class Durationtasks + { + public int id; + public bool is_com_reward; + public bool is_double; + public string text_read_ru; + public string text_read; + public string desc; + public int tol_num; + public int reward_num; + public bool is_get; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs.meta new file mode 100644 index 0000000..1c96067 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/DurationtasksModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b78b92c1d9e172548b8ffe9b3ab8368c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs new file mode 100644 index 0000000..a24e30b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs @@ -0,0 +1,10 @@ +namespace ScrewsMaster +{ + public class GameUrlsConstModel + { + public int[] webAutoResetCD; + public int[] webMarginTopDownLeftRight; + public int webMaxCTByToday; + public int webOrder_X; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs.meta new file mode 100644 index 0000000..dd7f672 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsConstModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 754f5700a3a57b14b8efae12525f2756 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs new file mode 100644 index 0000000..1999d01 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class GameUrlsModel : IDataList + { + public List dataList { get; set; } + } + + public class GameUrls + { + public string[] countryCode; + public string[] excludedCountryCode; + public int[] hideWebTimesCT; + public int id; + public int probability; + public int sectionalizerId; + public int userType; + public string webLink; + public int[] webTimesCT; + public int webType; + public string hideWebLink; + public int webLinkrefreshMax; + public int hideWebLinkrefreshMax; + public int webLinkLimittimes; + public int hideWebLinkLimittimes; + public int wvType; + public int darkWebTimesCT; + public int refreshMax; + public int wvthrough; + public int isMagic; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs.meta new file mode 100644 index 0000000..136c940 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/GameUrlsModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c3ad40552b3dc54d9732eb05b53350d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs new file mode 100644 index 0000000..d5bfffe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public interface IDataList + { + List dataList { get; set; } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs.meta new file mode 100644 index 0000000..481de47 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/IDataList.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 68bd7950acaf4a1db949aef52eb2147b +timeCreated: 1721208372 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs new file mode 100644 index 0000000..b9d919b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class LangDisplayModel:IDataList + { + public List dataList { get; set; } + } + + public class LangDisplay + { + public int id; + public string desc; + public string language; + public string name; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs.meta new file mode 100644 index 0000000..912b000 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LangDisplayModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fb76f87627e849259b4a1faba1d1d165 +timeCreated: 1692609227 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs new file mode 100644 index 0000000..6d288cd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class LargerewardNumModel : IDataList + { + public List dataList { get; set; } + } + + public class LargerewardNum + { + public int id; + public float[] cash_1; + public float[] cash_2; + public float[] cash_3; + public float[] nor_1; + public float[] nor_2; + public float[] nor_3; + public float rv_1; + public float rv_2; + public float rv_3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs.meta new file mode 100644 index 0000000..f3decff --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LargerewardNumModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91ab827f55980734fa3bd52c07c75c92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs new file mode 100644 index 0000000..1a6b592 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class LevelDataModel : IDataList + { + public List dataList { get; set; } + } + + public class LevelData + { + public int id; + public string name; + public int screwCount; + public int screwTypeCount; + public int[] panelCountRangePerLayer; + public float startWeightRatio; + } + public class LevelDataModel_2 : IDataList + { + public List dataList { get; set; } + } + public class LevelDataModel_3 : IDataList + { + public List dataList { get; set; } + } + +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs.meta new file mode 100644 index 0000000..a4ca15f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/LevelDataModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7f786f9cc4d044f0921915560e9c5ca0 +timeCreated: 1725871976 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs new file mode 100644 index 0000000..4f8709b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Linq; + +namespace ScrewsMaster +{ + public class MakeupModel : IDataList + { + public List dataList { get; set; } + + public Makeup GetData(int id) + { + return dataList.FirstOrDefault(makeup => makeup.id == id); + } + + } + + public class Makeup + { + public int id; + public decimal redeem_num; + public int require_time; + public int task_need; + public bool is_onetime; + + public int ad_need; + public int levels_need; + + public int item; + public int redeem_ID; + public int redeem_BR; + public int redeem_TH; + public int item_need; + public string desc; + public int AD_Down; + public int AD_CD; + public int AD_Limit_times; + public int Login_Limit_times; + public int Active_time; + public int Active_time_Down; + public int Active_Limit_times; + } + public class MakeupModel_2 : IDataList + { + public List dataList { get; set; } + + public Makeup_2 GetData(int id) + { + return dataList.FirstOrDefault(makeup => makeup.id == id); + } + + } + + public class Makeup_2 + { + public int id; + public int item_need; + public bool is_onetime; + public int task_need; + public int ad_need; + public int item; + public int levels_need; + public int AD_Down; + public int AD_Limit_times; + public int Login_Limit_times; + public int Active_time; + public int Active_time_Down; + public int Active_Limit_times; + public int Reset_time; + public float ADIncrease; + public int PayIncrease; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs.meta new file mode 100644 index 0000000..ff59bc9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/MakeupModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ccc8190d0599fff48b2caed678a084a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs new file mode 100644 index 0000000..2f884b9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PaidcoinsModel:IDataList + { + public List dataList { get; set; } + } + + public class Paidcoins + { + public int id; + public int Actual_coins; + public int Discount_rate; + public float Payment_amount; + public float Payment_amount2; + public int receive_CD; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs.meta new file mode 100644 index 0000000..1df8567 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaidcoinsModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 313872374088cbb4fa12c1a90eb8c289 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs new file mode 100644 index 0000000..0e169f6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PassingTaskModel:IDataList + { + public List dataList { get; set; } + } + + public class PassingTask + { + public int id; + public bool is_com_reward; + public bool is_double; + public string text_read_ru; + public string text_read; + public string desc; + public int tol_num; + public int reward_num; + public bool is_get; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs.meta new file mode 100644 index 0000000..813cd4e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassingTaskModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b52103c07b44c7542bb95c108331e805 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs new file mode 100644 index 0000000..f556094 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PassportrewardsModel : IDataList + { + public List dataList { get; set; } + } + + public class Passportrewards + { + public int id; + public int Eliminating_quantity; + public int Free_rewards_num; + public int Free_rewards_type; + public int Paid_rewards_num; + public int Paid_rewards_type; + public int Passportrewards_CD; + } + public class MultigiftModel: IDataList + { + public List dataList { get; set; } + } + + public class Multigift + { + public int id; + public float Paid_price; + public float Paid_price2; + + public int coins_quantity; + + public int[] props_type; + public int[] props_quantity; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs.meta new file mode 100644 index 0000000..1279292 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PassportrewardsModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 62ce2d31f0c73c3438cdbd4ded49e1d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs new file mode 100644 index 0000000..d497ec7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PaymentTypeModel : IDataList + { + public List dataList { get; set; } + } + + public class PaymentType + { + public int id; + public string card_name; + public List countryKey; + public string logo_id; + public int multi; + public string payer; + public string payicon; + public Dictionary test; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs.meta new file mode 100644 index 0000000..662f3ba --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PaymentTypeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b300ebad8093ce458b409869e3bbad3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs new file mode 100644 index 0000000..d1343f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PrizeWheelDataModel : IDataList + { + public List dataList { get; set; } + } + + public class PrizeWheelData + { + public int id; + public int wheel_item; + public float quantity; + public int weight; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs.meta new file mode 100644 index 0000000..bc6dd49 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/PrizeWheelDataModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 040de92fd808441aa0bbce1dc1435774 +timeCreated: 1728719796 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs new file mode 100644 index 0000000..57974d9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class RewardNumModel : IDataList + { + public List dataList { get; set; } + } + + public class RewardNum + { + public int id; + public int[] cash_1; + public int[] cash_2; + public int[] cash_3; + + public float[] nor_1; + public float[] nor_2; + public float[] nor_3; + public float rv_1; + public float rv_2; + public float rv_3; + } + + + public class PaidgiftModel : IDataList + { + public List dataList { get; set; } + } + + public class Paidgift + { + public int Paid_type; + public float Paid_price; + + public int coins_quantity; + public int[] props_quantity; + public float Paid_price2; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs.meta new file mode 100644 index 0000000..0917fdc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/RewardNumModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a03954130e2b4bc9acffaf4f0df89e1c +timeCreated: 1692609474 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs new file mode 100644 index 0000000..125129b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class SignDailyRewardModel + { + public List dataList; + } + + public class SignDailyReward + { + public int id; + public bool is_com_reward; + public bool is_double; + public int[] item1; + public int multi; + public decimal[] quantity; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs.meta new file mode 100644 index 0000000..eede0eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SignDailyRewardModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 536f4ceda45a48319cdb0a9540535bad +timeCreated: 1726109077 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs new file mode 100644 index 0000000..4331cbe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class SmallrewardNumModel : IDataList + { + public List dataList { get; set; } + } + + public class SmallrewardNum + { + public int id; + public float[] cash_1; + public float[] cash_2; + public float[] cash_3; + public float[] nor_1; + public float[] nor_2; + public float[] nor_3; + public float rv_1; + public float rv_2; + public float rv_3; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs.meta new file mode 100644 index 0000000..5aad315 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/SmallrewardNumModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a89163cfd21b1b04f87e56b3cd250ee9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs new file mode 100644 index 0000000..7a6ebbc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class TurntableModel:IDataList + { + public List dataList { get; set; } + } + + public class Turntable + { + public int id; + public int Seq; + public int wheel_item; + public int quantity; + public int weight; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs.meta new file mode 100644 index 0000000..019f61d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/TurntableModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: dae01d6b93cc45149324ea3b3601fbfe +timeCreated: 1704963556 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs new file mode 100644 index 0000000..032eb4d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine.Scripting; + +namespace ScrewsMaster +{ + public class exBrPoolModel : IDataList + { + public List dataList { get; set; } + public List config_name_list; + public List config_money_list; + public exBrPool GetData(int id) + { + return dataList.FirstOrDefault(makeup => makeup.id == id); + } + } + + public class exBrPool + { + public int id; + public string user_name; + public string amount; + } + public class exBrPoolModel_2 : IDataList + { + public List dataList { get; set; } + public List config_name_list; + public List config_money_list; + public exBrPool_2 GetData(int id) + { + return dataList.FirstOrDefault(makeup => makeup.id == id); + } + } + + public class exBrPool_2 + { + public int id; + public string user_name; + public string amount; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs.meta new file mode 100644 index 0000000..85b40ee --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Game/exBrPoolModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1f9625550f492e4f81175c313aae91a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question.meta new file mode 100644 index 0000000..a0c798d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c106e3eed08844e18ea4e84cdd5053e3 +timeCreated: 1692758689 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs new file mode 100644 index 0000000..059dce0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class QuestionBankModel + { + public List dataList; + } + + public class QuestionBank + { + public int id; + public string[] tableKey; + public List type; + public string desc; + public int weight; + public string desc_es; + public string desc_pt; + public string desc_ru; + public string icon_name; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs.meta new file mode 100644 index 0000000..7a0d4f3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionBankModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4fcdd0ed4df8446e9aec129dbaee870b +timeCreated: 1692758698 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs new file mode 100644 index 0000000..4cd9c6b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs @@ -0,0 +1,27 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class QuestionModel + { + public List dataList; + + public Question GetRandomQuestion() + { + int index = Random.Range(0, dataList.Count); + return dataList[index]; + } + } + + public class Question + { + public int id; + public int Picture_name; + public string subject; + public string answer_one; + public string answer_two; + public string answer_three; + public string answer_four; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs.meta new file mode 100644 index 0000000..47261b9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Config/Question/QuestionModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4bee883971854d8ebeb6241c256f1c12 +timeCreated: 1692759890 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game.meta new file mode 100644 index 0000000..e402f13 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e4115be74f64478e91e3503927734ab9 +timeCreated: 1692323976 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs new file mode 100644 index 0000000..7dda313 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class GameQuestionData + { + public int questionBankID; + public string questionName; + public int questionTableID; + public int questionType; + public string questionTitle; + public string[] answer; + public int logoId; + public string desc; + public bool isGuide; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs.meta new file mode 100644 index 0000000..8e11cd1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/GameQuestionData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 92c56a131d499d242b2862ea94fd2c76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs new file mode 100644 index 0000000..f89ff07 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs @@ -0,0 +1,50 @@ +namespace ScrewsMaster +{ + public class LoginModel : BaseModel + { + public long uid; + public bool new_player; + public string token; + public long expires_at; + public string country; + public bool is_magic; + public string invite_code; + public string invite_url; + public long last_login_time; + public string play_data; + public string setting; + public string cdn_url; + public long login_time; + public long reg_time; + public bool is_black_ip; + public string ConfigType; + public long play_data_ver; + public Preferences preferences; + public bool debug_log = true; + public int enwp; + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + } + + protected override void RemoveListener() + { + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs.meta new file mode 100644 index 0000000..2efcbea --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/LoginModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2344f926dc38bb449b5663c4d75ed814 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs new file mode 100644 index 0000000..5ce95cc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PlayData + { + public Dictionary data; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs.meta new file mode 100644 index 0000000..03bb7af --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/PlayData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb09473f43a1ee34d82911835fdb7a1c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs new file mode 100644 index 0000000..bba54f2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs @@ -0,0 +1,14 @@ +namespace ScrewsMaster +{ + public partial class Preferences + { + public int gameStartCount = 0; + public int loginGameTodayTimes = 0; + public int videoEffective_count; + public bool isLogEffective = false; + public long data_ver = 0; + public bool haveBeenGameStart = false; + public string date = string.Empty; + public int lastLoginDays = 0; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs.meta new file mode 100644 index 0000000..09fc614 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Base.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa1e3104990281d4e877ab367549a0f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs new file mode 100644 index 0000000..76824eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public partial class Preferences + { + public decimal currency102; + public decimal maxCurrency102; + public int thisDayWatchSlyderVideoNum; + public long nextNewDayTime; + public string playerName; + public int playerAvatarId; + public List signState; + public List completeGuideList; + public bool isResetGuide; + public int gameOfCount; + public int winOfGame; + public List onceStatistcList; + public int watchVideoBeginSum; + public bool isGod; + public string facebookId; + public string facebookName; + public string facebookAvatarUrl; + public bool isFaceBookLogin; + public bool isGuideFinish; + public int currentQuestionIndex; + public int GameLevel = 1; + public int BattleExp = 0; + public int TotalCoins = 50; + public int AdWatchCount = 0; + public int PrizeWheelCount = 0; + public long PrizeWheelTime = 0; + public bool PayBox1 = false; + public bool PayBox2 = false; + public Dictionary Items = new Dictionary(); + public bool exchangeBindGuide; + public string exchangeAccount; + public string exchangeName; + public List haveRedeemedSkin; + public int inUseSkin; + public string paypalAccount; + public bool isSuccessRedeem; + public List inviteDataList; + public List inviteRecordList; + public List inviteMakeUpHistoryList; + public bool isEditInviteCode = false; + public decimal webViewMakeUpOnlineTime; + public decimal webViewADTaskOnlineTime; + public bool isShowRewardFly101 = false; + public bool isShowRewardFly102 = false; + + public decimal playReawrd111; + public bool isShowRewardFly111 = false; + public int openRewardCount = 0; + public int interRewardShowLevel = -1; + public bool isShowOpenReward = false; + public bool isRealProcessing; + public int realWatchVideo; + public bool isClickH5Icon; + public long lastClickMainIconTime; + public int interH5Url1Count; + public int interH5Url2Count; + public List makeupSatisfyGears; + public int makeupRealReportGear; + public bool isLastH5Tab; + public long nextOpenWheelStampTime; + public long adCashFlyShowTime; + public List adTaskDataList; + public int adTaskCount; + public int correctAnswerCount; + public List achievementAnswerList; + public int h5StayTime; + public int videoWatchCount; + public int signInCount; + public List achievementSignInList; + public int inviteCount; + public bool naiveStepFinish; + public List makeupTaskHistory; + public decimal makeupTaskH5Time; + public bool makeupConditionMark; + public Dictionary statisticDictionary; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs.meta new file mode 100644 index 0000000..c635cd9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/Preferences_Logic.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c96714641282bd4599d9910970cc804 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs new file mode 100644 index 0000000..59b11d3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs @@ -0,0 +1,207 @@ +using FairyGUI; +using System.Linq; +using UnityEngine; + +namespace ScrewsMaster +{ + using System; + using System.Collections.Generic; + + [Flags] + public enum RewardDisplayType + { + None = 0b_0000_0000, + + + Number = 0b_0000_0001, + + + ValueChange = 0b_0000_0010, + + + Dialog = 0b_0000_0100, + + + RewardFly = 0b_0000_1000, + } + + + public enum RewardOrigin + { + None, + GameWin, + H5Icon, + LuckyWheel, + SignIn, + PrizeWheel, + AdTask, + Play, + Achievement, + H5Fly101, + } + + public enum RewardCondition + { + None, + AD, + } + + + public class RewardSingleData + { + public int id; + public int type; + public decimal value; + public decimal multiRate; + public decimal rate; + + public decimal GetTotalValue() + { + return Math.Round(value * rate, 2); + } + + public RewardOrigin origin; + public Vector2 startPosition; + public Vector2 endPosition; + + public RewardSingleData(int id, decimal value, RewardOrigin origin) + { + this.id = id; + this.value = value; + this.origin = origin; + InitData(); + } + + private void InitData() + { + InitRate(); + InitMultiRate(); + } + + private void InitRate() + { + if (rate == 0) + { + rate = 1; + } + } + + private void InitMultiRate() + { + if (multiRate == 0) + { + multiRate = 1; + } + } + + public void InitFlyPosition() + { + InitStartPosition(); + InitEndPosition(); + } + + private void InitStartPosition() + { + if (startPosition == Vector2.zero) + { + startPosition = GRoot.inst.size / 2; + } + } + + private void InitEndPosition() + { + if (endPosition == Vector2.zero && id != 0) + { + var itemUI = GameHelper.GetItemUI(id); + var gObject = itemUI?.GetChildAt(1); + if (gObject != null) + { + endPosition = itemUI.LocalToRoot((Vector2)gObject.position + gObject.size / 2, GRoot.inst); + } + } + } + + public bool IsCanFly() + { + return IsCanFly(id); + } + + public static bool IsCanFly(int id) + { + return id == 101 || id == 102 || id == 111; + } + } + + + public class RewardData + { + private List rewardDataList; + + public RewardDisplayType displayType; + + public RewardCondition condition; + + private Action mOnCompleted; + + public bool isSingle; + + public decimal ctRate; + + public RewardData() + { + InitData(); + } + + public void AddCompleted(Action onCompleted) + { + mOnCompleted += onCompleted; + } + + + public void OnCompleted(bool isSuccess) + { + mOnCompleted?.Invoke(isSuccess); + } + + public void AddReward(RewardSingleData rewardSingleData) + { + rewardDataList ??= new List(); + + var isNeedAdd = true; + + foreach (var data in rewardDataList.Where(data => data.id == rewardSingleData.id)) + { + data.value += rewardSingleData.value; + isNeedAdd = false; + break; + } + + if (isNeedAdd) + { + rewardDataList.Add(rewardSingleData); + } + } + + private void InitData() + { + if (rewardDataList != null) + { + rewardDataList.Clear(); + } + else + { + rewardDataList = new List(); + } + } + + public List GetRewardDataList() + { + return rewardDataList; + } + + public int GetRewardFlyCount() + { + return GetRewardDataList().Count(rewardSingleData => rewardSingleData.IsCanFly()); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs.meta new file mode 100644 index 0000000..d11e225 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ab2c0def1063b543b89fed5d33423d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs new file mode 100644 index 0000000..c01016a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs @@ -0,0 +1,90 @@ +using System; +using UnityEngine; + +namespace ScrewsMaster +{ + public class RewardDisplayData + { + public RewardSingleData rewardSingleData; + public bool isPlayAudio; + public string audioName; + public bool isNeedFly; + public bool isNeedValueChange; + public event Action UpdateCb; + public event Action EndEventCb; + public event Action UICloseEventCb; + private decimal coinAddTime = 0.45m; + public bool isSingle; + private decimal showValue; + private decimal showAddValue; + private bool isCompleted; + + public RewardDisplayData(RewardSingleData rewardSingleData) + { + this.rewardSingleData = rewardSingleData; + showValue = rewardSingleData.GetTotalValue(); + showAddValue = showValue; + } + + public void SetUpdate(Action updateCb) + { + UpdateCb = updateCb; + } + + public void Update() + { + if (isCompleted) + { + return; + } + + var val = showValue * Convert.ToDecimal(Time.deltaTime) / coinAddTime; + if (showAddValue >= val) + { + showAddValue -= val; + if (isNeedValueChange) + { + UpdateCb?.Invoke(val); + } + } + else if (showAddValue > 0) + { + if (isNeedValueChange) + { + UpdateCb?.Invoke(showAddValue); + } + + showAddValue = 0; + } + else + { + EndEvent(); + } + } + + + public void SetUpdateComplete(Action endEventCb) + { + EndEventCb = endEventCb; + } + + public void EndEvent() + { + EndEventCb?.Invoke(); + EndEventCb = null; + isCompleted = true; + } + + public void UICloseEvent() + { + UICloseEventCb?.Invoke(); + } + + public void Dispose() + { + UpdateCb = null; + EndEventCb = null; + UICloseEventCb = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs.meta new file mode 100644 index 0000000..d595589 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Game/RewardDisplayData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96c535e1964438c499609fb7a2376428 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network.meta new file mode 100644 index 0000000..c57261b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a9eafcb38d704b73b585e6cf09500c46 +timeCreated: 1692324038 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common.meta new file mode 100644 index 0000000..d72011a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7f5a30e987967a64a9eaaaebee0452c9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs new file mode 100644 index 0000000..feaf464 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs @@ -0,0 +1,18 @@ +namespace ScrewsMaster +{ + public class RespDebugData + { + public long uid; + public string device; + public string os_ver; + public string network; + public string device_id; + public string pack_name; + public string version; + public string channel; + public string level; + public string message; + public string stacktrace; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs.meta new file mode 100644 index 0000000..0926985 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespDebugData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9f39e3d1bf01df045a747578f4116192 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs new file mode 100644 index 0000000..347d897 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class RespLoginFunnelData + { + public long uid; + public string trace_id; + public string device_id; + public string pack_name; + public string version; + public string channel; + public string type; + public string payload; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs.meta new file mode 100644 index 0000000..0db79db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Common/RespLoginFunnelData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1f239ecb4377814a8d09a33c9ae35f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login.meta new file mode 100644 index 0000000..e83486f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 150775511ca7461893ce10ec8fde523d +timeCreated: 1692324525 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs new file mode 100644 index 0000000..efed9f0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs @@ -0,0 +1,11 @@ +namespace ScrewsMaster +{ + public class RequestLoginData + { + public string device_id; + public string pack_name; + public string app_version; + public string channel; + public bool sim; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs.meta new file mode 100644 index 0000000..94a1981 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/RequestLoginData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 379445958647447cb9d8c5bdc4a6b545 +timeCreated: 1692324059 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs new file mode 100644 index 0000000..ab4787b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs @@ -0,0 +1,9 @@ +namespace ScrewsMaster +{ + public class ResponseData + { + public int code; + public string msg; + public object data; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs.meta new file mode 100644 index 0000000..a1d88ff --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 63d467dfdd754d0fb05cc967327761e7 +timeCreated: 1692339515 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs new file mode 100644 index 0000000..bb0a811 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class ResponseFunnelData + { + public long uid; + public string trace_id; + public string device_id; + public string pack_name; + public string version; + public string channel; + public string type; + public string payload; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs.meta new file mode 100644 index 0000000..5881d71 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/Login/ResponseFunnelData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 68ed5146b075ecb489264a49e66ee441 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData.meta new file mode 100644 index 0000000..0d9987f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aa0c21c1bc4d4bb08e3fe22e1e301ec1 +timeCreated: 1692344204 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs new file mode 100644 index 0000000..99097d3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs @@ -0,0 +1,8 @@ +namespace ScrewsMaster +{ + public class RequestResultData + { + public int type; + public string result; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs.meta new file mode 100644 index 0000000..ad73962 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestResultData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 38b47c2fc5534bf2bbd7efc4bcb41df9 +timeCreated: 1730960720 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs new file mode 100644 index 0000000..844a6d4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs @@ -0,0 +1,8 @@ +namespace ScrewsMaster +{ + public class RequestSavePlayData + { + public long version; + public string data; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs.meta new file mode 100644 index 0000000..bbfee40 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestSavePlayData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 64287b3c02aa4e9d82576052db1ffa86 +timeCreated: 1692344216 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs new file mode 100644 index 0000000..f02ffd2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs @@ -0,0 +1,16 @@ +namespace ScrewsMaster +{ + public class RequestStageData + { + public int level; + public int layer; + public int item_type; + public int total_item; + public int remove_item; + public int[] item_costs; + public bool pass; + public int begin_time; + public int end_time; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs.meta new file mode 100644 index 0000000..ed84468 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/Network/SavePlayData/RequestStageData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2c2172ac39bc4a909b5964f5906033a3 +timeCreated: 1730950643 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent.meta new file mode 100644 index 0000000..9234917 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 52e46b6ff2dd1814e87e71a316a195a1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs new file mode 100644 index 0000000..73ace08 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs @@ -0,0 +1,14 @@ +namespace ScrewsMaster +{ + public class RequestSendEventH5Info + { + public string link; + public string type; + } + + public class ResponseSendEventH5Info + { + public string link; + public int times; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs.meta new file mode 100644 index 0000000..cae2b2c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Define/Model/WebEvent/RequestSendEventH5Info.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 508f7b9e8a834854a9c1ea1b16fc61d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper.meta b/Assets/CrazyZoo/Runtime/Logic/Helper.meta new file mode 100644 index 0000000..ebc5afd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5d35253e05f9aa54b8beaa3dde869fa0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs new file mode 100644 index 0000000..ef003c1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs @@ -0,0 +1,52 @@ +using System.IO; +using System.Text; +using System.Security.Cryptography; + +namespace ScrewsMaster +{ + public class AESForFileKit + { + private static readonly byte[] Salt = Encoding.UTF8.GetBytes(CrazyZooConstant.nifldg); + private const int Iterations = 1000; + + public static void EncryptFile(string inputPath, string outputPath, string password) + { + var passwordBytes = Encoding.UTF8.GetBytes(password); + var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read); + var outputStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write); + + using var aes = new AesManaged(); + var key = new Rfc2898DeriveBytes(passwordBytes, Salt, Iterations); + aes.Key = key.GetBytes(aes.KeySize / 8); + aes.IV = key.GetBytes(aes.BlockSize / 8); + using var cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(), CryptoStreamMode.Write); + inputStream.CopyTo(cryptoStream); + cryptoStream.FlushFinalBlock(); + cryptoStream.Close(); + outputStream.Close(); + inputStream.Close(); + } + + public static byte[] DecryptToBytes(string inputPath, string password, out int dataSize) + { + var passwordBytes = Encoding.UTF8.GetBytes(password); + var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read); + var outputMemoryStream = new MemoryStream(); + + using (var aes = new AesManaged()) + { + var key = new Rfc2898DeriveBytes(passwordBytes, Salt, Iterations); + aes.Key = key.GetBytes(aes.KeySize / 8); + aes.IV = key.GetBytes(aes.BlockSize / 8); + using (var cryptoStream = new CryptoStream(inputStream, aes.CreateDecryptor(), CryptoStreamMode.Read)) + { + cryptoStream.CopyTo(outputMemoryStream); + } + } + + var outputBytes = outputMemoryStream.ToArray(); + dataSize = outputBytes.Length; + return outputBytes; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs.meta new file mode 100644 index 0000000..f4f1b65 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/AESForFileKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 429efb8e8784c764387a3d6f29225252 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs new file mode 100644 index 0000000..f935e45 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs @@ -0,0 +1,118 @@ +// #if UNITY_EDITOR +using System.Text; +using UnityEngine; +using UnityEngine.Events; +using Object = UnityEngine.Object; + +namespace ScrewsMaster.Editor +{ + public class AssetDataBaseKit : Singleton, ILoadAsset + { + private string assetRootPath = "CrazyZooAssets/"; + + public T GetAsset(string dfsad, string sa) where T : Object + { + + // try + // { + var asPath = new StringBuilder(AssetPathFormat(dfsad)); + if (sa.EndsWith("!a.png")) + { + // assetFullPath = AssetPathFormat(dfsad, sa); + } + else + { + sa = sa.Split(".")[0]; + } + var asset = Resources.Load(asPath.ToString() + "/" + sa); + + if (asset == null) + { + Debug.LogError($"[Jarvis] [AssetDataBaseKit] 未能加载资源: {asPath}/{sa}"); + return default; // 或者返回一个备用资源,或者抛出异常 + } + + return asset; + // } + // catch (System.Exception e) + // { + // Debug.Log($"[Jarvis] [AssetDataBaseKit] 错误堆栈:{e.StackTrace}"); + // Debug.LogError($"[Jarvis] [AssetDataBaseKit] 加载资源时发生错误: {e.Message}"); + // return default; // 或者返回一个备用资源,或者抛出异常 + // } + // var assetPath = new StringBuilder(AssetPathFormat(dfsad)); + // var assetFullPath = ""; + + // if (sa.EndsWith("!a.png")) + // { + // assetFullPath = AssetPathFormat(dfsad, sa); + // } + // else + // { + // sa = sa.Split(".")[0]; + // var assets = AssetDatabase.FindAssets(sa, new[] { assetPath.ToString() }); + + // var nameFilter = sa + "."; + // foreach (var temp in assets) + // { + // var fullPath = AssetDatabase.GUIDToAssetPath(temp); + // if (fullPath.Contains(nameFilter)) + // { + // assetFullPath = fullPath; + // break; + // } + // } + // } + + // var asset = AssetDatabase.LoadAssetAtPath(assetFullPath); + // return asset; + } + + public void GetAsset(string dfsad, string sa, UnityAction onCompleted) where T : Object + { + + // try + // { + var asset = GetAsset(dfsad, sa); + onCompleted?.Invoke(asset); + // } + // catch (System.Exception e) + // { + // Debug.Log($"[ Jarvis ] [ GetAsset ] 错误堆栈:{e.StackTrace}"); + + // Debug.LogError($"[ Jarvis ] [ GetAsset ] 异步加载资源 {sa} 时发生错误: {e.Message}"); + // onCompleted?.Invoke(default); // 可能需要通知用户加载失败 + // } + } + + public void RecycleAsset(string assetUrl, UnityAction onCompleted) + { + onCompleted?.Invoke(); + } + + private string AssetPathFormat(string assetUrl, string assetName) + { + var replace = assetUrl.Replace(".", "/"); + var sb = new StringBuilder(replace); + var folderPath = sb + "/"; + + var assetPath = $"{assetRootPath}{folderPath}{assetName}"; + return assetPath; + } + + private string AssetPathFormat(string assetUrl) + { + var assetPath = $"{assetRootPath}{assetUrl.Replace(".", "/")}"; + return assetPath; + } + + public static T GetAssetstatic(string assetUrl, string assetName) where T : Object + { + var assetPath = $"{"CrazyZooAssets/"}{assetUrl.Replace(".", "/")}"; + assetName = assetName.Split(".")[0]; + var asset = Resources.Load(assetPath.ToString() + "/" + assetName); + return asset; + } + } +} +// #endif \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs.meta new file mode 100644 index 0000000..a937714 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/AssetDataBaseKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ab04c207993344cca1762aee3d1e840f +timeCreated: 1683361552 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs new file mode 100644 index 0000000..13e4a12 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs @@ -0,0 +1,426 @@ +using System; +using FairyGUI; +using System.Text; +using UnityEngine; +using System.Collections.Generic; +using Application = UnityEngine.Application; +using Random = UnityEngine.Random; + +namespace ScrewsMaster +{ + public static class CommonHelper + { + public static Dictionary activeTimes = new Dictionary(); +public static Dictionary activeTimes_saveingpot = new Dictionary(); + public static int GetIndexByChanceList(int[] chanceList) + { + float total = 0; + for (int i = 0; i < chanceList.Length; i++) + { + total += chanceList[i]; + } + + float result = Random.Range(0, total); + float tmpTotal = 0; + for (int i = 0; i < chanceList.Length; i++) + { + float chance = chanceList[i]; + tmpTotal += chance; + if (result < tmpTotal) + { + return i; + } + } + + + return -1; + } + + public static bool GetBoolByChance(float chance) + { + var value = UnityEngine.Random.Range(0, 1f); + if (value <= chance) + return true; + return false; + } + + public static void SetActive(this Component component, bool isActive) + { + component.gameObject.SetActive(isActive); + } + + public static string GetAppSavePath() + { + return Application.persistentDataPath; + } + + public static GTweener FadeIn(GObject obj, float duration = 0.3f, float delay = 0) + { + if (obj != null) + { + obj.alpha = 0.5f; + return obj.TweenFade(1, duration).SetDelay(delay); + } + + return null; + } + + public static GTweener FadeOut(GObject obj, float duration = 0.3f, float delay = 0) + { + if (obj != null) + { + obj.alpha = 1; + return obj.TweenFade(0f, duration).SetDelay(delay); + } + + return null; + } + + private static float clickTime; + + public static bool IsClickNoQuick() + { + if (Time.time < clickTime) + { + clickTime = Time.time + 0.1f; + return false; + } + + clickTime = Time.time + 0.3f; + return true; + } + + public static void InitGButton(GObject button, Action action, bool isNetworkCheck = false, + bool isQuickClickCheck = true) + { + button?.onClick.Set(() => + { + if (isQuickClickCheck && !IsClickNoQuick()) + { + return; + } + + action?.Invoke(); + }); + } + + public static string TimeFormat(int second, CountDownType countDownType = CountDownType.Second, + string dayFormat = "") + { + var result = new StringBuilder(); + if (second < 0) + { + second = 0; + } + + if (countDownType == CountDownType.Second) + { + result.Append(second); + return result.ToString(); + } + + int tmpSecond; + + + if (second >= 60) + { + tmpSecond = second % 60; + } + else + { + tmpSecond = second; + } + + result.Append(tmpSecond); + + if (tmpSecond < 10) + { + result.Insert(0, 0); + } + + + int tmpMin = second / 60; + + if (countDownType == CountDownType.Minute) + { + result.Insert(0, ":"); + result.Insert(0, tmpMin); + return result.ToString(); + } + + int tmpHour = tmpMin / 60; + + if (countDownType == CountDownType.Hour) + { + if (tmpMin >= 60) + { + tmpMin %= 60; + } + + result.Insert(0, ":"); + result.Insert(0, tmpMin); + if (tmpMin < 10) + { + result.Insert(0, 0); + } + + result.Insert(0, ":"); + result.Insert(0, tmpHour); + if (tmpHour < 10) + { + result.Insert(0, 0); + } + + return result.ToString(); + } + + int tmpDay = tmpHour / 24; + + if (countDownType == CountDownType.Day) + { + if (tmpMin >= 60) + { + tmpMin %= 60; + } + + result.Insert(0, ":"); + result.Insert(0, tmpMin); + if (tmpMin < 10) + { + result.Insert(0, 0); + } + + if (tmpHour >= 24) + { + tmpHour %= 24; + } + + result.Insert(0, ":"); + result.Insert(0, tmpHour); + + if (tmpHour < 10) + { + result.Insert(0, 0); + } + + if (string.IsNullOrEmpty(dayFormat)) + { + dayFormat = "Days"; + } + + result.Insert(0, $" {dayFormat} "); + result.Insert(0, tmpDay); + } + + return result.ToString(); + } + + public static string FormatTime(int second, + CountDownType countDownType = CountDownType.Second, string dayFormat = "") + { + StringBuilder result = new StringBuilder(); + if (second < 0) + { + second = 0; + } + + if (countDownType == CountDownType.Second) + { + result.Append(second); + return result.ToString(); + } + + int tmpSecond; + + if (second >= 60) + { + tmpSecond = second % 60; + } + else + { + tmpSecond = second; + } + + result.Append(tmpSecond); + + if (tmpSecond < 10) + { + result.Insert(0, 0); + } + + + int tmpMin = second / 60; + + if (countDownType == CountDownType.Minute) + { + result.Insert(0, ":"); + result.Insert(0, tmpMin); + return result.ToString(); + } + + + int tmpHour = tmpMin / 60; + + if (countDownType == CountDownType.Hour) + { + if (tmpMin >= 60) + { + tmpMin %= 60; + } + + result.Insert(0, ":"); + result.Insert(0, tmpMin); + if (tmpMin < 10) + { + result.Insert(0, 0); + } + + result.Insert(0, ":"); + result.Insert(0, tmpHour); + if (tmpHour < 10) + { + result.Insert(0, 0); + } + + return result.ToString(); + } + + int tmpDay = tmpHour / 24; + + if (countDownType == CountDownType.Day) + { + if (tmpMin >= 60) + { + tmpMin %= 60; + } + + result.Insert(0, ":"); + result.Insert(0, tmpMin); + if (tmpMin < 10) + { + result.Insert(0, 0); + } + + if (tmpHour >= 24) + { + tmpHour %= 24; + } + + result.Insert(0, ":"); + result.Insert(0, tmpHour); + + if (tmpHour < 10) + { + result.Insert(0, 0); + } + + if (string.IsNullOrEmpty(dayFormat)) + { + dayFormat = "Days"; + } + + result.Insert(0, $" {dayFormat} "); + result.Insert(0, tmpDay); + } + + return result.ToString(); + } + + public static void RandomSortList(List list) + { + System.Random r = new System.Random(); + for (int i = 0; i < list.Count; i++) + { + int index = r.Next(list.Count); + (list[i], list[index]) = (list[index], list[i]); + } + } + public static int RandomInt(this IList array) + { + return Random.Range(array[0], array[1]); + } + public static int RandomRange(int[] range) + { + if (range == null) + { + return 0; + } + + if (range.Length == 2) + { + return RandomRange(range[0], range[1]); + } + else + { + return range[0]; + } + } + + public static int RandomRange(int begin, int end) + { + return Random.Range(begin, end); + } + + public static T RandomWeight(Dictionary weightDic) + { + int totalWeight = 0; + foreach (var weight in weightDic) + { + totalWeight += weight.Value; + } + + int randomWeight = Random.Range(0, totalWeight); + + int currWeight = 0; + foreach (var weight in weightDic) + { + currWeight += weight.Value; + if (randomWeight < currWeight) + { + return weight.Key; + } + } + + return default; + } + + public static int RandomWeight(List weightArray) + { + float totalWeight = 0; + for (var i = 0; i < weightArray.Count; i++) totalWeight += weightArray[i]; + + var randomWeight = Random.Range(0, totalWeight); + if (randomWeight >= totalWeight) return weightArray.Count - 1; + + float currWeight = 0; + for (var i = 0; i < weightArray.Count; i++) + { + currWeight += weightArray[i]; + if (randomWeight < currWeight) return i; + } + + return -1; + } + + public static int RandomRangeIncludeEnd(int[] range) + { + if (range == null) return 0; + if (range.Length == 2) + return RandomRange(range[0], range[1] + 1); + return range[0]; + } + + public static bool IsToday(long timestamp) + { + // 将时间戳转换为DateTime对象 + DateTime dateTime = DateTimeOffset.FromUnixTimeSeconds(timestamp).ToLocalTime().DateTime; + + // 获取今天的日期(不包含时间部分) + DateTime today = DateTime.Today; + + //Debug.Log($"dateTime: {dateTime.Date} \n today: {today} \n 是否是今天: {dateTime.Date == today}"); + // 比较日期部分是否相等 + return dateTime.Date == today; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs.meta new file mode 100644 index 0000000..289680a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/CommonHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 503da24caec74f59a9df8b84a7635133 +timeCreated: 1681803914 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs new file mode 100644 index 0000000..bb5fc3f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs @@ -0,0 +1,145 @@ +using System.IO; +using System.Linq; +using UnityEngine.Events; +using System.Text.RegularExpressions; +using Application = UnityEngine.Application; + + +#if UNITY_EDITOR +#endif + +namespace ScrewsMaster +{ + public class CrazyZooFileKit + { + private static bool isLog = true; + + private static string AssetBundleRootUrl = Application.streamingAssetsPath + "/CrazyZooAssets/AssetBundles/"; + private static string mFileUrl = Application.streamingAssetsPath + "/CrazyZooAssets/CrazyZooFile.txt"; + + public static string GetSavePath() + { + return Application.persistentDataPath; + } + + + public static string GetFilePath() + { + return $"{GetSavePath()}/CrazyZooAssets/"; + } + + public static void GetLocalAssetBundle(UnityAction onPreloadCompleted, UnityAction loadCompleted) + { + GetAssetFile(s => { GetMAssetBundle(s, onPreloadCompleted, loadCompleted); }); + } + + + public static void GetMAssetBundle(string content, UnityAction onPreloadCompleted, + UnityAction onLoadCompleted) + { + if (content.IsNullOrWhiteSpace()) + { + return; + } + + + var mFile = Regex.Split(content, "\r\n", RegexOptions.IgnoreCase).ToList(); + for (var i = mFile.Count - 1; i >= 0; i--) + { + var aotMetaAssemblyFile = mFile[i]; + if (string.IsNullOrEmpty(aotMetaAssemblyFile) || string.IsNullOrWhiteSpace(aotMetaAssemblyFile)) + { + mFile.RemoveAt(i); + } + } + + + var completedCount = mFile.Count; + onPreloadCompleted?.Invoke(completedCount); + + + foreach (var m in mFile) + { + if (m.IsNullOrWhiteSpace()) + { + onLoadCompleted?.Invoke(); + completedCount--; + if (completedCount <= 0) + { + OnGetAssetBundleCompleted(); + } + + continue; + } + + + var assetBundleNameInfoArray = + m.Split(CrazyZooConstant.fgklpk.ToCharArray()); + + var fileName = assetBundleNameInfoArray[0]; + + var mUrl = $"{AssetBundleRootUrl}{fileName}"; + + var mFilePath = $"{GetFilePath()}{fileName}"; + + if (File.Exists(mFilePath)) + { + var fileMD5 = MD5Kit.GetFileMD5(mFilePath); + + var fileMD5New = assetBundleNameInfoArray[1]; + if (fileMD5.Equals(fileMD5New)) + { + if (isLog) + { + } + + onLoadCompleted?.Invoke(); + completedCount--; + if (completedCount <= 0) + { + OnGetAssetBundleCompleted(); + } + + continue; + } + + if (isLog) + { + } + } + + + CrazyAsyKit.StartCoroutine(DownloadKit.GetFileFromUrl(mUrl, fileName, isSuccess => + { + if (isLog) + { + } + + onLoadCompleted?.Invoke(); + completedCount--; + if (completedCount <= 0) + { + OnGetAssetBundleCompleted(); + } + })); + } + } + + + private static void OnGetAssetBundleCompleted() + { + CrazyZooKit.Instance.InitManifest(CrazyZooConstant.lesest, + manifestInfo => + { + AppDispatcher.Instance.Dispatch(AppMsg.UI_LoadingInitAsset); + }); + } + + public static void GetAssetFile(UnityAction action) + { + + CrazyAsyKit.StartCoroutine(DownloadKit.GetTextFromUrl(mFileUrl, "CrazyZooFile", + content => { action?.Invoke(content); })); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs.meta new file mode 100644 index 0000000..e7cb1e7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/CrazyZooFileKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 583922fa338e2bb4e840ef1b59e376a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs new file mode 100644 index 0000000..124593c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs @@ -0,0 +1,157 @@ +using System.IO; +using UnityEngine; +using UnityEngine.Events; +using System.Collections; +using UnityEngine.Networking; + +namespace ScrewsMaster +{ + public class DownloadKit + { + private static void SaveTextFile(string content, string filePath, string fileName) + { + if (!Directory.Exists(filePath)) + { + Directory.CreateDirectory(filePath); + } + + File.WriteAllText($"{filePath}{fileName}.txt", content); + } + + public static void SaveFile(string content, string filePath, string fileName) + { + SaveTextFile(content, filePath, fileName); + } + + private static void SaveTextFile(byte[] content, string filePath, string fileName) + { + if (!Directory.Exists(filePath)) + { + Directory.CreateDirectory(filePath); + } + + File.WriteAllBytes($"{filePath}{fileName}.txt", content); + } + + public static IEnumerator GetTextFromUrl(string url, string fileName, UnityAction action = null, + string savePath = null, bool isSave = true) + { + var unityWebRequest = UnityWebRequest.Get(url); + yield return unityWebRequest.SendWebRequest(); + if (unityWebRequest.result is UnityWebRequest.Result.ConnectionError + or UnityWebRequest.Result.ProtocolError) + { + yield return null; + action?.Invoke(default); + yield break; + } + + var content = unityWebRequest.downloadHandler.text; + if (isSave) + { + savePath ??= CrazyZooFileKit.GetFilePath(); + SaveTextFile(content, savePath, fileName); + } + + yield return null; + action?.Invoke(content); + } + + public static IEnumerator GetTextFromUrl1(string url, string fileName, UnityAction action = null, + string savePath = null, bool isSave = true) + { + var www = new WWW(url); + + while (!www.isDone) + { + } + + if (isSave) + { + savePath ??= CrazyZooFileKit.GetFilePath(); + SaveTextFile(www.bytes, savePath, fileName); + } + + yield return null; + action?.Invoke(System.Text.Encoding.UTF8.GetString(www.bytes)); + } + + public static void GetTextFromUrl2(string url, string fileName, UnityAction action = null, + string savePath = null, bool isSave = true) + { + var www = new WWW(url); + + while (!www.isDone) + { + } + + if (isSave) + { + savePath ??= CrazyZooFileKit.GetFilePath(); + SaveTextFile(www.bytes, savePath, fileName); + } + + // yield return null; + action?.Invoke(System.Text.Encoding.UTF8.GetString(www.bytes)); + } + + public static IEnumerator GetFileFromUrl(string url, string fileName, UnityAction action) + { + var unityWebRequest = UnityWebRequest.Get(url); + yield return unityWebRequest.SendWebRequest(); + if (unityWebRequest.result is + UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError) + { + action?.Invoke(false); + yield break; + } + + var results = unityWebRequest.downloadHandler.data; + var savePath = CrazyZooFileKit.GetFilePath(); + + if (!Directory.Exists(savePath)) + { + Directory.CreateDirectory(savePath); + } + + var filePath = $"{savePath}{fileName}"; + var fileInfo = new FileInfo(filePath); + var fs = fileInfo.Create(); + fs.Write(results, 0, results.Length); + fs.Flush(); + fs.Close(); + fs.Dispose(); + yield return YieldConst.WaitForEndOfFrame; + action?.Invoke(true); + } + + public static string DownloadResourceSync(string url, string savePath, string fileName, bool isSave = true) + { + using (var unityWebRequest = UnityWebRequest.Get(url)) + { + unityWebRequest.SendWebRequest(); + + while (!unityWebRequest.isDone) + { + // 等待下载完成 + } + + if (unityWebRequest.result == UnityWebRequest.Result.ConnectionError || + unityWebRequest.result == UnityWebRequest.Result.ProtocolError) + { + Debug.LogError($"Error downloading resource: {unityWebRequest.error}"); + return ""; + } + + var content = unityWebRequest.downloadHandler.text; + if (isSave) + { + savePath ??= CrazyZooFileKit.GetFilePath(); + SaveTextFile(content, savePath, fileName); + } + + return content; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs.meta new file mode 100644 index 0000000..a3be9f4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/DownloadKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe2634714606b7443a3b12c2393423fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs new file mode 100644 index 0000000..6c61121 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs @@ -0,0 +1,1422 @@ +using System; +using FairyGUI; +using UnityEngine; +using DG.Tweening; +using Spine.Unity; +using System.Text; +using System.Collections.Generic; +using Random = UnityEngine.Random; +using System.Text.RegularExpressions; +using System.Linq; +using AppsFlyerSDK; +using static ScrewsMaster.NetworkKit; + +namespace ScrewsMaster +{ + public static class GameHelper + { + private static LoginModel loginModel; + + public static string GetRandomNum(int count) + { + var resultStr = new StringBuilder(); + for (int i = 0; i < count; i++) + { + resultStr.Append(Random.Range(0, 10)); + } + + return resultStr.ToString(); + } + + public static Vector3 FguiPotToUnityTrfLocalPot(Vector3 pot) + { + var v = Vector3.zero; + v.x = pot.x; + v.y = -pot.y; + v.z = pot.z; + return v; + } + + public static void ShowLoading(float min = 0.2f, float max = 1f, Action onCompleted = null) + { + ShowLoading(Random.Range(min, max), onCompleted); + } + + public static void ShowLoading(float time, Action onCompleted = null) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Open); + TimerHelper.mEasy.AddTimer(time, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close); + onCompleted?.Invoke(); + }); + } + + public static void ShowTips(string val, bool isLangue = false) + { + var valStr = val; + if (isLangue) + { + } + + var tipsData = JoastData.GetTips(valStr); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SCTipsUI_Open, tipsData); + } + + public static string GetCurrCountry() + { + var loginModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel; + var country = loginModel.country; + return country.ToUpper(); + } + + public static bool CheckAccountValidly(string account) + { + return CheckEMailValidly(account); + } + + public static bool CheckEMailValidly(string eMail) + { + if (eMail.IsNullOrWhiteSpace()) + { + return false; + } + + + const string expression = + @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; + return Regex.IsMatch(eMail, expression); + } + + public static bool CheckIDPhoneValidly(string phone) + { + if (phone.IsNullOrWhiteSpace() || phone.Length < 9 || phone.Length > 14) + { + return false; + } + + const string expression = + @"^[0-9]*$"; + return Regex.IsMatch(phone, expression); + } + + public static void ShowVideoAd(string adId, Action onCompleted) + { + MaxADKit.ShowVideo(adId, isSuccess => + { + if (isSuccess) + { + CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchVideoFinish); + look_interad_numbers = 0; + AddAdWatchCount(1); + AdOverEvent(1); + } + else + { + ShowTips("Ads Not Ready", true); + } + + onCompleted?.Invoke(isSuccess); + }); + } + + private static long CanShowInterstitialTime; + + + public static void ShowInterstitial(string key) + { + #if !UNITY_EDITOR + //if(Random.Range(0, 100)>ConfigSystem.GetConfig().interstitialtype) return; + MaxADKit.ShowInterstitial(key, isSuccess => + { + if (isSuccess) + { + CtrlDispatcher.Instance.Dispatch(CtrlMsg.WatchIntVideoFinish); + Debug.Log($"ShowInterstitial key==== {key}"); + if (key == "AfterReward") + { + NetworkKit.androidPointObject.@event = BuriedPointEvent.Apple_AD_event; + NetworkKit.androidPointObject.property = BuriedPointEvent.afterRewardAdEnd; + NetworkKit.androidPointObject.n = 1; + NetworkKit.PostWithHeader("/event/incrN", androidPointObject, (isSuccess, obj) => + { + }); + } + AdOverEvent(2); + } + }); +#endif + } + + + public static Vector2 GetUICenterPosition(GObject gObject, bool isCenter = false) + { + Vector2 centerPot = Vector2.zero; + if (!isCenter) + { + centerPot = gObject.size / 2; + } + + return gObject.LocalToRoot(Vector2.zero, GRoot.inst) + centerPot; + } + + public static void PlayFGUIFx(Transition transition, bool isReset = true, + PlayCompleteCallback onCompleted = null) + { + if (isReset) + { + if (transition.playing) + { + transition.Stop(); + } + } + + if (!transition.playing) + { + transition.Play(); + } + + transition.SetCompleteEvent(onCompleted); + } + + #region 时间判断 + + public static int GetTomorrowCountTime() + { + var today = DateTime.Now; + return 86400 - today.Hour * 3600 - today.Minute * 60 - today.Second; + } + + + public static long GetNowTime() + { + return DateTimeManager.Instance.GetServerCurrTimestamp(); + } + + + public static bool InToday(long time, int offset = 0, bool isInclude = false) + { + DateTime oldDate = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + oldDate = oldDate.AddSeconds(time); + oldDate = new DateTime(oldDate.Year, oldDate.Month, oldDate.Day); + + + var yesterday = DateTimeManager.Instance.GetCurrDateTime().AddDays(offset); + + yesterday = new DateTime(yesterday.Year, yesterday.Month, yesterday.Day); + if (isInclude) + { + return oldDate >= yesterday; + } + + return oldDate > yesterday; + } + + #endregion + + + public static void SetSelfAvatar(GLoader gLoader) + { + var avatarId = PreferencesMgr.Instance.PlayerAvatarId; + TextureHelper.SetAvatarToLoader(avatarId, gLoader); + } + + public static void SetSelfCountryFlag(GLoader gLoader) + { + SetCountryFlag(gLoader, GetLoginModel().country.ToLower()); + } + + + public static void SetCountryFlag(GLoader countryFlagLoader, string country) + { + var sprite = LoadKit.Instance.LoadSprite("Atlas.Flag", country.ToLower()); + if (sprite == null) + { + sprite = LoadKit.Instance.LoadSprite("Atlas.Flag", "us"); + } + + var countryTexture = new NTexture(sprite); + countryFlagLoader.texture = countryTexture; + } + + + public static string LimitName(string name, int length, string suffix = "...") + { + if (!string.IsNullOrEmpty(name) && name.Length > length) + { + name = name.Substring(0, length) + suffix; + } + + return name; + } + + + public static void SetName(GTextField gTextField, bool isLimit = false, int length = 6) + { + var name = PreferencesMgr.Instance.PlayerName; + if (isLimit) + { + name = LimitName(name, length); + } + + + gTextField.text = name; + } + + public static long GetUID() + { + return GetLoginModel().uid; + } + + public static void OnRiseUI(int itemId, UILayerType layerType = UILayerType.Highest) + { + var gObject = GetItemUI(itemId); + if (gObject != null) + { + SetUILayer(gObject, gObject.sortingOrder + 500, layerType); + } + } + + + public static void OnRiseUIRecover(int itemId, UILayerType layerType = UILayerType.Top) + { + var gObject = GetItemUI(itemId); + if (gObject == null) return; + SetUILayer(gObject, gObject.sortingOrder - 500, layerType); + UIManager.Instance.ResetGObjectUILayer(gObject); + } + + + public static GComponent GetItemUI(int itemId) + { + GComponent gObject = null; + switch (itemId) + { + case 101: + { + // if (UIManager.Instance.GetDynamicUI(UIConst.CurrencyUI) is CurrencyUI topUI) + // { + // gObject = topUI.ui.btn_currency; + // } + } + break; + } + + return gObject; + } + + public static void SetUILayer(GObject gObject, int sortingOrder, UILayerType layerType) + { + gObject.sortingOrder = sortingOrder; + UIManager.Instance.SetGObjectUILayer(layerType, gObject); + } + + public static LoginModel GetLoginModel() + { + if (loginModel != null) + { + return loginModel; + } + + return loginModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel; + } + + public static bool IsGiftSwitch() + { + //is_magic == false -> A 面 + + // return true; //zhushi + //return false;//zhushi + + return GetLoginModel().is_magic; + } + + + public static bool IsOpenGuide() + { + return true; + return false; + } + + public static bool CheckNameValidly(string name) + { + if (string.IsNullOrEmpty(name)) + { + return false; + } + + + const string expression = @"^[a-zA-Z]*$"; + return Regex.IsMatch(name, expression); + } + + + public static decimal Get102() + { + return PreferencesMgr.Instance.Currency102; + } + + + public static void InitGalleryView(GList glist, int numItems, float duration, + ListItemRenderer OnRendererPersonItem, + int itemWidth) + { + glist.itemRenderer = OnRendererPersonItem; + glist.numItems = numItems; + + var moveW = itemWidth * glist.numItems - glist.viewWidth; + DOVirtual.Float(0, moveW + 300, duration, prg => + { + if (prg > moveW) + { + return; + } + + glist.scrollPane.SetPosX(prg, false); + }).SetLoops(-1); + } + + public static SkeletonAnimation ShowFinger(GGraph target, GTweenCallback onComplete = null) + { + Action closeCallBack = null; + var handSpine = FXManager.Instance.SetFx(target, Fx_Type.fx_hand_pre, ref closeCallBack); + handSpine.state.SetAnimation(0, "idle", true); + var tweenBtn = CommonHelper.FadeIn(target); + tweenBtn.OnComplete(onComplete); + return handSpine; + } + + public static void ShowGuide(int _step, Vector2 _targeSize, Vector2 _targePos, Action _onEnd = null, + GObject _fingerGuideObj = null) + { + // var guideData = new GuideData() + // { + // targeSize = _targeSize, + // targePos = _targePos, + // step = _step, + // onEnd = _onEnd, + // fingerGuidePos = _targePos, + // }; + // + // if (_fingerGuideObj != null) + // { + // guideData.fingerGuidePos = GameHelper.GetUICenterPosition(_fingerGuideObj); + // } + // + // + // guideData.needMaskCloseEvent = _step == 10; + // + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GuideUI_Open, guideData); + // + // if (_step == 3) + // { + // } + } + + public static CommonModel GetCommonModel() + { + return ConfigSystem.GetConfig(); + } + + + public static string Get101String(decimal currency102 = -1) + { + if (currency102 == -1) + { + currency102 = GameHelper.Get102(); + } + + if (GameHelper.IsGiftSwitch()) + { + return $"${currency102:N}"; + } + else + { + return $"{currency102:N}"; + } + } + + public static string Get102Str(decimal currency102) + { + + var paymentTypeVO = GetPaymentTypeVO(); + if (IsGiftSwitch()) + { + return $"{paymentTypeVO.payicon}{currency102 * paymentTypeVO.multi:N}"; + } + else + { + return $"{currency102:N}"; + } + } + + public static string GetDeviceLanguage() + { + return "US"; + } + + public static bool IsContinuousSignIn() + { + if (PreferencesMgr.Instance.SignState.Count == 0) + { + return false; + } + + if (PreferencesMgr.Instance.SignState.Count >= 7) + { + return false; + } + + var tmp = PreferencesMgr.Instance.SignState[PreferencesMgr.Instance.SignState.Count - 1]; + return InToday(tmp, -1, true); + } + + public static void OpenEmail() + { + var email = ""; + var common = ConfigSystem.GetConfig(); + if (common != null) + { + email = common.contactUs; + } + + var subject = "Contact Us"; + var body = $"My UID is [ {GetUID()} ]\n"; + var url = $"mailto:{email}?subject={subject}&body={body}"; + var uri = new Uri(url); + + OpenBrowser.OpenURL(uri.AbsoluteUri); + GameHelper.ShowTips("Trying to call send mail..."); + } + + public static PaymentType GetPaymentTypeVO() + { + var isRu = GetCurrCountry().ToUpper().Equals("RU"); + var isPT = AppConst.isPt(); + var PaymentTypeModel = ConfigSystem.GetConfig(); + var voList = PaymentTypeModel.dataList; + foreach (var paymentTypeVo in voList) + { + if (isRu) + { + if (paymentTypeVo.countryKey.Contains("RU")) + { + return paymentTypeVo; + } + } + else if (isPT) + { + if (paymentTypeVo.countryKey.Contains("BR")) + { + return paymentTypeVo; + } + } + else + { + if (paymentTypeVo.countryKey.Contains("US")) + { + return paymentTypeVo; + } + } + } + + + return voList[0]; + } + + + public static int GetPaymentMulti() + { + return GetPaymentTypeVO().multi; + } + + + public static decimal GetQuizMax() + { + return 0m; + } + + public static int GetIsWacthAd() + { + return PlayerPrefs.GetInt("isWacthAd"); + } + + public static void SetIsWatchAd(int isWacthAd) + { + PlayerPrefs.SetInt("isWacthAd", isWacthAd); + } + + public static int GetReviveCount() + { + return PlayerPrefs.GetInt("reviveCount"); + } + + public static void SetReviveCount() + { + int count = PlayerPrefs.GetInt("reviveCount") + 1; + PlayerPrefs.SetInt("reviveCount", count); + } + + public static void RestartReviveCount() + { + PlayerPrefs.SetInt("reviveCount", 0); + } + + + public static float[] GetRewardValue(int type) + { + var currentRedeemLevel = 1; + + for (var i = 0; i < PreferencesMgr.Instance.MakeupTaskHistory.Count; i++) + { + var task = PreferencesMgr.Instance.MakeupTaskHistory[i]; + + if (task.status == MakeupTaskStatus.Inline) + { + currentRedeemLevel++; + } + } + + Debug.Log($"GetRewardValue=====================currentRedeemLevel {currentRedeemLevel} \n type: {type}"); + + if (currentRedeemLevel > 3) + { + currentRedeemLevel = 3; + } + + var currentIndex = GetValueIndex(currentRedeemLevel); + + if (currentIndex != -1) + { + switch (type) + { + case 0: + { + var vos = ConfigSystem.GetConfig().dataList; + SmallrewardNum rewardNumVo = vos[currentIndex]; + return GetValue(rewardNumVo, currentRedeemLevel); + } + case 1: + { + var vos = ConfigSystem.GetConfig().dataList; + LargerewardNum rewardNumVo = vos[currentIndex]; + return GetValue(rewardNumVo, currentRedeemLevel); + } + case 2: + { + var vos = ConfigSystem.GetConfig().dataList; + RewardNum rewardNumVo = vos[currentIndex]; + return GetValue(rewardNumVo, currentRedeemLevel); + } + } + } + return new float[] { 0, 0 }; + } + + private static int GetValueIndex(int index) + { + var cash = Get102(); + var vos = ConfigSystem.GetConfig().dataList; + + var currentIndex = -1; + if (cash < 0) + { + currentIndex = 0; + } + else + { + for (var i = 0; i < vos.Count; i++) + { + var rewardNumVo = vos[i]; + var cashArray = index switch + { + 1 => rewardNumVo.cash_1, + 2 => rewardNumVo.cash_2, + 3 => rewardNumVo.cash_3, + _ => default + }; + + if (i < vos.Count - 1) + { + if (cash >= (decimal)cashArray[0] && cash < (decimal)cashArray[1]) + { + currentIndex = i; + break; + } + } + else + { + if (cash >= (decimal)cashArray[0]) + { + currentIndex = i; + break; + } + } + } + } + + return currentIndex; + } + + + private static float[] GetValue(SmallrewardNum rewardNumVo, int level) + { + + float[] normalArray = null; + var videoRewardRate = 0f; + switch (level) + { + case 1: + + normalArray = rewardNumVo.nor_1; + videoRewardRate = rewardNumVo.rv_1; + + break; + case 2: + + normalArray = rewardNumVo.nor_2; + videoRewardRate = rewardNumVo.rv_2; + break; + case 3: + + normalArray = rewardNumVo.nor_3; + videoRewardRate = rewardNumVo.rv_3; + + break; + } + float normalValue = Random.Range(normalArray[0], normalArray[1]); + normalValue = (float)Math.Round(normalValue, 2); + return new float[] { normalValue, videoRewardRate }; + } + private static float[] GetValue(LargerewardNum rewardNumVo, int level) + { + + float[] normalArray = null; + var videoRewardRate = 0f; + switch (level) + { + case 1: + + normalArray = rewardNumVo.nor_1; + videoRewardRate = rewardNumVo.rv_1; + + break; + case 2: + + normalArray = rewardNumVo.nor_2; + videoRewardRate = rewardNumVo.rv_2; + break; + case 3: + + normalArray = rewardNumVo.nor_3; + videoRewardRate = rewardNumVo.rv_3; + + break; + } + float normalValue = Random.Range(normalArray[0], normalArray[1]); + normalValue = (float)Math.Round(normalValue, 2); + return new float[] { normalValue, videoRewardRate }; + } + private static float[] GetValue(RewardNum rewardNumVo, int level) + { + + float[] normalArray = null; + var videoRewardRate = 0f; + switch (level) + { + case 1: + + normalArray = rewardNumVo.nor_1; + videoRewardRate = rewardNumVo.rv_1; + + break; + case 2: + + normalArray = rewardNumVo.nor_2; + videoRewardRate = rewardNumVo.rv_2; + break; + case 3: + + normalArray = rewardNumVo.nor_3; + videoRewardRate = rewardNumVo.rv_3; + + break; + } + float normalValue = Random.Range(normalArray[0], normalArray[1]); + normalValue = (float)Math.Round(normalValue, 2); + return new float[] { normalValue, videoRewardRate }; + } + public static bool CanGuide() + { + return IsOpenGuide() && IsGiftSwitch() && !PreferencesMgr.Instance.IsGuideFinish; + } + + + public static decimal GetQuizRate() + { + return 0m; + } + + + public static decimal GetNormalRewardValue() + { + return 0m; + } + + + public static void GetRewardOnly(decimal value, RewardOrigin origin, GObject startGObject = null, + GObject endGObject = null, Action onCompleted = null, decimal rate = 1) + { + GetReward(value, origin, startGObject, endGObject, false, false, onCompleted, rate); + } + + + public static void GetReward(decimal value, RewardOrigin origin, GObject startGObject = null, + GObject endGObject = null, + bool isDialog = true, bool isNeedAd = true, + Action onCompleted = null, decimal rate = 1, decimal ctRate = 50) + { + var rewardData = new RewardData(); + var rewardSingleData = new RewardSingleData(101, value, origin) + { + multiRate = rate + }; + + + if (startGObject != null) + { + rewardSingleData.startPosition = GetUICenterPosition(startGObject); + } + + + if (endGObject != null) + { + rewardSingleData.endPosition = GetUICenterPosition(endGObject); + } + + rewardData.AddReward(rewardSingleData); + + if (isDialog) + { + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.Dialog | + RewardDisplayType.ValueChange; + + rewardData.condition = isNeedAd ? RewardCondition.AD : RewardCondition.None; + } + else + { + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + } + + + rewardData.AddCompleted(onCompleted); + rewardData.ctRate = ctRate; + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + } + + + public static decimal GetVideoRate() + { + return 0m; + } + + + public static string GetPaymentPayer() + { + return GetPaymentTypeVO().payer; + } + + + public static bool IsContinuousSignToday() + { + if (PreferencesMgr.Instance.SignState.Count == 0) + { + return false; + } + + if (PreferencesMgr.Instance.SignState.Count >= 7) + { + return true; + } + + var tmp = PreferencesMgr.Instance.SignState[PreferencesMgr.Instance.SignState.Count - 1]; + return InToday(tmp, 0, true); + } + + public static decimal GetQuizRewardValue() + { + return 0m; + } + + public static bool IsCTFunction() + { + return true; + } + + public static int GetItemNumber(ItemEnum item) + { + var index = (int)item; + var items = PreferencesMgr.Instance.Items; + if (items.TryGetValue(index, out var num)) + { + return num; + } + + return 0; + } + + public static void SetItemNumber(ItemEnum item, int value) + { + var index = (int)item; + var items = PreferencesMgr.Instance.Items; + if (items.ContainsKey(index)) + { + items[index] = value; + } + else + { + items.Add(index, value); + } + + PreferencesMgr.Instance.Items = items; + GameDispatcher.Instance.Dispatch(GameMsg.RefreshItemCount); + } + + public static void AddItemNumber(ItemEnum type, int change) + { + SetItemNumber(type, GetItemNumber(type) + change); + } + + public static bool GetPayBox1() + { + // return PlayerPrefs.GetInt("PayBox1", 0); + return PreferencesMgr.Instance.PayBox1; + } + public static bool GetPayBox2() + { + // return PlayerPrefs.GetInt("PayBox2", 0); + return PreferencesMgr.Instance.PayBox2; + } + + public static void SetPayBox1(bool value) + { + + // PlayerPrefs.SetInt("PayBox1", value); + PreferencesMgr.Instance.PayBox1 = value; + + } + public static void SetPayBox2(bool value) + { + PreferencesMgr.Instance.PayBox2 = value; + // PlayerPrefs.SetInt("PayBox2", value); + + } + + public static int GetLevel() + { + // PlayerPrefs.GetInt("Level", 1); + // return 5; //zhushi + return PreferencesMgr.Instance.GameLevel; + + } + public static void SetLevel(int level) + { + PreferencesMgr.Instance.GameLevel = level; + // PlayerPrefs.SetInt("Level", level); + } + public static int getLevelstate() + { + return PlayerPrefs.GetInt("_lvstate", 3);//4种,数字3为可以用广告和金币复活,2为只能用广告,1为只能用金币。0为不能复活 + } + + public static void setLevelstate(int state) + { + PlayerPrefs.SetInt("_lvstate", state); + } + + #region 广告次数 + + public static int GetAdWatchCount() + { + return PreferencesMgr.Instance.AdWatchCount; + } + public static int AddAdWatchCount(int value, bool updateExchangeTime = false) + { + int a = Mathf.Max(GetAdWatchCount() + value, 0); + PreferencesMgr.Instance.AdWatchCount = a; + GameDispatcher.Instance.Dispatch(GameMsg.AdWatchCountUpdated); + + if (updateExchangeTime) + { + UpdateAdRewardExchangeTime(); + } + return a; + } + public static bool CheckAdWatchCount(int target) + { + return GetAdWatchCount() >= target; + } + + public static void UpdateAdRewardExchangeTime() + { + SaveData.GetSaveobject().lastAdRewardExchangeTime = GetNowTime(); + GameDispatcher.Instance.Dispatch(GameMsg.AdRewardClaimed); + } + + public static long GetAdRewardCooldownTime() + { + return SaveData.GetSaveobject().lastAdRewardExchangeTime + GetCommonModel().exchangeCD; + } + + public static bool InAdRewardCooldown() + { + if (SaveData.GetSaveobject().lastAdRewardExchangeTime == 0) + { + return false; + } + + return GetAdRewardCooldownTime() > GetNowTime(); + } + + #endregion + + public static int GetGoldNumber() + { + // return PlayerPrefs.GetInt("_gold", 10000); + return PreferencesMgr.Instance.TotalCoins; + } + public static int AddGoldNumber(int value) + { + int a = Mathf.Max(GetGoldNumber() + value, 0); + PreferencesMgr.Instance.TotalCoins = a; + // PlayerPrefs.SetInt("_gold", a); + return a; + } + public static bool CheckGoldNumber(int target) + { + return GetGoldNumber() >= target; + } + + public static void addGameTime() + { + int a = PlayerPrefs.GetInt("_time", 0) + 1; + PlayerPrefs.SetInt("_time", a); + + } + public static int getGameTime() + { + return PlayerPrefs.GetInt("_time", 0); + } + + public static void setGameday() + { + + PlayerPrefs.SetInt("_day", DateTime.Now.Day); + + } + public static int getGameday() + { + return PlayerPrefs.GetInt("_day", 0); + } + + + public static int GetGameExp() + { + // PlayerPrefs.GetInt("_exp", 0); + return PreferencesMgr.Instance.BattleExp; + } + public static void AddGameExp(int change) + { + PreferencesMgr.Instance.BattleExp += change; + // if (PreferencesMgr.Instance.BattleExp >= _nextNeedEliminatingQuantity) + // { + // GameDispatcher.Instance.Dispatch(GameMsg.BattleLevelUp); + // GetBattleLv(); + // } + + GameDispatcher.Instance.Dispatch(GameMsg.BattleLevelUp); + // PlayerPrefs.SetInt("_exp", GetGameExp() + change); + } + public static void ResetGameExp() + { + PreferencesMgr.Instance.BattleExp = 0; + // PlayerPrefs.SetInt("_exp", 0); + } + + private static int _curBattleLv; + private static int _nextNeedEliminatingQuantity; + public static int GetBattleLv() + { + int exp = GetGameExp(); + List list = ConfigSystem.GetConfig().dataList; + for (int i = 0; i < list.Count; i++) + { + if (exp < list[i].Eliminating_quantity) + { + _curBattleLv = i; + _nextNeedEliminatingQuantity = list.Count < i + 1 ? list[i + 1].Eliminating_quantity : list[i].Eliminating_quantity; + return i; + + } + } + return list.Count; + } + + public static bool needShowLevelstate(int id = -1) + { + + var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + int lv = vo.id; + int a = PlayerPrefs.GetInt("cash_lv", 0); + if (id != -1) lv = id + 1; + if (a < lv) + { + return true; + } + + return false; + } + public static void AddMoney(int a) + { + PreferencesMgr.Instance.Currency102 += a; + + } + public static void AddMoney(float a) + { + // PreferencesMgr.Instance.Currency101 = (decimal)((float)PreferencesMgr.Instance.Currency101 + a); + PreferencesMgr.Instance.Currency102 += (decimal)a; + + } + + + + public static bool showGameUI = true; + + public static int look_interad_numbers = 0; + + public static bool is_first_login = true; + + public static void AddInterAdNumber() + { + look_interad_numbers++; + if (IsGiftSwitch() && !SaveData.GetSaveobject().is_get_removead && look_interad_numbers >= ConfigSystem.GetConfig().playtimes) + { + look_interad_numbers = 0; + + if (Random.Range(0, 100) < ConfigSystem.GetConfig().interstitialtype) + { + if (UIManager.Instance.IsExistUI(UIConst.H5UI)) + GameHelper.ShowInterstitial("interstitial_h5reward"); + else + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Open); + } + } + } + + public static Dictionary statusDic = new Dictionary(); + public static Dictionary> statusDic2 = new Dictionary>(); + + public static string trace_id; + public static void PostFunnelLogin(string str, bool payload = false) + { + Debug.Log(str); + if (statusDic.TryGetValue(str, out var status)) + { + if (status) + { + return; + } + } + + if (str == "bootstrap") + { + long timestamp = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000; + trace_id = timestamp.ToString(); + } + long user_id = 0; + if (loginModel != null && loginModel.uid != 0) user_id = loginModel.uid; + string play_object = ""; + if (str == "afRecv" || str == "loginRecv") + { + play_object = payload ? "success" : "fail"; + } + + var requestData = new + { + uid = user_id, + trace_id = trace_id, + device_id = SystemInfo.deviceUniqueIdentifier, + pack_name = NetworkManager.packName, + version = Application.version, + channel = SuperApplication.Instance.attribution, + type = str, + payload = play_object + }; + statusDic.Add(str, true); + NetworkKit.Post("event/funnelLogin", requestData, (isSuccess, data) => + { + + }); + } + + public static void SendLogToServer(string message, string stacktrace, LogType type) + { + // 如果只需要日期部分,可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化 + if (!GameHelper.GetLoginModel().debug_log) return; + System.DateTime currentDate = System.DateTime.Now; + var formattedDate = currentDate.ToString("yyyy_MM_dd_HH_mm"); + var md5Str = MD5Kit.GetStringMD5(message + stacktrace); + if (!statusDic2.ContainsKey(formattedDate)) + { + statusDic2.Add(formattedDate, new Dictionary()); + } + if (!statusDic2[formattedDate].ContainsKey(md5Str)) + { + statusDic2[formattedDate].Add(md5Str, false); + } + //Debug.Log($"SendLogToServer requestData========={formattedDate} \nmd5Str=== {md5Str}"); + if (statusDic2[formattedDate][md5Str]) + { + return; + } + long user_id = 0; + if (loginModel != null && loginModel.uid != 0) user_id = loginModel.uid; + var requestData = new + { + uid = user_id, + device = SystemInfo.deviceModel, + os_ver = SystemInfo.operatingSystem, + network = GetNetworkType(), + device_id = SystemInfo.deviceUniqueIdentifier, + pack_name = NetworkManager.packName, + version = Application.version, + channel = SuperApplication.Instance.attribution, + level = type == 0 ? "error" : "warn", + message = message, + stacktrace = stacktrace + }; + statusDic2[formattedDate][md5Str] = true; + // Debug.Log($"SendLogToServer requestData1========={JsonConvert.SerializeObject(requestData)}"); + // NetworkKit.Post("event/cliDebugLog", requestData, (isSuccess, data) => + // { + + // }); + } + private static string GetNetworkType() + { + string types = "Not Connected"; + switch (Application.internetReachability) + { + case NetworkReachability.ReachableViaCarrierDataNetwork: + types = "Mobile Data"; + break; + case NetworkReachability.ReachableViaLocalAreaNetwork: + types = "Wi-Fi"; + break; + } + return types; + } + + + private static GameObject SheepPlayUI; + + public static void ShowSheepPlayUI(bool isShow) + { + if (SheepPlayUI == null) + { + SheepPlayUI = GameObject.Find("(SheepPlayUI)sheep_play"); + } + if (SheepPlayUI != null) + { + + SheepPlayUI.transform.localPosition = isShow ? new Vector3(0, 0, 0) : new Vector3(-2000, 0, 0); + } + } + + //获取当前时间戳,精确到秒的时间戳 + public static long GetCurrentTimestamp() + { + // 获取当前UTC时间 + DateTime now = DateTime.UtcNow; + // 计算从1970年1月1日00:00:00到现在的总秒数 + long timestamp = (long)(now - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; + return timestamp; + } + + public static bool IsTemporaryEnd; + + public static void SendErrorToServer(string error, string stackTrace) + { + var reqData = new RespDebugData + { + level = "error", + message = error, + stacktrace = stackTrace + }; + NetworkKit.SendLogToServer(reqData); + } + + public static Dictionary adCallbackInfo = new Dictionary(); + public static void sendHighRevenueToAF() + { + float purch_number = GameHelper.GetCommonModel().afSendNum; + string countryCode = "USD"; + adCallbackInfo.Clear(); + adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId()); + adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().uid.ToString()); + adCallbackInfo.Add("af_currency", countryCode); + adCallbackInfo.Add("af_revenue", purch_number.ToString()); + + AppsFlyer.sendEvent("af_new_purchase", adCallbackInfo); + + Debug.Log($"AppsFlyer sendEvent af_new_purchase {purch_number}"); + } + public static List makeupLevels = new(); + public static void SetLevelsList() + { + + List makeup_list = ConfigSystem.GetConfig().dataList; + for (int i = 0; i < makeup_list.Count; i++) + { + makeupLevels.Add(makeup_list[i].levels_need); + } + // Debug.Log($"barry makeupLevels-======== {SerializeUtil.ToJson(makeupLevels)}"); + } + + public static bool IsShowLevelTips() + { + GameHelper.SetLevelsList(); + bool isShow = false; + for (int i = 0; i < makeupLevels.Count; i++) + { + if (IsGiftSwitch() && GetLevel() == makeupLevels[i]) + { + isShow = true; + break; + } + + } + + return isShow; + } + public static long getNowTimeByMillisecond() + { +#if !JarvisRelease + return DateTimeManager.Instance.GetCurrTimesTampByMillisecond(); + // return DateTimeManager.Instance.GetServerCurrTimestamp(); +#else + return DateTimeManager.Instance.GetServerCurrTimestampByMillisecond(); +#endif + } + public static void sendRevenueToServer(string eventname, string eventproperty, int integer) + { + NetworkKit.BuriedPoint(eventname, eventproperty, integer); + } + public static bool IsAdModelOfPay() + { + bool isAd = true; + + if (GetLoginModel().enwp == 1) + { + isAd = false; + } + // return true;//zhushi + // return false;//zhushi + return isAd; + } + + private static int m_gameTimes = 0; + public static void PlayGameTimeEvent(int gameType, Action action = null) + { + m_gameTimes = GetPlayGameTimes(); + + if (m_gameTimes == 0) + { + action?.Invoke(); + return; + } + ; + RespGameTimeEventData respData = new RespGameTimeEventData() + { + type = gameType, + second = m_gameTimes + }; + + m_gameTimes = 0; + + PlayerPrefs.SetInt("game_times", m_gameTimes); +Debug.Log("fasongshichang"); + NetworkKit.PostWithHeader("event/gameTime", respData, (isSuccess, obj) => + { + Debug.Log($"PlayGameTimeEvent==== {m_gameTimes}"); + action?.Invoke(); + }); + } + public static int GetPlayGameTimes() + { + return PlayerPrefs.GetInt("game_times", 0); + } + public static void SetGameTimes() + { + m_gameTimes++; + PlayerPrefs.SetInt("game_times", m_gameTimes); + } + public static int conf_num = 1; + /// + /// 玩法调控,请求配置 + /// + public static void RequestGameConfig() + { + NetworkKit.PostWithHeader("game/regulate", null, (isSuccess, obj) => + { + if (isSuccess) + { + Debug.Log($"RequestGameConfig==== {obj.conf_num}"); + PlayerPrefs.SetInt("game_conf_num", obj.conf_num); + ShowScrews.Instance.InitAllLeveData(); + conf_num = obj.conf_num; + } + + isCanCloseResultView = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close); + }); + } + private static bool isCanCloseResultView = false; + + public static bool GetCloseResult() + { + return isCanCloseResultView; + } + public static void SetCloseResult(bool isCan) + { + isCanCloseResultView = isCan; + } + public static void AdOverEvent(int type) + { + + RespAdEventData respData = new RespAdEventData() + { + type = type + }; + + NetworkKit.PostWithHeader("event/adWatchOver", respData, (isSuccess, obj) => + { + + }); + } + } +} +public class ResGameConfigData +{ + public int conf_num; +} +public class RespGameTimeEventData +{ + public int type; + public int second; +} +public class RespAdEventData +{ + public int type; +} diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs.meta new file mode 100644 index 0000000..2146074 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/GameHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fd79a9adb913488d9704813bd7ebac98 +timeCreated: 1681804422 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs new file mode 100644 index 0000000..0e62348 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs @@ -0,0 +1,16 @@ +using UnityEngine.Events; +using Object = UnityEngine.Object; + +namespace ScrewsMaster +{ + public interface ILoadAsset + { + T GetAsset(string dfsad, string sa) where T : Object; + + + void GetAsset(string dfsad, string sa, UnityAction onCompleted) where T : Object; + + + void RecycleAsset(string assetUrl, UnityAction onCompleted); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs.meta new file mode 100644 index 0000000..29d3d9d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/ILoadAsset.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4f5f73f6c2c342f9a9ee2cae54688486 +timeCreated: 1682576608 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs new file mode 100644 index 0000000..313d9a2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs @@ -0,0 +1,289 @@ +// #if UNITY_EDITOR + +using ScrewsMaster.Editor; +// #endif +using UnityEngine.Events; + +namespace ScrewsMaster +{ + using System; + using System.Linq; + using UnityEngine; + using System.Collections.Generic; + using Object = UnityEngine.Object; + + + public class LoadKit : Singleton + { + private readonly Dictionary> mGameObject2AbMap = new(); + + private readonly Dictionary> mSprite2AbMap = new(); + + private readonly Dictionary> mAudio2AbMap = new(); + + private ILoadAsset LoadAssetType { get; set; } + + public void Init(ILoadAsset loadAssetType = null) + { + // #if UNITY_EDITOR + LoadAssetType = loadAssetType ?? new AssetDataBaseKit(); + // #else + // LoadAssetType = loadAssetType ?? new CrazyZooKit(); + // #endif + } + + public void LoadAsset(string assetUrl, string assetName, UnityAction onCompleted, bool isRecord = true) + where T : Object + { + if (string.IsNullOrEmpty(assetUrl) || string.IsNullOrEmpty(assetName)) + { + Debug.LogError("AssetUrl or AssetName is Empty."); + onCompleted?.Invoke(default); + return; + } + + Init(); + + if (LoadAssetType == null) + { + Debug.LogError("Please Call LoadBox.Instance.Init() first."); + onCompleted?.Invoke(default); + return; + } + + LoadAssetType.GetAsset(assetUrl, assetName, (obj) => + { + if (obj != null && isRecord) + { + RecordGameObject(assetUrl, obj); + } + + onCompleted?.Invoke(obj); + }); + } + + public T LoadAsset(string assetUrl, string assetName, bool isRecord = true) where T : Object + { + if (string.IsNullOrEmpty(assetUrl) || string.IsNullOrEmpty(assetName)) + { + Debug.LogError("AssetUrl or AssetName is Empty."); + return default; + } + + Init(); + + if (LoadAssetType == null) + { + Debug.LogError("Please Call LoadBox.Instance.Init() first."); + return default; + } + + var obj = LoadAssetType.GetAsset(assetUrl, assetName); + if (obj != null && isRecord) + { + RecordGameObject(assetUrl, obj); + } + + return obj; + } + + #region 加载Sprite相关 + + public void LoadSprite(string assetUrl, string assetName, UnityAction onCompleted, bool isRecord = true) + { + LoadAsset(assetUrl, assetName, onCompleted, isRecord); + } + + public Sprite LoadSprite(string assetUrl, string assetName, bool isRecord = true) + { + return LoadAsset(assetUrl, assetName, isRecord); + } + + public void LoadSprite(string assetUrl, Action onCompleted) + { + if (string.IsNullOrEmpty(assetUrl)) + { + Debug.LogError("AssetUrl is Empty."); + onCompleted?.Invoke(null); + return; + } + + Init(); + + if (LoadAssetType == null) + { + Debug.LogError("Please Call LoadKit.Instance.Init() first."); + onCompleted?.Invoke(null); + return; + } + + string assetName; + if (assetUrl.Contains("/")) + { + assetName = assetUrl.Split('/').Last(); + assetUrl = assetUrl.Replace($"/{assetName}", string.Empty); + } + else + { + assetName = assetUrl.Split('.').Last(); + assetUrl = assetUrl.Replace($".{assetName}", string.Empty); + } + + LoadAssetType.GetAsset(assetUrl, assetName, delegate (Sprite sprite) + { + if (sprite != null) + { + RecordSprite(assetUrl, sprite); + } + + onCompleted?.Invoke(sprite); + }); + } + + + + + public void RecordSprite(string assetName, Sprite sprite) + { + if (sprite == null || string.IsNullOrEmpty(assetName)) + { + Debug.LogError("ABName is Null or Sprite is Null"); + return; + } + + var instanceId = sprite.GetInstanceID(); + if (mSprite2AbMap.Keys.Contains(assetName)) + { + if (!mSprite2AbMap[assetName].Keys.Contains(instanceId)) + { + mSprite2AbMap[assetName].Add(instanceId, sprite.name); + } + } + else + { + var spriteNameIns = new Dictionary { { instanceId, sprite.name } }; + mSprite2AbMap.Add(assetName, spriteNameIns); + } + } + + + + #endregion + + #region 加载GameObject相关 + + public GameObject LoadGameObject(string assetUrl, string assetName, bool isRecord = true) + { + return LoadAsset(assetUrl, assetName, isRecord); + } + + + public void LoadGameObjectAndClone(string assetUrl, string assetName, + UnityAction onCompleted = null, + Transform parent = null, bool worldPositionStays = false) + { + LoadAsset(assetUrl, assetName, + gameObject => { InstantiateAndRecord(gameObject, parent, worldPositionStays, onCompleted); }, false); + } + + + public GameObject LoadGameObjectAndCloneSync(string assetUrl, string assetName, Transform parent = null, + bool worldPositionStays = false) + { + var gameObject = LoadGameObject(assetUrl, assetName, false); + return InstantiateAndRecord(gameObject, parent, worldPositionStays); + } + + + public void RecordGameObject(string assetName, Object gameObject) + { + if (gameObject == null || string.IsNullOrEmpty(assetName)) + { + Debug.LogError("ABName is Null or Sprite is Null"); + return; + } + + var instanceId = gameObject.GetInstanceID(); + if (mGameObject2AbMap.Keys.Contains(assetName)) + { + if (!mGameObject2AbMap[assetName].Keys.Contains(instanceId)) + { + mGameObject2AbMap[assetName].Add(instanceId, gameObject.name); + } + } + else + { + var gameNameIns = new Dictionary { { instanceId, gameObject.name } }; + mGameObject2AbMap.Add(assetName, gameNameIns); + } + } + + + public GameObject InstantiateAndRecord(GameObject gameObject, Transform parent = null, + bool worldPositionStays = false, UnityAction onCompleted = null) + { + if (gameObject == null) + { + Debug.LogError("GameObject is Null"); + return null; + } + + var newGameObject = parent + ? Object.Instantiate(gameObject, parent, worldPositionStays) + : Object.Instantiate(gameObject); + + if (newGameObject != null) + { + RecordCloneGameObject(gameObject, newGameObject); + } + + onCompleted?.Invoke(newGameObject); + return newGameObject; + } + + + private void RecordCloneGameObject(GameObject gameObject, GameObject newGameObject) + { + if (gameObject == null || newGameObject == null) + { + return; + } + + var oldInstanceId = gameObject.GetInstanceID(); + var instanceId = newGameObject.GetInstanceID(); + foreach (var keyValuePair in mGameObject2AbMap) + { + if (!keyValuePair.Value.Keys.Contains(oldInstanceId) || + keyValuePair.Value.Keys.Contains(instanceId)) continue; + keyValuePair.Value.Add(instanceId, newGameObject.name); + break; + } + } + + #endregion + + #region 加载声音相关 + + public void LoadAudio(string assetUrl, string assetName, UnityAction onCompleted) + { + LoadAsset(assetUrl, assetName, onCompleted); + } + + + #endregion + + + public void RecycleAsset(string assetUrl, UnityAction onCompleted = null) + { + Init(); + if (LoadAssetType != null) + { + LoadAssetType.RecycleAsset(assetUrl, onCompleted); + } + else + { + Debug.LogError("Please Call LoadBox.Instance.Init() first."); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs.meta new file mode 100644 index 0000000..41130c2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/LoadKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 283019491b0d411db1c4a6967309149e +timeCreated: 1682578772 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs b/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs new file mode 100644 index 0000000..4322a8e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs @@ -0,0 +1,347 @@ +using FairyGUI; +using UnityEngine; +using System.Collections.Generic; +using System; +using System.IO; + +using UnityEngine.Events; +using System.Collections; +using UnityEngine.Networking; +using ScrewsMaster; +public class TextureHelper +{ + private static Dictionary nTexturesDic = new(); + private static Dictionary avatarNTexturesDic = new(); + private static Dictionary galleryNTexturesDic = new Dictionary(); + + public static void GetNTexture(string path, string name, UnityAction action) + { + if (!nTexturesDic.TryGetValue(path + name, out NTexture spr)) + { + try + { + LoadKit.Instance.LoadSprite(path, name, sprite => + { + if (sprite != null) + { + spr = new NTexture(sprite); + action?.Invoke(spr); + nTexturesDic.TryAdd(path + name, spr); + } + }); + } + catch (Exception e) + { + Debug.LogError(e); + } + } + else + { + action?.Invoke(spr); + } + } + + #region 加载Texture + + private static IEnumerator GetLocalTexture(string imagePath, Action action) + { + var file = $"{CommonHelper.GetAppSavePath()}/{imagePath}"; + var fileInfo = new FileInfo(file); + if (!fileInfo.Exists) + { + action?.Invoke(null); + yield break; + } + + var avatarPath = $"file://{file}"; + var uwr = UnityWebRequestTexture.GetTexture(avatarPath); + yield return uwr.SendWebRequest(); + if (uwr.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError) + { + action?.Invoke(null); + yield break; + } + + var texture2D = DownloadHandlerTexture.GetContent(uwr); + + action?.Invoke(texture2D); + } + + public static void GetCardIcon(bool isLogo = false, UnityAction action = null) + { + var cardIconPath = ""; + var paymentTypeVo = GameHelper.GetPaymentTypeVO(); + if (isLogo) + { + cardIconPath = paymentTypeVo.logo_id; + } + else + { + cardIconPath = paymentTypeVo.card_name; + } + + + GetNTexture("Atlas.Pay", cardIconPath, action); + } + + private static IEnumerator GetTextureFromNet(string type, int imgId, string imgUrl, Action action = null) + { + string imagePath = $"{CommonHelper.GetAppSavePath()}/{type}/{imgId}.jpg"; + FileInfo fileInfo = new FileInfo(imagePath); + if (fileInfo.Exists) + { + action?.Invoke(true); + yield break; + } + + var avatarRequest = UnityWebRequest.Get(imgUrl); + yield return avatarRequest.SendWebRequest(); + if (avatarRequest.result == UnityWebRequest.Result.ConnectionError || + avatarRequest.result == UnityWebRequest.Result.ProtocolError) + { + action?.Invoke(false); + } + else + { + var avatarData = avatarRequest.downloadHandler.data; + var dirPath = Path.GetDirectoryName(imagePath); + if (!Directory.Exists(dirPath)) + { + Directory.CreateDirectory(dirPath); + } + + if (fileInfo.Exists) yield break; + Stream stream = fileInfo.Create(); + stream.Write(avatarData, 0, avatarData.Length); + stream.Close(); + stream.Dispose(); + action?.Invoke(true); + } + } + + #endregion + + + public static void GetItemIcon(int itemId, UnityAction action = null) + { + var itemIconPath = "Atlas.Item"; + string name = itemId.ToString(); + if (!GameHelper.IsGiftSwitch()) + { + // if (itemId is 101 or 111) + // { + // name = "102"; + // } + } + else + { + if (itemId is 102 or 106) + { + name += "_normal"; + } + } + + GetNTexture(itemIconPath, name, action); + } + + #region 头像相关 + + public static void SetAvatarToLoader(int avatarId, GLoader _GLoader, bool IsNeedDefAvatar = true) + { + if (!avatarNTexturesDic.TryGetValue(avatarId, out NTexture spr)) + { + try + { + Sprite sprite = null; + if (avatarId == 0) + { + if (!PlayerPrefsKit.ReadBool("IsLogin")) + { + avatarId = 1; + SetAvatarToLoader(avatarId, _GLoader); + return; + } + else + { + if (PlayerPrefsKit.ReadString("AvatarUrl").IsNullOrWhiteSpace()) + { + _GLoader.url = "ui://pmf3wbjicxrg4"; + return; + } + else + { + GetSelfFaceBookAvatar(texture => + { + if (_GLoader != null) + { + if (texture != null) + { + _GLoader.texture = texture; + } + else + { + _GLoader.url = "ui://pmf3wbjicxrg4"; + } + } + }); + return; + } + } + } + else if (avatarId > 100) + { + if (IsNeedDefAvatar) + { + _GLoader.url = "ui://pmf3wbjicxrg4"; + } + + GetFaceBookAvatar(avatarId, (e) => + { + if (_GLoader != null) + { + if (e == null) + { + _GLoader.url = "ui://pmf3wbjicxrg4"; + } + else + { + _GLoader.texture = e; + } + } + }); + return; + } + else + { + LoadKit.Instance.LoadSprite("Atlas.Avatar", avatarId.ToString(), (spr) => + { + sprite = spr; + var spr1 = new NTexture(sprite); + _GLoader.texture = spr1; + avatarNTexturesDic.Add(avatarId, spr1); + }); + } + } + catch (System.Exception e) + { + UnityEngine.Debug.LogError(e); + } + } + else + { + _GLoader.texture = spr; + } + } + + + private static IEnumerator GetAvatarLocal(int avatarId, Action action) + { + yield return GetLocalTexture($"Avatar/{avatarId}.jpg", action); + } + + #endregion + + #region FaceBook头像相关 + + public static void GetFaceBookAvatar(int avatarId, Action action) + { + if (!avatarNTexturesDic.TryGetValue(avatarId, out NTexture spr)) + { + HallManager.Instance.StartCoroutine(GetAvatarLocal(avatarId, texture => + { + if (texture == null) + { + action?.Invoke(null); + return; + } + + spr = new NTexture(texture); + if (avatarNTexturesDic.ContainsKey(avatarId)) + { + avatarNTexturesDic.Add(avatarId, spr); + } + + action?.Invoke(spr); + })); + } + else + { + action?.Invoke(spr); + } + } + + + public static void GetSelfFaceBookAvatar(Action action) + { + if (!avatarNTexturesDic.TryGetValue(0, out NTexture spr)) + { + } + else + { + action?.Invoke(spr); + } + } + + #endregion + + + public static IEnumerator GetGalleryFromNet(int imageID, Action action = null) + { + if (imageID == 0) + { + action?.Invoke(true); + } + else + { + string picInfoUrl = $"{NetworkKit.CDNUrl}gallery/{imageID}.jpg"; + yield return GetTextureFromNet("Gallery", imageID, picInfoUrl, action); + } + } + + public static string GetBankIconUrl(string icon_name) + { + return string.Format("ui://G002_main/{0}", icon_name); + } + + public static void GetGalleryLocal(int imageID, Action action) + { + if (!galleryNTexturesDic.TryGetValue(imageID, out NTexture spr)) + { + var path = $"Gallery/{imageID}"; + var asset = Resources.Load($"Atlas/{path}"); + if (asset) + { + } + else + { + CrazyAsyKit.StartCoroutine(GetGalleryFromNet(imageID, (bool isSuccess) => + { + if (isSuccess) + { + CrazyAsyKit.StartCoroutine(GetLocalTexture($"{path}.jpg", texture => + { + if (texture == null) + { + action?.Invoke(null); + + return; + } + + var spr1 = new NTexture(texture); + galleryNTexturesDic.TryAdd(imageID, spr1); + action?.Invoke(spr1); + })); + } + else + { + action?.Invoke(null); + } + })); + } + } + else + { + action?.Invoke(spr); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs.meta new file mode 100644 index 0000000..f6c13f1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Helper/TextureHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9fd5ef95c27f44cc8b171cbc1bfc7f7f +timeCreated: 1681806348 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/MainScene.cs b/Assets/CrazyZoo/Runtime/Logic/MainScene.cs new file mode 100644 index 0000000..22d8f0f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/MainScene.cs @@ -0,0 +1,109 @@ +// #if UNITY_EDITOR +// #endif + +using FairyGUI; +using SGame; +using UnityEngine; + +namespace ScrewsMaster +{ + public class MainScene : BaseScene + { + public override int SceneIdx => 0; + + + protected override void OnEnter() + { + } + + protected override void OnLeave() + { + } + + protected override void OnSwitchSceneComplete(object param = null) + { + StartUpAppProcess(); + } + + private void StartUpAppProcess() + { + OnPermanentAssetsInitComplete(); + } + + private void OnPermanentAssetsInitComplete(object param = null) + { + CtrlDispatcher.Instance.AddListener(CtrlMsg.Login_Succeed, OnLoginSucceed); + var isAssetBundleLoad = false; +#if !UNITY_EDITOR && UNITY_ANDROID + // MaxADKit.Init(); +#endif + +#if UNITY_EDITOR + isAssetBundleLoad = false; +#else + isAssetBundleLoad = false; +#endif + if (isAssetBundleLoad) + { + int value = 0; + CrazyZooFileKit.GetLocalAssetBundle( + max => { GameDispatcher.Instance.Dispatch(GameMsg.UpdateHotFixMax, max + 1); }, () => + { + value++; + // GameDispatcher.Instance.Dispatch(GameMsg.UpdateHotFixProgress, value); + }); + } + else + { + OnInitAsset(); + } + + AppDispatcher.Instance.AddListener(AppMsg.UI_LoadingInitAsset, OnInitAsset); + } + + private void OnLoginSucceed(object param = null) + { + CtrlDispatcher.Instance.RemoveListener(CtrlMsg.Login_Succeed, OnLoginSucceed); + } + + private void OnInitAsset(object param = null) + { + AppDispatcher.Instance.Dispatch(AppMsg.AppManagerRegister); + AppDispatcher.Instance.Dispatch(AppMsg.InitUIMgr); + // NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login); + AppDispatcher.Instance.AddListener(AppMsg.LoginInit, OnLoadingComplete); + + // NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetConfig); + // PreferencesMgr.Instance.InitPreferences(); + } + + private void OnLoadingComplete(object param = null) + { + CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartReady); + + TimerHelper.mEasy.AddTimer(3.0f, () => + { + AudioManager.Instance.InitDefaultButtonClickSound(AudioConst.UIButtonDefault); + ModuleManager.Instance.AllModuleGameStart(); + ShowScene(); + + SaveingPotHelper.CheckSaveingPot(); + SaveingPotHelper.TestingClearTime(); + if (GameHelper.IsGiftSwitch()) + { + WebviewManager.Instance.openWebview(); + } + }); + + } + + private void ShowScene() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameLoginUI_Open); + } + + public override void Dispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/MainScene.cs.meta b/Assets/CrazyZoo/Runtime/Logic/MainScene.cs.meta new file mode 100644 index 0000000..47f0feb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/MainScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80af4c667a8a8c149b694c748e4ccbce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager.meta b/Assets/CrazyZoo/Runtime/Logic/Manager.meta new file mode 100644 index 0000000..a80b808 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9413cdb615b453c4d9e5ed72908bc884 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs b/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs new file mode 100644 index 0000000..7263dc4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs @@ -0,0 +1,193 @@ +namespace ScrewsMaster +{ + using System; + using FairyGUI; + using Spine.Unity; + using UnityEngine; + using System.Collections.Generic; + using Object = UnityEngine.Object; + + public class FXManager : BaseUnityManager + { + private string fxPath = "Effect/sys/"; + + FXPool fx_ObjMonoObjPool; + + private Transform goWrapperPar; + + public override void Init() + { + base.Init(); + GameObject obj = new GameObject("FX_Pool"); + obj.transform.parent = transform; + obj.transform.localPosition = Vector3.zero; + obj.transform.localEulerAngles = Vector3.zero; + fx_ObjMonoObjPool = new FXPool(obj.transform); + fx_ObjMonoObjPool.NewObjFunc = NewObjFunc; + fx_ObjMonoObjPool.GetObjFunc = GetObjFunc; + fx_ObjMonoObjPool.RecObjFunc = RecObjFunc; + } + + private void RecObjFunc(Fx_Type arg1, Object arg2) + { + var componet = arg2 as Component; + if (componet) + componet.gameObject.SetActive(false); + else + { + (arg2 as GameObject).SetActive(false); + } + } + + private void GetObjFunc(Fx_Type arg1, Object arg2) + { + var componet = arg2 as Component; + if (componet) + componet.gameObject.SetActive(true); + else + { + (arg2 as GameObject).SetActive(true); + } + } + + + private Object NewObjFunc(Fx_Type arg) + { + if ((int)arg < 100) + { + var go = LoadKit.Instance.LoadGameObjectAndCloneSync("Effect.spine." + arg, arg.ToString()); + SkeletonAnimation sk = go.GetComponent(); + + return sk; + } + else + { + fxPath = "Effect.sys." + arg; + var go = LoadKit.Instance.LoadGameObjectAndCloneSync(fxPath, arg.ToString()); + + + ParticleSystem particleSystem = go.GetComponent(); + if (particleSystem == null) + { + particleSystem = go.GetComponentInChildren(); + } + + if (particleSystem != null) + { + foreach (var item in particleSystem.GetComponentsInChildren()) + { + var main = item.main; + main.scalingMode = ParticleSystemScalingMode.Hierarchy; + } + + particleSystem.transform.localScale = Vector3.one * 100; + return particleSystem; + } + + return go; + } + } + + public T GetFx(Fx_Type fx_Type) where T : Object + { + T obj = fx_ObjMonoObjPool.GetObject(fx_Type); + SkeletonAnimation ani = obj as SkeletonAnimation; + if (ani != null) + { + ani.gameObject.layer = 0; + ani.ClearState(); + ani.transform.localPosition = Vector3.zero; + ani.transform.localEulerAngles = Vector3.zero; + } + + return obj; + } + + public void RecFx(Fx_Type fx_Type, T obj) where T : Object + { + fx_ObjMonoObjPool.RecObject(fx_Type, obj); + } + + public List gameObjects = new List(); + + + public override void Dispose() + { + base.Dispose(); + fx_ObjMonoObjPool.Dispose(); + } + + private Queue goWrapperQueue = new Queue(); + + public T SetFx(GGraph gp, Fx_Type fx_Type, ref Action Rec) where T : Component + { + var fx = GetFx(fx_Type); + if (fx != null) + { + var goWrapper = new GoWrapper(fx.gameObject); + gp.SetNativeObject(goWrapper); + fx.transform.localPosition = Vector3.zero; + fx.transform.localScale = Vector3.one * 100; + fx.transform.localEulerAngles = Vector3.zero; + Rec += () => + { + goWrapper.wrapTarget = null; + gp.SetNativeObject(null); + RecFx(fx_Type, fx); + }; + } + + return fx; + } + + public GameObject SetFx(GGraph gp, Fx_Type fx_Type, ref Action Rec, bool supportStencil = false) + { + GameObject fx = GetFx(fx_Type); + if (fx != null) + { + var goWrapper = new GoWrapper(fx.gameObject); + gp.SetNativeObject(goWrapper); + fx.transform.localPosition = Vector3.zero; + fx.transform.localScale = Vector3.one * 100; + fx.transform.localEulerAngles = Vector3.zero; + Rec += () => + { + goWrapper.wrapTarget = null; + gp.SetNativeObject(null); + RecFx(fx_Type, fx); + }; + } + + return fx; + } + } + + public enum Fx_Type + { + None = -1, + gamwin, + fx_login, + fx_signin,//2024年9月12日添加 + fx_title, + fx_title_light, + fx_prize_wheel, + fx_rabbit, + fx_savepot_icon, + fx_broad, + fx_tips, + fx_savepot, + fx_hand_pre, + fx_main_ad, + fx_disaappear_1, + fx_disaappear_2, + fx_first_reward, + fx_lose, + fx_win, + fx_win_light, + fx_three_gift, + fx_title_effect, + fx_free_idle = 104, + fx_ui_jinbi_click = 107, + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs.meta new file mode 100644 index 0000000..aa93f1e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/FXManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9cde96b619c044d99e1f59d178df68cd +timeCreated: 1681806251 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs b/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs new file mode 100644 index 0000000..eb8b4b4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs @@ -0,0 +1,228 @@ +namespace ScrewsMaster +{ + using System; + using UnityEngine; + using System.Collections; + using System.Collections.Generic; + + public class HallManager : BaseUnityManager + { + public event Action UpdateSecondEvent; + public event Action UpdateFiveSecondEvent; + + private float _secondTime; + private float _secondTime1; + private LoginModel loginModel; + private bool isGameStart; + private GameDataSystem gameDataSys; + private WindowSystem windowSys; + private RewardSystem rewardSys; + private ConsumeSystem consumeSys; + public QuestionBank selectedQuestionbankVo; + public event Action UpdateEvent; + + public override void Init() + { + CtrlDispatcher.Instance.AddListener(CtrlMsg.Game_Start, OnGameStart); + GameDispatcher.Instance.AddListener(GameMsg.OpenGame, EnterGame); + GameDispatcher.Instance.AddListener(GameMsg.BackMainScene, EnterHall); + AppDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, BackToGame); + InitSystem(); + } + + private void InitSystem() + { + gameDataSys = new GameDataSystem(); + windowSys = new WindowSystem(); + rewardSys = new RewardSystem(); + consumeSys = new ConsumeSystem(); + } + + private void OnGameStart(object obj) + { + var lang = PlayerPrefsKit.ReadString("LangIdKey"); + if (lang.IsNullOrWhiteSpace()) + { + lang = "en"; + } + PurchasingManager.Instance.InitProduct(); + AudioManager.Instance.PlayBGM("game_bgm"); + UIManager.Instance.SetSwitchLanguage(lang); + EnterHall(); + + isGameStart = true; + } + + private void EnterHall(object obj = null) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardAniUI_Close); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SheepPlayUI_Open); + // Debug.Log("dakaiyouxijiemian"); + // AudioManager.Instance.PlayBGM(AudioConst.MainBg); + + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainTabUI_Open); + + + if (GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BroadcastUI_Open); + GameHelper.PlayGameTimeEvent(3); + } + + void BackToGame(object obj = null) + { + Debug.Log("BackToGame----"); + if (MaxPayManager.isPay) + { + MaxPayManager.isPay = false; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close); + MaxPayManager.Instance.PaySuccess(); + } + + // DateTime newDate = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); + // newDate = newDate.AddSeconds(GameHelper.GetNowTime()); + // var newDays = newDate.Day; + // var last_time = PlayerPrefs.GetInt("Dayreftimes", 0); + // if (last_time != newDays) + // { + // var config = ConfigSystem.GetConfig(); + // if (config == null) + // { + // return; + // } + // SaveData.GetSaveobject().onlineRewardsTimes = 0; + // } + } + private void EnterGame(object obj) + { + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainTabUI_Close); + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MainUI_Close); + var questionDatas = obj as List; + } + + #region 缓存资源 + + public void GetGalleryNet(int imageID, Action action = null) + { + StartCoroutine(TextureHelper.GetGalleryFromNet(imageID, action)); + } + + #endregion + + public void Update() + { + if (!isGameStart) return; + UpdateEvent?.Invoke(); + _secondTime += Time.deltaTime; + _secondTime1 += Time.deltaTime; + if (_secondTime >= 1) + { + _secondTime = 0; + UpdateSecondEvent?.Invoke(); + } + + if (_secondTime1 >= 5) + { + _secondTime1 = 0; + UpdateFiveSecondEvent?.Invoke(); + } + } + + public List RandomSelectQuestions(QuestionBank vo, bool isGuide = false) + { + var questionDatas = new List(); + int needGenerate = CommonHelper.RandomRange(ConfigSystem.GetConfig().quiznum); + + int temp = needGenerate; + while (temp > 0) + { + var questionModel = QuestionBankKit.GetQuestionTable(vo, isGuide); + bool isAdd = true; + foreach (var gameQuestionData in questionDatas) + { + if (gameQuestionData.questionType.Equals(questionModel.questionType) + && gameQuestionData.questionTableID.Equals(questionModel.questionTableID)) + { + isAdd = false; + } + } + + if (isAdd) + { + temp--; + questionDatas.Add(questionModel); + } + } + + foreach (var questionData in questionDatas) + { + GetGalleryNet(questionData.logoId); + } + + return questionDatas; + } + + public void GetQuestionData(List questionDatas, Action totalDownloadAction, + Action preAction = null, + Action action = null) + { + StartCoroutine(GetQuestionData1(questionDatas, totalDownloadAction, preAction, action)); + } + + + private IEnumerator GetQuestionData1(List questionDatas, Action totalDownloadAction, + Action preAction = null, + Action action = null) + { + int logoCount = 0; + + int completedIndex = 0; + int cacheCompletedIndex = 0; + + foreach (var questionData in questionDatas) + { + if (questionData.logoId != 0) + { + logoCount++; + } + } + + totalDownloadAction?.Invoke(logoCount); + + for (var i = 0; i < questionDatas.Count; i++) + { + var questionData = questionDatas[i]; + GetGalleryNet(questionData.logoId, (bool isSuccess) => + { + completedIndex++; + if (isSuccess) + { + cacheCompletedIndex++; + } + + preAction?.Invoke(); + if (completedIndex == questionDatas.Count) + { + CommonHelper.RandomSortList(questionDatas); + action?.Invoke(cacheCompletedIndex == questionDatas.Count); + } + }); + } + + yield return null; + } + + public void AddChangeGiftSwitch(Action action) + { + } + + public void RemoveChangeGiftSwitch(Action action) + { + } + + void OnApplicationQuit() + { + PreferencesMgr.Instance.ImmediateSendSave(); + } + + private bool isInH5; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs.meta new file mode 100644 index 0000000..59fd786 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/HallManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7b0f6f2d2a8a4351902376d77d27b4e8 +timeCreated: 1681804729 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs b/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs new file mode 100644 index 0000000..ee856a4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs @@ -0,0 +1,35 @@ +namespace ScrewsMaster +{ + public class NetworkManager : BaseUnityManager + { +#if JarvisRelease + public static string CrazyUrl = DomainReleaseUrl; +#else + public static string CrazyUrl = DomainDebugUrl; +#endif + + public const string DomainDebugUrl = @"https://api.jsoncompare.online/"; + + public static readonly string DomainReleaseUrl = $"https://{DomainRelease}/api/"; + public const string DomainRelease = "bingotornado.top"; + public static bool haveSimCard = false; + private LoginSystem loginSystem; + private ConfigSystem configSystem; + private PlayDataSystem playDataSystem; + + // public const string packName = "com.stronggame.nutboltparty"; + public const string packName = "com.zoo.ZooMatchSolo"; + + public override void Init() + { + InitSystem(); + } + + private void InitSystem() + { + loginSystem = new LoginSystem(); + configSystem = new ConfigSystem(); + playDataSystem = new PlayDataSystem(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs.meta new file mode 100644 index 0000000..fe1bcbf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/NetworkManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 54f9fcd655e04ba99afa430eec09c068 +timeCreated: 1681976638 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs b/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs new file mode 100644 index 0000000..39dd17e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs @@ -0,0 +1,246 @@ +using System; +using System.IO; +using UnityEngine; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public sealed partial class PreferencesMgr : BaseInterfaceManager + { + private Preferences preferences; + private DataDispatcher dataDispatcher; + + private PlayData c2s_preferencesMsg; + + private ObjectPool keyValuePool; + private List autoSaveList; + + public override void Init() + { + base.Init(); + AddListener(); + + c2s_preferencesMsg = new PlayData + { + data = new Dictionary() + }; + + keyValuePool = new ObjectPool(); + autoSaveList = new List(); + } + + public override void StartUp() + { + base.StartUp(); + + dataDispatcher = DataDispatcher.Instance; + //HACK preferences服务器数据实时存储 + TimerHelper.UnscaleGeneral.AddLoopTimer(10, OnAutoDelaySave); + } + + public override void DisposeBefore() + { + base.DisposeBefore(); + ImmediateSendSave(); + } + + public override void Dispose() + { + base.Dispose(); + RemoveListener(); + + //autoSaveTimer.Dispose(); + keyValuePool.Dispose(); + } + + private void AddListener() + { + AppDispatcher.Instance.AddListener(AppMsg.App_Pause_True, ImmediateSendSave); + } + + private void RemoveListener() + { + AppDispatcher.Instance.RemoveListener(AppMsg.App_Pause_True, ImmediateSendSave); + } + + public void InitPreferences() + { + LoginModel loginModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel; + + preferences = new Preferences(); + if (!loginModel.new_player) + { + preferences = ReadServerPreferencesCache(); + + var ser_dataVer = loginModel.play_data_ver; + if (preferences == null || ser_dataVer > preferences.data_ver) + { + preferences = loginModel.preferences; + } + + if (preferences == null) + { + preferences = new Preferences(); + } + } + else + { + PlayerPrefs.DeleteAll(); + NetworkKit.SetCacheToken(loginModel.token); + PlayerPrefs.Save(); + + } + + SaveServerPreferencesCache(preferences); + + OnInitPreferences(); + } + + private void AutoSaveList(List autolist) + { + if (autolist == null || autolist.Count == 0) return; + foreach (KeyValue item in autolist) + { + Save(item.key, item.value); + keyValuePool.Release(item); + } + + autolist.Clear(); + } + + private void AddDataVer() + { + ++Data_ver; + } + + /// + /// 立即发送保存 + /// + public void ImmediateSendSave(object arg = null) + { + AutoSaveList(autoSaveList); + PreferencesSendSave(); + } + + private void OnAutoDelaySave(TimerTask timerInfo) + { + AutoSaveList(autoSaveList); + PreferencesSendSave(); + } + + #region 远程存储 + + #region 保存方法 + + private void AddToAutoDelaySaveList(string key, object value) + { + KeyValue item = keyValuePool.Get(); + item.key = key; + item.value = value; + autoSaveList.Add(item); + + ImmediateSendSave(); + } + + private void Save(string key, T data) + { + c2s_preferencesMsg.data[key] = data; + } + + #endregion 保存方法 + + private void ClearPreferencesDic() + { + // c2s_preferencesMsg.data.Clear(); + } + + private long timeSave = 0; + private long unsaveCount = 0; + + private void PreferencesSendSave() + { + if (c2s_preferencesMsg == null || c2s_preferencesMsg.data.Count == 0) return; + + AddDataVer(); + + SaveServerPreferencesCache(preferences); + try + { + // if (unsaveCount < 3) + // { + // if (timeSave > 0 && GameHelper.GetNowTime() - timeSave < 3) + // { + // unsaveCount++; + // return; + // } + // } + + // unsaveCount = 0; + // timeSave = GameHelper.GetNowTime(); + // var data = SerializeUtil.ToObject>(SerializeUtil.ToJson(preferences)); + // NetworkDispatcher.Instance.Dispatch(NetworkMsg.SavePlayData, data); + } + catch (Exception e) + { + Debug.LogError(e); + throw; + } + + ClearPreferencesDic(); + } + + #endregion 远程存储 + + #region 封装 + + public Preferences GetPreferences() + { + return preferences; + } + + /// + /// 保存Preferences缓存服务器数据 + /// + public static void SaveServerPreferencesCache(Preferences preferences) + { + var text = SerializeUtil.ToJson(preferences); + if (!Directory.Exists(PlayerPrefsConst.CachePath + "/..")) + { + Directory.CreateDirectory(PlayerPrefsConst.CachePath + "/.."); + } + + File.WriteAllText(PlayerPrefsConst.CachePath, text); + } + + /// + /// 读取Preferences缓存服务器数据 + /// + public static Preferences ReadServerPreferencesCache() + { + Preferences preferences = null; + var path = PlayerPrefsConst.CachePath; + if (File.Exists(path)) + { + try + { + string text = File.ReadAllText(path); + if (string.IsNullOrEmpty(text)) + { + // Debug.LogError("[JsonEncryptUtil]ReadFormLocalFile decryptedString Fail: " + path); + preferences = null; + } + + preferences = SerializeUtil.ToObject(text); + } + catch (Exception) + { + // Debug.LogError("[LoginLocalCache]ReadServerPreferencesCache Fail!"); + } + } + + return preferences; + } + + #endregion 封装 + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs.meta new file mode 100644 index 0000000..17df456 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Manager/PreferencesMgr.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a99b010c051c8764b8de691284c7310c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager.meta new file mode 100644 index 0000000..abbb7c6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8794d2d9c82619641bbf19cd33ec0a5c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs new file mode 100644 index 0000000..414192c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs @@ -0,0 +1,59 @@ +namespace ScrewsMaster +{ + public static class CtrlConst + { + public const string ADTaskCtrl = "ADTaskCtrl"; + public const string CurrencyRewardCtrl = "CurrencyRewardCtrl"; + public const string GameLoginCtrl = "GameLoginCtrl"; + public const string FXWndCtrl = "FXWndCtrl"; + public const string JoastCtrl = "JoastCtrl"; + public const string MenuCtrl = "MenuCtrl"; + public const string LanguageWinCtrl = "LanguageWinCtrl"; + public const string MaskCtrl = "MaskCtrl"; + public const string ProfileCtrl = "ProfileCtrl"; + public const string NetLoadingCtrl = "NetLoadingCtrl"; + public const string LoadingCtrl = "LoadingCtrl"; + public const string OpenBgCtrl = "OpenBgCtrl"; + public const string RewardCtrl = "RewardCtrl"; + public const string PrivacyCtrl = "PrivacyCtrl"; + public const string PreferencesDataReadyCtrl = "PreferencesDataReadyCtrl"; + public const string LevelSuccessCtrl = "LevelSuccessCtrl"; + public const string SheepPlayCtrl = "SheepPlayCtrl"; + public const string CoinWnd_newCtrl = "CoinWnd_newCtrl"; + public const string SheepwindowCtrl = "SheepwindowCtrl"; + public const string RemakeCtrl = "RemakeCtrl"; + public const string BuyslotCtrl = "BuyslotCtrl"; + public const string ScreenViewCtrl = "ScreenViewCtrl"; + public const string OpenGameCtrl = "OpenGameCtrl"; + public const string H5Ctrl = "H5Ctrl"; + public const string NewTaskCtrl = "NewTaskCtrl"; + public const string GetTaskRewardCtrl = "GetTaskRewardCtrl"; + public const string RewardboxCtrl = "RewardboxCtrl"; + public const string PackrewardCtrl = "PackrewardCtrl"; + public const string BuygoldCtrl = "BuygoldCtrl"; + public const string MakeupConfirmCtrl = "MakeupConfirmCtrl"; + public const string MakeupRecordCtrl = "MakeupRecordCtrl"; + public const string MakeupStepCtrl = "MakeupStepCtrl"; + public const string RegulationCtrl = "RegulationCtrl"; + public const string PixPayCtrl = "PixPayCtrl"; + public const string WebViewCtrl = "WebViewCtrl"; + public const string PayloadingCtrl = "PayloadingCtrl"; + public const string AdcomingCtrl = "AdcomingCtrl"; + public const string PassunlockCtrl = "PassunlockCtrl"; + public const string FirstRewardCtrl = "FirstRewardCtrl"; + public const string ReviveCtrl = "ReviveCtrl"; + public const string PropCtrl = "PropCtrl"; + public const string TipsCtrl = "TipsCtrl"; + + public const string SignInViewCtrl = "SignInViewCtrl"; + public const string PrizeWheelCtrl = "PrizeWheelCtrl"; + public const string GameHomeCtrl = "GameHomeCtrl"; + public const string RankCtrl = "RankCtrl"; + public const string ResurgenceCtrl = "ResurgenceCtrl"; + public const string SaveingPotCtrl = "SaveingPotCtrl"; + public const string BroadcastCtrl = "BroadcastCtrl"; + public const string RecordViewCtrl = "RecordViewCtrl"; + public const string ThreeDaysGiftCtrl = "ThreeDaysGiftCtrl"; + public const string RewardMulNewCtrl = "RewardMulNewCtrl"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs.meta new file mode 100644 index 0000000..53299cb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/CtrlConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6a30429d4802f924b86f9258ea857543 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs new file mode 100644 index 0000000..000912e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs @@ -0,0 +1,62 @@ +namespace ScrewsMaster +{ + public static class ModelConst + { + public const string LoginModel = "LoginModel"; + public const string MaskModel = "MaskModel"; + public const string RewardAniModel = "RewardAniModel"; + public const string FXWndModel = "FXWndModel"; + public const string CurrencyRewardModel = "CurrencyRewardModel"; + public const string GameLoginModel = "GameLoginModel"; + public const string JoastModel = "JoastModel"; + public const string LanguageWinModel = "LanguageWinModel"; + public const string PrivacyModel = "PrivacyModel"; + public const string LoadingModel = "LoadingModel"; + public const string ADTaskModel = "ADTaskModel"; + public const string OpenBgModel = "OpenBgModel"; + public const string ProfileModel = "ProfileModel"; + public const string NetLoadingModel = "NetLoadingModel"; + public const string MenuModel = "MenuModel"; + public const string SheepPlayModel = "SheepPlayModel"; + public const string CoinWnd_newModel = "CoinWnd_newModel"; + public const string RewardModel = "RewardModel"; + public const string RemakeModel = "RemakeModel"; + public const string SheepwindowModel = "SheepwindowModel"; + public const string LevelSuccessModel = "LevelSuccessModel"; + public const string BuyslotModel = "BuyslotModel"; + public const string ScreenViewModel = "ScreenViewModel"; + public const string OpenGameModel = "OpenGameModel"; + public const string H5Model = "H5Model"; + public const string NewTaskModel = "NewTaskModel"; + public const string GetTaskRewardModel = "GetTaskRewardModel"; + public const string RewardboxModel = "RewardboxModel"; + public const string PackrewardModel = "PackrewardModel"; + public const string BuygoldModel = "BuygoldModel"; + public const string MakeupConfirmModel = "MakeupConfirmModel"; + public const string MakeupRecordModel = "MakeupRecordModel"; + public const string MakeupStepModel = "MakeupStepModel"; + public const string RegulationModel = "RegulationModel"; + public const string PixPayModel = "PixPayModel"; + public const string GameUrlsConstModel = "GameUrlsConstModel"; + public const string GameUrlsModel = "GameUrlsModel"; + public const string PayloadingModel = "PayloadingModel"; + public const string AdcomingModel = "AdcomingModel"; + public const string PassunlockModel = "PassunlockModel"; + public const string FirstRewardModel = "FirstRewardModel"; + + public const string ReviveModel = "ReviveModel"; + public const string PropModel = "PropModel"; + public const string TipsModel = "TipsModel"; + + public const string SignInViewModel = "SignInViewModel"; + public const string PrizeWheelModel = "PrizeWheelModel"; + public const string GameHomeModel = "GameHomeModel"; + public const string RankModel = "RankModel"; + public const string ResurgenceModel = "ResurgenceModel"; + public const string SaveingPotModel = "SaveingPotModel"; + public const string BroadcastModel = "BroadcastModel"; + public const string RecordViewModel = "RecordViewModel"; + public const string ThreeDaysGiftModel = "ThreeDaysGiftModel"; + public const string RewardMulNewModel = "RewardMulNewModel"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs.meta new file mode 100644 index 0000000..6fed513 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModelConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea836ac66cd633041a2faa7aa15d3fb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs new file mode 100644 index 0000000..207923d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs @@ -0,0 +1,198 @@ + + +namespace ScrewsMaster +{ + public static class ModuleManagerRegister + { + public static void AutoRegisterModel() + { + ModuleManager moduleManager = ModuleManager.Instance; + moduleManager.AddModel(ModelConst.LoginModel, new LoginModel()); + moduleManager.AddModel(ModelConst.CurrencyRewardModel, new CurrencyRewardModel()); + moduleManager.AddModel(ModelConst.FXWndModel, new FXWndModel()); + moduleManager.AddModel(ModelConst.GameLoginModel, new GameLoginModel()); + moduleManager.AddModel(ModelConst.JoastModel, new JoastModel()); + moduleManager.AddModel(ModelConst.LoadingModel, new LoadingModel()); + moduleManager.AddModel(ModelConst.MaskModel, new MaskModel()); + moduleManager.AddModel(ModelConst.MenuModel, new MenuModel()); + moduleManager.AddModel(ModelConst.NetLoadingModel, new NetLoadingModel()); + moduleManager.AddModel(ModelConst.OpenBgModel, new OpenBgModel()); + moduleManager.AddModel(ModelConst.PrivacyModel, new PrivacyModel()); + moduleManager.AddModel(ModelConst.ProfileModel, new ProfileModel()); + moduleManager.AddModel(ModelConst.RewardModel, new RewardModel()); + moduleManager.AddModel(ModelConst.SheepPlayModel, new SheepPlayModel()); + moduleManager.AddModel(ModelConst.CoinWnd_newModel, new CoinWnd_newModel()); + moduleManager.AddModel(ModelConst.LevelSuccessModel, new LevelSuccessModel()); + moduleManager.AddModel(ModelConst.OpenGameModel, new OpenGameModel()); + moduleManager.AddModel(ModelConst.NewTaskModel, new NewTaskModel()); + moduleManager.AddModel(ModelConst.GetTaskRewardModel, new GetTaskRewardModel()); + moduleManager.AddModel(ModelConst.RewardboxModel, new RewardboxModel()); + moduleManager.AddModel(ModelConst.PayloadingModel, new PayloadingModel()); + moduleManager.AddModel(ModelConst.AdcomingModel, new AdcomingModel()); + moduleManager.AddModel(ModelConst.ReviveModel, new ReviveModel()); + moduleManager.AddModel(ModelConst.PropModel, new PropModel()); + moduleManager.AddModel(ModelConst.TipsModel, new TipsModel()); + moduleManager.AddModel(ModelConst.MakeupConfirmModel, new MakeupConfirmModel()); + moduleManager.AddModel(ModelConst.MakeupRecordModel, new MakeupRecordModel()); + moduleManager.AddModel(ModelConst.H5Model, new H5Model()); + moduleManager.AddModel(ModelConst.BuygoldModel, new BuygoldModel()); + moduleManager.AddModel(ModelConst.PackrewardModel, new PackRewardModel()); + moduleManager.AddModel(ModelConst.FirstRewardModel, new FirstRewardModel()); + moduleManager.AddModel(ModelConst.PassunlockModel, new PassunlockModel()); + + moduleManager.AddModel(ModelConst.SignInViewModel, new SignInViewModel()); + moduleManager.AddModel(ModelConst.PrizeWheelModel, new PrizeWheelModel()); + moduleManager.AddModel(ModelConst.GameHomeModel, new GameHomeModel()); + moduleManager.AddModel(ModelConst.RankModel, new RankModel()); + moduleManager.AddModel(ModelConst.ResurgenceModel, new ResurgenceModel()); + moduleManager.AddModel(ModelConst.SaveingPotModel, new SaveingPotModel()); + moduleManager.AddModel(ModelConst.BroadcastModel, new BroadcastModel()); + moduleManager.AddModel(ModelConst.RecordViewModel, new RecordViewModel()); + moduleManager.AddModel(ModelConst.ThreeDaysGiftModel, new ThreeDaysGiftModel()); + moduleManager.AddModel(ModelConst.RewardMulNewModel, new RewardMulNewModel()); + } + public static void AutoRegisterUICtrl() + { + ModuleManager moduleManager = ModuleManager.Instance; + moduleManager.AddUICtrl(UICtrlConst.CurrencyRewardUICtrl, new CurrencyRewardUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.FXWndUICtrl, new FXWndUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.GameLoginUICtrl, new GameLoginUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.JoastUICtrl, new JoastUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.LoadingUICtrl, new LoadingUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.MaskUICtrl, new MaskUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.MenuUICtrl, new MenuUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.NetLoadingUICtrl, new NetLoadingUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.OpenBgUICtrl, new OpenBgUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.PrivacyUICtrl, new PrivacyUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.ProfileUICtrl, new ProfileUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.RewardUICtrl, new RewardUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.SheepPlayUICtrl, new SheepPlayUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.CoinWnd_newUICtrl, new CoinWnd_newUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.LevelSuccessUICtrl, new LevelSuccessUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.OpenGameUICtrl, new OpenGameUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.NewTaskUICtrl, new NewTaskUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.GetTaskRewardUICtrl, new GetTaskRewardUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.RewardboxUICtrl, new RewardboxUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.MakeupConfirmUICtrl, new MakeupConfirmUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.MakeupRecordUICtrl, new MakeupRecordUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.H5UICtrl, new H5UICtrl()); + moduleManager.AddUICtrl(UICtrlConst.BuygoldUICtrl, new BuygoldUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.PackrewardUICtrl, new PackRewardUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.FirstRewardUICtrl, new FirstRewardUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.PassunlockUICtrl, new PassunlockUICtrl()); + + moduleManager.AddUICtrl(UICtrlConst.PayloadingUICtrl, new PayloadingUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.AdcomingUICtrl, new AdcomingUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.SignInViewUICtrl, new SignInViewUICtrl()); + + moduleManager.AddUIType(UIConst.ReviveUI, typeof(ReviveUI)); + moduleManager.AddUIType(UIConst.PropUI, typeof(PropUI)); + moduleManager.AddUIType(UIConst.TipsUI, typeof(TipsUI)); + moduleManager.AddUIType(UIConst.PrizeWheelUI, typeof(PrizeWheelUI)); + moduleManager.AddUIType(UIConst.GameHomeUI, typeof(GameHomeUI)); + moduleManager.AddUIType(UIConst.RankUI, typeof(RankUI)); + moduleManager.AddUICtrl(UICtrlConst.ResurgenceUICtrl, new ResurgenceUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.SaveingPotUICtrl, new SaveingPotUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.BroadcastUICtrl, new BroadcastUICtrl()); + + moduleManager.AddUICtrl(UICtrlConst.RecordViewUICtrl, new RecordViewUICtrl()); + moduleManager.AddUIType(UIConst.ThreeDaysGiftUI, typeof(ThreeDaysGiftUI)); + moduleManager.AddUIType(UIConst.RewardMulNewUI, typeof(RewardMulNewUI)); + } + + public static void AutoRegisterCtrl() + { + ModuleManager moduleManager = ModuleManager.Instance; + moduleManager.AddCtrl(CtrlConst.CurrencyRewardCtrl, new CurrencyRewardCtrl()); + moduleManager.AddCtrl(CtrlConst.FXWndCtrl, new FXWndCtrl()); + moduleManager.AddCtrl(CtrlConst.GameLoginCtrl, new GameLoginCtrl()); + moduleManager.AddCtrl(CtrlConst.JoastCtrl, new JoastCtrl()); + moduleManager.AddCtrl(CtrlConst.LoadingCtrl, new LoadingCtrl()); + moduleManager.AddCtrl(CtrlConst.MaskCtrl, new MaskCtrl()); + moduleManager.AddCtrl(CtrlConst.MenuCtrl, new MenuCtrl()); + moduleManager.AddCtrl(CtrlConst.NetLoadingCtrl, new NetLoadingCtrl()); + moduleManager.AddCtrl(CtrlConst.OpenBgCtrl, new OpenBgCtrl()); + moduleManager.AddCtrl(CtrlConst.PrivacyCtrl, new PrivacyCtrl()); + moduleManager.AddCtrl(CtrlConst.ProfileCtrl, new ProfileCtrl()); + moduleManager.AddCtrl(CtrlConst.RewardCtrl, new RewardCtrl()); + moduleManager.AddCtrl(CtrlConst.PreferencesDataReadyCtrl, new PreferencesDataReadyCtrl()); + moduleManager.AddCtrl(CtrlConst.SheepPlayCtrl, new SheepPlayCtrl()); + moduleManager.AddCtrl(CtrlConst.CoinWnd_newCtrl, new CoinWnd_newCtrl()); + moduleManager.AddCtrl(CtrlConst.LevelSuccessCtrl, new LevelSuccessCtrl()); + moduleManager.AddCtrl(CtrlConst.OpenGameCtrl, new OpenGameCtrl()); + moduleManager.AddCtrl(CtrlConst.NewTaskCtrl, new NewTaskCtrl()); + moduleManager.AddCtrl(CtrlConst.GetTaskRewardCtrl, new GetTaskRewardCtrl()); + moduleManager.AddCtrl(CtrlConst.RewardboxCtrl, new RewardboxCtrl()); + moduleManager.AddCtrl(CtrlConst.PayloadingCtrl, new PayloadingCtrl()); + moduleManager.AddCtrl(CtrlConst.AdcomingCtrl, new AdcomingCtrl()); + moduleManager.AddCtrl(CtrlConst.ReviveCtrl, new ReviveCtrl()); + moduleManager.AddCtrl(CtrlConst.PropCtrl, new PropCtrl()); + moduleManager.AddCtrl(CtrlConst.TipsCtrl, new TipsCtrl()); + moduleManager.AddCtrl(CtrlConst.MakeupConfirmCtrl, new MakeupConfirmCtrl()); + moduleManager.AddCtrl(CtrlConst.MakeupRecordCtrl, new MakeupRecordCtrl()); + moduleManager.AddCtrl(CtrlConst.H5Ctrl, new H5Ctrl()); + moduleManager.AddCtrl(CtrlConst.BuygoldCtrl, new BuygoldCtrl()); + moduleManager.AddCtrl(CtrlConst.PackrewardCtrl, new PackRewardCtrl()); + moduleManager.AddCtrl(CtrlConst.FirstRewardCtrl, new FirstRewardCtrl()); + moduleManager.AddCtrl(CtrlConst.PassunlockCtrl, new PassunlockCtrl()); + + moduleManager.AddCtrl(CtrlConst.SignInViewCtrl, new SignInViewCtrl()); + moduleManager.AddCtrl(CtrlConst.PrizeWheelCtrl, new PrizeWheelCtrl()); + moduleManager.AddCtrl(CtrlConst.GameHomeCtrl, new GameHomeCtrl()); + moduleManager.AddCtrl(CtrlConst.RankCtrl, new RankCtrl()); + moduleManager.AddCtrl(CtrlConst.ResurgenceCtrl, new ResurgenceCtrl()); + moduleManager.AddCtrl(CtrlConst.SaveingPotCtrl, new SaveingPotCtrl()); + moduleManager.AddCtrl(CtrlConst.BroadcastCtrl, new BroadcastCtrl()); + moduleManager.AddCtrl(CtrlConst.RecordViewCtrl, new RecordViewCtrl()); + moduleManager.AddCtrl(CtrlConst.ThreeDaysGiftCtrl, new ThreeDaysGiftCtrl()); + moduleManager.AddCtrl(CtrlConst.RewardMulNewCtrl, new RewardMulNewCtrl()); + } + + public static void AutoRegisterUIType() + { + ModuleManager moduleManager = ModuleManager.Instance; + moduleManager.AddUIType(UIConst.CurrencyRewardUI, typeof(CurrencyRewardUI)); + moduleManager.AddUIType(UIConst.FXWndUI, typeof(FXWndUI)); + moduleManager.AddUIType(UIConst.GameLoginUI, typeof(GameLoginUI)); + moduleManager.AddUIType(UIConst.JoastUI, typeof(JoastUI)); + moduleManager.AddUIType(UIConst.LoadingUI, typeof(LoadingUI)); + moduleManager.AddUIType(UIConst.MaskUI, typeof(MaskUI)); + moduleManager.AddUIType(UIConst.MenuUI, typeof(MenuUI)); + moduleManager.AddUIType(UIConst.NetLoadingUI, typeof(NetLoadingUI)); + moduleManager.AddUIType(UIConst.OpenBgUI, typeof(OpenBgUI)); + moduleManager.AddUIType(UIConst.PrivacyUI, typeof(PrivacyUI)); + moduleManager.AddUIType(UIConst.ProfileUI, typeof(ProfileUI)); + moduleManager.AddUIType(UIConst.RewardUI, typeof(RewardUI)); + moduleManager.AddUIType(UIConst.SheepPlayUI, typeof(SheepPlayUI)); + moduleManager.AddUIType(UIConst.CoinWnd_newUI, typeof(CoinWnd_newUI)); + moduleManager.AddUIType(UIConst.LevelSuccessUI, typeof(LevelSuccessUI)); + moduleManager.AddUIType(UIConst.OpenGameUI, typeof(OpenGameUI)); + moduleManager.AddUIType(UIConst.NewTaskUI, typeof(NewTaskUI)); + moduleManager.AddUIType(UIConst.GetTaskRewardUI, typeof(GetTaskRewardUI)); + moduleManager.AddUIType(UIConst.RewardboxUI, typeof(RewardboxUI)); + moduleManager.AddUIType(UIConst.PayloadingUI, typeof(PayloadingUI)); + moduleManager.AddUIType(UIConst.AdcomingUI, typeof(AdcomingUI)); + moduleManager.AddUICtrl(UICtrlConst.ReviveUICtrl, new ReviveUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.PropUICtrl, new PropUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.TipsUICtrl, new TipsUICtrl()); + moduleManager.AddUIType(UIConst.MakeupConfirmUI, typeof(MakeupConfirmUI)); + moduleManager.AddUIType(UIConst.MakeupRecordUI, typeof(MakeupRecordUI)); + moduleManager.AddUIType(UIConst.H5UI, typeof(H5UI)); + moduleManager.AddUIType(UIConst.BuygoldUI, typeof(BuygoldUI)); + moduleManager.AddUIType(UIConst.PackrewardUI, typeof(PackRewardUI)); + moduleManager.AddUIType(UIConst.FirstRewardUI, typeof(FirstRewardUI)); + moduleManager.AddUIType(UIConst.PassunlockUI, typeof(PassunlockUI)); + + moduleManager.AddUIType(UIConst.SignInViewUI, typeof(SignInViewUI)); + moduleManager.AddUICtrl(UICtrlConst.PrizeWheelUICtrl, new PrizeWheelUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.GameHomeUICtrl, new GameHomeUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.RankUICtrl, new RankUICtrl()); + moduleManager.AddUIType(UIConst.ResurgenceUI, typeof(ResurgenceUI)); + moduleManager.AddUIType(UIConst.SaveingPotUI, typeof(SaveingPotUI)); + moduleManager.AddUIType(UIConst.BroadcastUI, typeof(BroadcastUI)); + moduleManager.AddUIType(UIConst.RecordViewUI, typeof(RecordViewUI)); + moduleManager.AddUICtrl(UICtrlConst.ThreeDaysGiftUICtrl, new ThreeDaysGiftUICtrl()); + moduleManager.AddUICtrl(UICtrlConst.RewardMulNewUICtrl, new RewardMulNewUICtrl()); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs.meta new file mode 100644 index 0000000..96147aa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/ModuleManagerRegister.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 959c9f91766f6f34bb5f9d91c33dbe0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs new file mode 100644 index 0000000..6b1121d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs @@ -0,0 +1,57 @@ +namespace ScrewsMaster +{ + public static class UIConst + { + public const string GameLoginUI = "GameLoginUI"; + public const string CurrencyRewardUI = "CurrencyRewardUI"; + public const string ADTaskUI = "ADTaskUI"; + public const string JoastUI = "JoastUI"; + public const string LanguageWinUI = "LanguageWinUI"; + public const string MenuUI = "MenuUI"; + public const string MaskUI = "MaskUI"; + public const string LoadingUI = "LoadingUI"; + public const string NetLoadingUI = "NetLoadingUI"; + public const string CoinWnd_newUI = "CoinWnd_newUI"; + public const string FXWndUI = "FXWndUI"; + public const string OpenBgUI = "OpenBgUI"; + public const string PrivacyUI = "PrivacyUI"; + public const string RewardUI = "RewardUI"; + public const string RemakeUI = "RemakeUI"; + public const string H5UI = "H5UI"; + public const string SheepPlayUI = "SheepPlayUI"; + public const string ProfileUI = "ProfileUI"; + public const string LevelSuccessUI = "LevelSuccessUI"; + public const string BuyslotUI = "BuyslotUI"; + public const string SheepwindowUI = "SheepwindowUI"; + public const string ScreenViewUI = "ScreenViewUI"; + public const string OpenGameUI = "OpenGameUI"; + public const string NewTaskUI = "NewTaskUI"; + public const string GetTaskRewardUI = "GetTaskRewardUI"; + public const string RewardboxUI = "RewardboxUI"; + public const string PackrewardUI = "PackrewardUI"; + public const string BuygoldUI = "BuygoldUI"; + public const string MakeupConfirmUI = "MakeupConfirmUI"; + public const string MakeupRecordUI = "MakeupRecordUI"; + public const string MakeupStepUI = "MakeupStepUI"; + public const string RegulationUI = "RegulationUI"; + public const string PixPayUI = "PixPayUI"; + public const string PayloadingUI = "PayloadingUI"; + public const string AdcomingUI = "AdcomingUI"; + public const string PassunlockUI = "PassunlockUI"; + public const string FirstRewardUI = "FirstRewardUI"; + public const string ReviveUI = "ReviveUI"; + public const string PropUI = "PropUI"; + public const string TipsUI = "TipsUI"; + + public const string SignInViewUI = "SignInViewUI"; + public const string PrizeWheelUI = "PrizeWheelUI"; + public const string GameHomeUI = "GameHomeUI"; + public const string RankUI = "RankUI"; + public const string ResurgenceUI = "ResurgenceUI"; + public const string SaveingPotUI = "SaveingPotUI"; + public const string BroadcastUI = "BroadcastUI"; + public const string RecordViewUI = "RecordViewUI"; + public const string ThreeDaysGiftUI = "ThreeDaysGiftUI"; + public const string RewardMulNewUI = "RewardMulNewUI"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs.meta new file mode 100644 index 0000000..0463170 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UIConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a037c3a4325f1c419b2352651eb90c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs new file mode 100644 index 0000000..01097e9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs @@ -0,0 +1,57 @@ +namespace ScrewsMaster +{ + public static class UICtrlConst + { + public const string ADTaskUICtrl = "ADTaskUICtrl"; + public const string JoastUICtrl = "JoastUICtrl"; + public const string LoadingUICtrl = "LoadingUICtrl"; + public const string MaskUICtrl = "MaskUICtrl"; + public const string ProfileUICtrl = "ProfileUICtrl"; + public const string CurrencyRewardUICtrl = "CurrencyRewardUICtrl"; + public const string FXWndUICtrl = "FXWndUICtrl"; + public const string SheepwindowUICtrl = "SheepwindowUICtrl"; + public const string LevelSuccessUICtrl = "LevelSuccessUICtrl"; + public const string MenuUICtrl = "MenuUICtrl"; + public const string NetLoadingUICtrl = "NetLoadingUICtrl"; + public const string GameLoginUICtrl = "GameLoginUICtrl"; + public const string LanguageWinUICtrl = "LanguageWinUICtrl"; + public const string RewardUICtrl = "RewardUICtrl"; + public const string CoinWnd_newUICtrl = "CoinWnd_newUICtrl"; + public const string SheepPlayUICtrl = "SheepPlayUICtrl"; + public const string RemakeUICtrl = "RemakeUICtrl"; + public const string OpenBgUICtrl = "OpenBgUICtrl"; + public const string PrivacyUICtrl = "PrivacyUICtrl"; + public const string BuyslotUICtrl = "BuyslotUICtrl"; + public const string ScreenViewUICtrl = "ScreenViewUICtrl"; + public const string OpenGameUICtrl = "OpenGameUICtrl"; + public const string H5UICtrl = "H5UICtrl"; + public const string NewTaskUICtrl = "NewTaskUICtrl"; + public const string GetTaskRewardUICtrl = "GetTaskRewardUICtrl"; + public const string RewardboxUICtrl = "RewardboxUICtrl"; + public const string PackrewardUICtrl = "PackrewardUICtrl"; + public const string BuygoldUICtrl = "BuygoldUICtrl"; + public const string MakeupConfirmUICtrl = "MakeupConfirmUICtrl"; + public const string MakeupRecordUICtrl = "MakeupRecordUICtrl"; + public const string MakeupStepUICtrl = "MakeupStepUICtrl"; + public const string RegulationUICtrl = "RegulationUICtrl"; + public const string PixPayUICtrl = "PixPayUICtrl"; + public const string PayloadingUICtrl = "PayloadingUICtrl"; + public const string AdcomingUICtrl = "AdcomingUICtrl"; + public const string PassunlockUICtrl = "PassunlockUICtrl"; + public const string FirstRewardUICtrl = "FirstRewardUICtrl"; + public const string ReviveUICtrl = "ReviveUICtrl"; + public const string PropUICtrl = "PropUICtrl"; + public const string TipsUICtrl = "TipsUICtrl"; + + public const string SignInViewUICtrl = "SignInViewUICtrl"; + public const string PrizeWheelUICtrl = "PrizeWheelUICtrl"; + public const string GameHomeUICtrl = "GameHomeUICtrl"; + public const string RankUICtrl = "RankUICtrl"; + public const string ResurgenceUICtrl = "ResurgenceUICtrl"; + public const string SaveingPotUICtrl = "SaveingPotUICtrl"; + public const string BroadcastUICtrl = "BroadcastUICtrl"; + public const string RecordViewUICtrl = "RecordViewUICtrl"; + public const string ThreeDaysGiftUICtrl = "ThreeDaysGiftUICtrl"; + public const string RewardMulNewUICtrl = "RewardMulNewUICtrl"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs.meta new file mode 100644 index 0000000..6d4ec3d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleManager/UICtrlConst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2fbf1793862578a4dab315b44d01ee43 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI.meta new file mode 100644 index 0000000..4281611 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2f7a7214a5891b640947dcf6105bb911 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming.meta new file mode 100644 index 0000000..1dfb710 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 988b707cb9f64d54c988a4304e5174e9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs new file mode 100644 index 0000000..2429e48 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class AdcomingCtrl : BaseCtrl + { + public static AdcomingCtrl Instance { get; private set; } + + private AdcomingModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.AdcomingModel) as AdcomingModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs.meta new file mode 100644 index 0000000..bb03133 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8bd042de9ef64e59b65fefb9788f71d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs new file mode 100644 index 0000000..21b4c30 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class AdcomingModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs.meta new file mode 100644 index 0000000..eb4538d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29789969ee11944f8be5196fc0b81532 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs new file mode 100644 index 0000000..5252282 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs @@ -0,0 +1,107 @@ +using DG.Tweening; + +namespace ScrewsMaster +{ + public class AdcomingUI : BaseUI + { + private AdcomingUICtrl ctrl; + private AdcomingModel model; + private FGUI.G008_reward.com_adcoming ui; + + public AdcomingUI(AdcomingUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.AdcomingUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_adcoming"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.AdcomingModel) as AdcomingModel; + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_adcoming; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.pack_close, playAni); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.pack_close, playAni); + } + #endregion + private int time = 5; + + //初始化页面逻辑 + private void InitView() + { + ui.time_text.text = time.ToString(); + + tweer = DOVirtual.Float(time, 0, time, value => { ui.time_text.text = ((int)value).ToString(); }); + tweer.onComplete += () => + { + CtrlCloseUI(); + GameHelper.ShowInterstitial("interstitial_gameend"); + }; + ui.btn_removead.SetClick(() => + { + if (UIManager.Instance.IsExistUI(UIConst.PackrewardUI)) + { + var ui = UIManager.Instance.GetDynamicUI(UIConst.PackrewardUI); + ui.baseUI.sortingOrder = 100; + } + else + { + PackRewardData param = new PackRewardData(); + param.isAutoPop = false; + param.isNeedScroll = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + } + tweer.Pause(); + }); + + } + private Tween tweer; + void playAni(object a) + { + tweer.Play(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs.meta new file mode 100644 index 0000000..519c7f7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dfe9a378b6c07410b91e71ce80c75a05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs new file mode 100644 index 0000000..b66ca27 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class AdcomingUICtrl : BaseUICtrl + { + private AdcomingUI ui; + private AdcomingModel model; + + private uint openUIMsg = UICtrlMsg.AdcomingUI_Open; + private uint closeUIMsg = UICtrlMsg.AdcomingUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.AdcomingModel) as AdcomingModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new AdcomingUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs.meta new file mode 100644 index 0000000..c98e0e5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Adcoming/AdcomingUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbf393f35eff5477da2f9c69a02c3822 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast.meta new file mode 100644 index 0000000..803d894 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 23ca926049ce946478bede18b0bef7f1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs new file mode 100644 index 0000000..c9245e7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class BroadcastCtrl : BaseCtrl + { + public static BroadcastCtrl Instance { get; private set; } + + private BroadcastModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs.meta new file mode 100644 index 0000000..cddf44f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 575f1d3d71a8445bc8d960a3f33d8bc1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs new file mode 100644 index 0000000..07cd029 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs @@ -0,0 +1,13 @@ +namespace ScrewsMaster +{ + public class BroadcastModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs.meta new file mode 100644 index 0000000..e9c37b9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2362fee130b6f4067b943f44ba629113 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs new file mode 100644 index 0000000..9e1f564 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs @@ -0,0 +1,207 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.A000_common; +using System; +using DG.Tweening; +using Spine.Unity; + +namespace ScrewsMaster +{ + public class BroadcastUI : BaseUI + { + private BroadcastUICtrl ctrl; + private BroadcastModel model; + private FGUI.A000_common.com_broadcast1 ui; + + public BroadcastUI(BroadcastUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.BroadcastUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "A000_common"; + uiInfo.assetName = "com_broadcast1"; + uiInfo.layerType = UILayerType.Top; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.A000_common.com_broadcast1; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + //ui.y = 241; + + // if (UIManager.Instance.IsExistUI(UIConst.RainPlayUI)) + // { + // Setbuttom(); + // } + // else + // { + Settop(); + //} + // ui.visible = false; + // if (Screen.safeArea.y != 0) + // {//刘海屏 + // ui.y += Screen.safeArea.y; + // } + text_ui = ui.broad_cast_text; + + ui.btn_record.SetClick(OpenRecord); + ui.broad_cast_text.btn_broad.SetClick(OpenRecord); + + if (ConfigSystem.GetConfig() == null) return; + config_name_list = ConfigSystem.GetConfig().config_name_list; + config_money_list = ConfigSystem.GetConfig().config_money_list; + GameDispatcher.Instance.AddListener(GameMsg.hideBroadCast, hideEvent); + GameDispatcher.Instance.AddListener(GameMsg.showBroadCast, showEvent); + // UICtrlDispatcher.Instance.AddListener(UICtrlMsg.MainUI_Open, Settop); + // UICtrlDispatcher.Instance.AddListener(UICtrlMsg.RainPlayUI_Open, Setbuttom); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + private int time_count = 11; + private com_broadcast_text1 text_ui; + private List config_name_list; + private List config_money_list; + private bool main_ui_show = true; + //初始化页面逻辑 + + private Action closeCallback = null; + private void InitView() + { + HallManager.Instance.UpdateSecondEvent += timeEvent; + + + var sk = FXManager.Instance.SetFx(ui.broad_cast_text.bg_panel, Fx_Type.fx_broad, ref closeCallback); + sk.state.SetAnimation(0, "animation", true); + } + + private void OpenRecord() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RecordViewUI_Open); + } + private void hideEvent(object sender = null) + { + Debug.Log("hide"); + main_ui_show = false; + ui.visible = false; + } + private void showEvent(object sender = null) + { + Debug.Log("show"); + main_ui_show = true; + ui.visible = true; + } + private void Settop(object sender = null) + { + ui.group_.y = 196; + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.group_.y += Screen.safeArea.y; + } + } + private void Setbuttom(object sender = null) + { + ui.group_.y = GRoot.inst.height - 300; + } + void timeEvent() + { + time_count++; + // if (time_count > 30) + // { + // time_count = 0; + // var name_index = UnityEngine.Random.Range(0, config_name_list.Count); + // var money_index = UnityEngine.Random.Range(0, config_money_list.Count); + // if (main_ui_show) + // { + // ui.visible = true; + // } + // Debug.Log(text_ui.cast_text.text); + // text_ui.cast_text.text = String.Format(text_ui.hide_text.text, config_name_list[name_index], + // config_money_list[money_index], DateTimeManager.Instance.GetCurrDateTime()); + // text_ui.cast_text.x = 686; + // Tweener tweener = DOTween.To(() => text_ui.cast_text.x, + // x => text_ui.cast_text.x = x, -1300, 10); + + // } + + // time_count = 0; + + + //Debug.Log($"barry broad time count======== {time_count}"); + if (time_count > 20) + { + time_count = 0; + var name_index = UnityEngine.Random.Range(0, config_name_list.Count); + var money_index = UnityEngine.Random.Range(0, config_money_list.Count); + Debug.Log(text_ui.cast_text.text); + + string name = config_name_list[name_index]; + if (name.Length > 4) + { + name = name[..4] + "..."; + } + string broad_text = String.Format(text_ui.hide_text.text, name, + "$" + config_money_list[money_index], DateTimeManager.Instance.GetCurrDateTime()); + text_ui.cast_text.text = broad_text; + // Tweener tweener = DOTween.To(() => ui.broad.x, + // x => ui.broad.x = x, 200, 0.5f); + ui.t0.Play(); + + DOVirtual.DelayedCall(3.5f, () => + { + // Tweener tweener = DOTween.To(() => ui.broad.x, + // x => ui.broad.x = x, 1080, 0.5f); + ui.t1.Play(); + }); + string str = name + "-" + config_money_list[money_index] + "-" + DateTimeManager.Instance.GetCurrDateTime(); + GameDispatcher.Instance.Dispatch(GameMsg.updateRecordList, str); + + } + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs.meta new file mode 100644 index 0000000..dfcf258 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d9a4125b4c0c64c94857a7ac85479526 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs new file mode 100644 index 0000000..7d6ec90 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs @@ -0,0 +1,77 @@ +using System.Collections; +using System.Collections.Generic; + + +namespace ScrewsMaster + +{ + public class BroadcastUICtrl : BaseUICtrl + { + private BroadcastUI ui; + private BroadcastModel model; + + private uint openUIMsg = UICtrlMsg.BroadcastUI_Open; + private uint closeUIMsg = UICtrlMsg.BroadcastUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.BroadcastModel) as BroadcastModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new BroadcastUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs.meta new file mode 100644 index 0000000..cedb61d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Broadcast/BroadcastUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35a4fff4d50cc4404951bdbed6e43b22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold.meta new file mode 100644 index 0000000..ac4650b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d8a71a4c41804ca9b8fddff13e97aecf +timeCreated: 1729595199 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs new file mode 100644 index 0000000..a38b995 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class BuygoldCtrl : BaseCtrl + { + public static BuygoldCtrl Instance { get; private set; } + + private BuygoldModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.BuygoldModel) as BuygoldModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs.meta new file mode 100644 index 0000000..1cd436b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2342594a3679d4cc3871150e477d7ffb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs new file mode 100644 index 0000000..003f1df --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class BuygoldModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs.meta new file mode 100644 index 0000000..c49595c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 14fccb4c1b1fb4e7188a1c7a070629dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs new file mode 100644 index 0000000..be2f0d7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs @@ -0,0 +1,436 @@ +using System.Collections.Generic; +using UnityEngine; +using FGUI.G012_openReward; +using System; +using DG.Tweening; +using FairyGUI; + +namespace ScrewsMaster +{ + public class BuygoldUI : BaseUI + { + private BuygoldUICtrl ctrl; + private BuygoldModel model; + private FGUI.G012_openReward.com_buygold ui; + + + + public BuygoldUI(BuygoldUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.BuygoldUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G012_openReward"; + uiInfo.assetName = "com_buygold"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.BuygoldModel) as BuygoldModel; + } + + protected override void OnClose() + { + GameHelper.showGameUI = true; + HallManager.Instance.UpdateSecondEvent -= InitList; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G012_openReward.com_buygold; + } + + protected override void OnOpenBefore(object args) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_show, 1); + ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1; + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed); + GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnAdWatchCountUpdated); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed); + GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnAdWatchCountUpdated); + } + + private void OnAdRewardClaimed(object args) + { + InitList(); + } + private void OnAdWatchCountUpdated(object args) + { + InitList(); + } + #endregion + void pay_success(object str) + { + string type = (string)str; + if (type.StartsWith("buy_gold")) + { + int startIndex = "buy_gold".Length; + string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 + int suffix_num = int.Parse(suffix); + + + switch (suffix_num) + { + case 0: + SaveData.GetSaveobject()._goldtime0 = (int)GameHelper.GetNowTime(); + break; + case 1: + SaveData.GetSaveobject()._goldtime1 = (int)GameHelper.GetNowTime(); + break; + case 2: + SaveData.GetSaveobject()._goldtime2 = (int)GameHelper.GetNowTime(); + break; + case 3: + SaveData.GetSaveobject()._goldtime3 = (int)GameHelper.GetNowTime(); + break; + case 4: + SaveData.GetSaveobject()._goldtime4 = (int)GameHelper.GetNowTime(); + break; + case 5: + SaveData.GetSaveobject()._goldtime5 = (int)GameHelper.GetNowTime(); + break; + case 6: + SaveData.GetSaveobject()._goldtime6 = (int)GameHelper.GetNowTime(); + break; + default: + return; + } + + SaveData.saveDataFunc(); + + var start = GameHelper.GetUICenterPosition((ui.list_item.GetChildAt(suffix_num) as buygold_item).coin_text); + var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start, end = end, change = list[suffix_num].Actual_coins, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddGoldNumber(list[suffix_num].Actual_coins); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f, + value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + InitList(); + } + + + } + + //初始化页面逻辑 + private void InitView() + { + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.top_gold.y += Screen.safeArea.y; + } + + ui.top_gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString(); + ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close); }); + // item_list.Add(ui.item4); + InitList(); + // + //Debug.Log(ConfigSystem.GetConfig().dataList); + HallManager.Instance.UpdateSecondEvent += InitList; + } + void InitList() + { + ui.text_hasADsCount.text = $"Owner ADs:{GameHelper.GetAdWatchCount()}"; + ui.list_item.itemRenderer = setRemaintime; + ui.list_item.numItems = list.Count; + + // for (int i = 0; i < item_list.Count; i++) + // { + // item_list[i].index.selectedIndex = i; + // setRemaintime(i, item_list[i]); + // } + + } + private List list = ConfigSystem.GetConfig().dataList; + + // void setPayClick(int index, buygold_item item) + // { + // var start = GameHelper.GetUICenterPosition(item.gold_bg); + // var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text")); + + + // reward_data temp = new reward_data() { start = start, end = end, change = 3, type = 101 }; + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + // GameHelper.addGoldNumber(3); + // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + // DOVirtual.DelayedCall(1, () => + // { + // DOVirtual.Float(0, (float)GameHelper.getGoldNumber(), 1f, + // value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); }); + // }); + + + // } + + + + void setRemaintime(int index, GObject obj) + { + int time = 0; + if (index == 0) time = SaveData.GetSaveobject()._goldtime0; + else if (index == 1) time = SaveData.GetSaveobject()._goldtime1; + else if (index == 2) time = SaveData.GetSaveobject()._goldtime2; + else if (index == 3) time = SaveData.GetSaveobject()._goldtime3; + else if (index == 4) time = SaveData.GetSaveobject()._goldtime4; + else if (index == 5) time = SaveData.GetSaveobject()._goldtime5; + else if (index == 6) time = SaveData.GetSaveobject()._goldtime6; + buygold_item item = obj as buygold_item; + if (index <= 4) item.index.selectedIndex = index; + else item.index.selectedIndex = 4; + item.btn_buy.img_saveingpot.visible = false; + var needWatchAds = false; + item.coin_text.text = "x" + list[index].Actual_coins.ToString(); + item.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1; + if (list[index].Discount_rate != 0) + { + item.off_text.text = list[index].Discount_rate + "%"; + item.show_off.selectedIndex = 1; + } + else item.show_off.selectedIndex = 0; + + + decimal price = 0; + price = Mathf.RoundToInt(list[index].Payment_amount); + if (time + list[index].receive_CD < GameHelper.GetNowTime()) //没在冷却 + { + + if (!GameHelper.IsAdModelOfPay()) + { + price = (decimal)list[index].Payment_amount2; + item.btn_buy.btn_text.text = "$ "+price; + + if (index == 0) + { + item.btn_buy.btn_text.text = "Free"; + item.btn_buy.SetClick(() => + { + PaySuccess(0); + }); + } + else + { + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) + { + item.btn_buy.img_saveingpot.visible = true; + } + item.btn_buy.SetClick(() => + { + ApplePayClass maxPayData = new ApplePayClass() + { + amount = (int)Math.Round(price * 100), + sku = getShopName(index), + currency = "USD", + shopName = $"buy_gold{index}" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + item.btn_buy.y = 330; + } + } + else + { + + if (index == 0) + { + item.btn_buy.btn_text.text = "Free"; + } + // else item.btn_buy.btn_text.text = GameHelper.GetPaymentTypeVO().payicon + list[index].Payment_amount; + else + { + + item.btn_buy.touchable = true; + item.btn_buy.grayed = false; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) + { + item.btn_buy.img_saveingpot.visible = true; + } + if (GameHelper.CheckAdWatchCount((int)price)) + { + item.btn_buy.btn_text.text = "Claim"; + item.btn_buy.img_saveingpot.visible = false; + } + else if (GameHelper.InAdRewardCooldown()) + { + item.btn_buy.btn_text.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + item.btn_buy.touchable = false; + item.btn_buy.grayed = true; + item.btn_buy.img_saveingpot.visible = false; + } + else + { + needWatchAds = true; + item.btn_buy.btn_text.text = $"Watch Ad"; + } + } + + item.btn_buy.SetClick(() => + { + if (index == 0) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_click + "_" + (index ), 1); + + PaySuccess(0); + + } + else + { + if (needWatchAds) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.gold_click + "_" + (index ), 1); + GameHelper.ShowVideoAd($"buy_gold{index}", success => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + return; + } + if (GameHelper.CheckAdWatchCount((int)price)) + { + GameHelper.AddAdWatchCount(-(int)price); + + PaySuccess(index); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + } + + } + }); + } + + + item.btn_buy.can_buy.selectedIndex = 0; + + } + else + { + if (index != 0 && !GameHelper.IsAdModelOfPay()) + { + item.btn_buy.y = 340; + } + + item.btn_buy.img_saveingpot.visible = false; + item.btn_buy.can_buy.selectedIndex = 1; + item.btn_buy.btn_text.text = CommonHelper.TimeFormat(time + list[index].receive_CD - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + item.btn_buy.SetClick(() => + { + + }); + } + item.text_priceDescription.text = index == 0 ? $"Daily Rewards" : $"Need {price} ADs"; + + } + public string getShopName(int index) + { + string name; + switch(index) + { + case 1: + name = PurchasingManager.buy_gold_1; + break; + case 2: + name = PurchasingManager.buy_gold_2; + break; + case 3: + name = PurchasingManager.buy_gold_3; + break; + case 4: + name = PurchasingManager.buy_gold_4; + break; + case 5: + name = PurchasingManager.buy_gold_5; + break; + default: + return ""; + + } + return name; + } + void PaySuccess(int index) + { + + + switch (index) + { + case 0: + SaveData.GetSaveobject()._goldtime0 = (int)GameHelper.GetNowTime(); + break; + case 1: + SaveData.GetSaveobject()._goldtime1 = (int)GameHelper.GetNowTime(); + break; + case 2: + SaveData.GetSaveobject()._goldtime2 = (int)GameHelper.GetNowTime(); + break; + case 3: + SaveData.GetSaveobject()._goldtime3 = (int)GameHelper.GetNowTime(); + break; + case 4: + SaveData.GetSaveobject()._goldtime4 = (int)GameHelper.GetNowTime(); + break; + case 5: + SaveData.GetSaveobject()._goldtime5 = (int)GameHelper.GetNowTime(); + break; + case 6: + SaveData.GetSaveobject()._goldtime6 = (int)GameHelper.GetNowTime(); + break; + default: + return; + } + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.GoldSuccess + "_" + (index ), 1); + SaveData.saveDataFunc(); + + var start = GameHelper.GetUICenterPosition((ui.list_item.GetChildAt(index) as buygold_item).coin_text); + var end = GameHelper.GetUICenterPosition(ui.top_gold.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start, end = end, change = list[index].Actual_coins, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddGoldNumber(list[index].Actual_coins); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f, + value => { ui.top_gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + InitList(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs.meta new file mode 100644 index 0000000..aa4fd27 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7de4ee29003a34adbb4ff4e0c97ed52c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs new file mode 100644 index 0000000..eb66b91 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class BuygoldUICtrl : BaseUICtrl + { + private BuygoldUI ui; + private BuygoldModel model; + + private uint openUIMsg = UICtrlMsg.BuygoldUI_Open; + private uint closeUIMsg = UICtrlMsg.BuygoldUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.BuygoldModel) as BuygoldModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new BuygoldUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs.meta new file mode 100644 index 0000000..38e4882 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Buygold/BuygoldUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfad94d0fa70d40bd8308f8fb11b9520 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new.meta new file mode 100644 index 0000000..617142a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 412aa0ea70abed443860a83b921a12d8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs new file mode 100644 index 0000000..9d57a6f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class CoinWnd_newCtrl : BaseCtrl + { + public static CoinWnd_newCtrl Instance { get; private set; } + + private CoinWnd_newModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.CoinWnd_newModel) as CoinWnd_newModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs.meta new file mode 100644 index 0000000..0089903 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 82125970c45e44fa3afcdd751aaa5418 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs new file mode 100644 index 0000000..89ad3b3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class CoinWnd_newModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs.meta new file mode 100644 index 0000000..861de17 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed7f9244ac32c442f874bfa7eac2cfc0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs new file mode 100644 index 0000000..6976e27 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs @@ -0,0 +1,258 @@ +using UnityEngine; +using FairyGUI; +using FGUI.G601_Coin; +using System; +using System.Text; +using DG.Tweening; + +namespace ScrewsMaster +{ + public class CoinWnd_newUI : BaseUI + { + private CoinWnd_newUICtrl ctrl; + private CoinWnd_newModel model; + private FGUI.G601_Coin.Com_CoinWnd_new ui; + + private reward_data pos_arr; + + private bool isUpdate = false; + + + + + private int completeSum = 0; + + + + + private float toSizeAniTime = 0.4f; + + + + + private float moveAniTime = 0.5f; + + + + + private float showAniTime = 0.1f; + + + + + private bool isRiseUI; + + private Action CloseCb; + public CoinWnd_newUI(CoinWnd_newUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.CoinWnd_newUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G601_Coin"; + uiInfo.assetName = "Com_CoinWnd_new"; + uiInfo.layerType = UILayerType.Animation; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + public override void OnUpdate() + { + if (!isUpdate) + { + if (isRiseUI) + { + // if (data.rewardSingleData.id == 101 || data.rewardSingleData.id == 111) + // { + + GameHelper.OnRiseUIRecover(pos_arr.type, UILayerType.Normal); + isRiseUI = false; + + + //} + } + + return; + } + + //data?.Update(); + } + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.CoinWnd_newModel) as CoinWnd_newModel; + } + + protected override void OnClose() + { + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Close);//2024年9月10日检查发现动画会调用全屏遮罩影响游戏体验,故而关闭 + CloseCb?.Invoke(); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G601_Coin.Com_CoinWnd_new; + } + + protected override void OnOpenBefore(object args) + { + if (AudioManager.Instance.IsOpenEffect) + { + AudioManager.Instance.PlayDynamicEffect(AudioConst.CoinFly); + } + pos_arr = (reward_data)args; + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Open);//2024年9月10日检查发现动画会调用全屏遮罩影响游戏体验,故而关闭 + + // if (args is RewardDisplayData displayModel) + // { + // data = displayModel; + // if (data.isPlayAudio) + // { + // AudioManager.Instance.PlayDynamicEffect(data.audioName); + // } + // } + + if (true) + { + // if (!data.isSingle) + // { + ShowText(); + // } + + + // ui.com_Coins.cont_coin.selectedIndex = !data.isSingle ? com_Coins.Coin_more : com_Coins.Coin_single; + // ui.com_Coins.position = data.rewardSingleData.startPosition; + ui.com_Coins.cont_coin.selectedIndex = com_Coins.Coin_more; + ui.com_Coins.position = pos_arr.start; + + float val = 0f; + + ui.fx_enter.position = ui.com_Coins.position; + + + foreach (var o in ui.com_Coins.GetChildren()) + { + var item = (com_Coin)o; + if (!item.visible) + { + continue; + } + + item.visible = false; + TextureHelper.GetItemIcon(pos_arr.type, spr => { item.icon.texture = spr; }); + float def = val; + DOVirtual.DelayedCall(0.05f, () => + { + item.visible = true; + + Vector2 tar = new Vector2(UnityEngine.Random.Range(0, item.parent.size.x / 1), + UnityEngine.Random.Range(0, item.parent.size.y / 1)); + item.size = Vector2.zero; + item.position = new Vector2(item.parent.width / 2, item.parent.height / 2); + // if (!data.isSingle) + // { + // } + // else + // { + // toSizeAniTime = 0.2f; + // } + + item.TweenMove(tar, toSizeAniTime + def); + DOTween.To(() => item.size, (e) => item.size = e, Vector2.one, toSizeAniTime + def); + item.icon.visible = true; + DOVirtual.DelayedCall(toSizeAniTime + def, () => + { + var moveTime = moveAniTime; + DOTween.To(() => item.icon.alpha, (e) => { item.icon.alpha = e; }, 0.6f, moveTime); + + item.TweenMove(pos_arr.end - (Vector2)item.parent.position + + item.parent.size / 2, moveTime); + + DOVirtual.DelayedCall(moveTime, () => + { + item.icon.visible = false; + completeSum++; + var fxPlayData = FxPlayData.Get(Fx_Type.fx_ui_jinbi_click, 1, + item.LocalToRoot(Vector2.zero, GRoot.inst)); + uiCtrlDispatcher.Dispatch(UICtrlMsg.PlayUIFX, fxPlayData); + + if (!isUpdate) + { + isUpdate = true; + + + + } + + if (completeSum >= ui.com_Coins.numChildren) + { + DOVirtual.DelayedCall(0.2f, () => { CtrlCloseUI(); }); + } + }); + }); + }); + val += 0.02f; + } + } + } + private void ShowText() + { + + var sb = new StringBuilder(); + sb.Append("+"); + // if (data.rewardSingleData.id == 101 || data.rewardSingleData.id == 111) + // { + + // sb.Append((data.rewardSingleData.GetTotalValue() * GameHelper.GetPaymentMulti()).ToString("N")); + sb.Append(pos_arr.change); + //} + // else + // { + // sb.Append(data.rewardSingleData.GetTotalValue().ToString("N0")); + // } + + ui.text_Add.SetText(sb.ToString()); + ui.text_Add.position = pos_arr.start; + ui.fx_addSum.Play(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + + } + } +} +class reward_data +{ + public Vector2 start; + public Vector2 end; + public float change; + public int type; +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs.meta new file mode 100644 index 0000000..ab54b85 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6320d97d6a3f34715a9194dc1bfc1336 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs new file mode 100644 index 0000000..cfc6ee4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class CoinWnd_newUICtrl : BaseUICtrl + { + private CoinWnd_newUI ui; + private CoinWnd_newModel model; + + private uint openUIMsg = UICtrlMsg.CoinWnd_newUI_Open; + private uint closeUIMsg = UICtrlMsg.CoinWnd_newUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.CoinWnd_newModel) as CoinWnd_newModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new CoinWnd_newUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs.meta new file mode 100644 index 0000000..067fe4a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CoinWnd_new/CoinWnd_newUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4074fed29af2547328f8116c839e8121 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward.meta new file mode 100644 index 0000000..6584eac --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b05bab87ee5860d45b1e0e643cda6b64 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs new file mode 100644 index 0000000..179cbd7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class CurrencyRewardCtrl : BaseCtrl + { + public static CurrencyRewardCtrl Instance { get; private set; } + + private CurrencyRewardModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs.meta new file mode 100644 index 0000000..296816c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 232c5fc22d0ebec41a34e1cf91ec335e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs new file mode 100644 index 0000000..9eeab8f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class CurrencyRewardModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs.meta new file mode 100644 index 0000000..15802b7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 08a25e84634bcd943ab1514b27f5f927 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs new file mode 100644 index 0000000..2e60e64 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs @@ -0,0 +1,181 @@ +namespace ScrewsMaster +{ + using System; + using FairyGUI; + using UnityEngine; + using DG.Tweening; + using System.Text; + using FGUI.G601_Coin; + using Random = UnityEngine.Random; + + public class CurrencyRewardUI : BaseUI + { + private CurrencyRewardUICtrl ctrl; + private CurrencyRewardModel model; + private FGUI.G601_Coin.Com_CoinWnd ui; + + public RewardDisplayData data; + private bool isUpdate = false; + private int completeSum = 0; + private float toSizeAniTime = 0.4f; + private float moveAniTime = 0.5f; + private float showAniTime = 0.1f; + private bool isRiseUI; + + private Action CloseCb; + + public CurrencyRewardUI(CurrencyRewardUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.CurrencyRewardUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G601_Coin"; + uiInfo.assetName = "Com_CoinWnd"; + uiInfo.layerType = UILayerType.Animation; + uiInfo.isTickUpdate = true; + } + + public override void OnUpdate() + { + if (!isUpdate) + { + if (isRiseUI) + { + if (data.rewardSingleData.id is 101 or 102) + { + GameHelper.OnRiseUIRecover(data.rewardSingleData.id, UILayerType.Normal); + isRiseUI = false; + } + } + + return; + } + + data?.Update(); + } + + #region 生命周期 + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.RewardAniModel) as CurrencyRewardModel; + } + + protected override void OnClose() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Close); + data?.EndEvent(); + DOVirtual.DelayedCall(Time.deltaTime, delegate + { + data?.UICloseEvent(); + data?.Dispose(); + }); + CloseCb?.Invoke(); + } + + protected override void OnBind() + { + ui = baseUI as Com_CoinWnd; + } + + protected override void OnOpenBefore(object args) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Open); + if (args is RewardDisplayData displayModel) + { + data = displayModel; + if (data.isPlayAudio) + { + AudioManager.Instance.PlayDynamicEffect(data.audioName); + } + } + + if (data.isNeedFly) + { + if (!data.isSingle) + { + ShowText(); + } + + ui.com_Coins.cont_coin.selectedIndex = !data.isSingle ? com_Coins.Coin_more : com_Coins.Coin_single; + ui.com_Coins.position = data.rewardSingleData.startPosition; + + var val = 0f; + ui.fx_enter.position = ui.com_Coins.position; + foreach (var o in ui.com_Coins.GetChildren()) + { + var item = (com_Coin)o; + if (!item.visible) + { + continue; + } + + item.visible = false; + TextureHelper.GetItemIcon(data.rewardSingleData.id, spr => { item.icon.texture = spr; }); + var def = val; + DOVirtual.DelayedCall(0.05f, () => + { + item.visible = true; + + var tar = new Vector2(Random.Range(0, item.parent.size.x / (!data.isSingle ? 1 : 2)), + Random.Range(0, item.parent.size.y / (!data.isSingle ? 1 : 2))); + item.size = Vector2.zero; + item.position = new Vector2(item.parent.width / 2, item.parent.height / 2); + if (data.isSingle) + { + toSizeAniTime = 0.2f; + } + + item.TweenMove(tar, toSizeAniTime + def); + DOTween.To(() => item.size, (e) => item.size = e, Vector2.one, toSizeAniTime + def); + item.icon.visible = true; + DOVirtual.DelayedCall(toSizeAniTime + def, () => + { + var moveTime = moveAniTime; + DOTween.To(() => item.icon.alpha, (e) => { item.icon.alpha = e; }, 0.6f, moveTime); + item.TweenMove(data.rewardSingleData.endPosition - (Vector2)item.parent.position + + item.parent.size / 2, moveTime); + DOVirtual.DelayedCall(moveTime, () => + { + item.icon.visible = false; + completeSum++; + var fxPlayData = FxPlayData.Get(Fx_Type.fx_ui_jinbi_click, 1, + item.LocalToRoot(Vector2.zero, GRoot.inst)); + uiCtrlDispatcher.Dispatch(UICtrlMsg.PlayUIFX, fxPlayData); + + if (!isUpdate) + { + isUpdate = true; + } + + if (completeSum >= ui.com_Coins.numChildren) + { + DOVirtual.DelayedCall(0.2f, CtrlCloseUI); + } + }); + }); + }); + val += 0.02f; + } + } + } + + private void ShowText() + { + var sb = new StringBuilder(); + sb.Append("+"); + sb.Append(data.rewardSingleData.id is 101 or 102 or 111 + ? (data.rewardSingleData.GetTotalValue()).ToString("N") + : data.rewardSingleData.GetTotalValue().ToString("N0")); + + ui.text_Add.SetText(sb.ToString()); + ui.text_Add.position = data.rewardSingleData.startPosition; + ui.fx_addSum.Play(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs.meta new file mode 100644 index 0000000..d99afcc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d2d9fbd8465dce4a9a3d6b7c76a1b5f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs new file mode 100644 index 0000000..6ef3d7d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs @@ -0,0 +1,57 @@ +namespace ScrewsMaster +{ + public class CurrencyRewardUICtrl : BaseUICtrl + { + private CurrencyRewardUI ui; + private CurrencyRewardModel model; + + private uint openUIMsg = UICtrlMsg.RewardAniUI_Open; + private uint closeUIMsg = UICtrlMsg.RewardAniUI_Close; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + ui = new CurrencyRewardUI(this); + ui.Open(args); + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs.meta new file mode 100644 index 0000000..e57a21c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/CurrencyReward/CurrencyRewardUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 53e075cd42f5230469d7b5a03e008a68 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/DailyTask.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/DailyTask.meta new file mode 100644 index 0000000..a494adb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/DailyTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 428c3222e38348c499d511fd1ab2ab45 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd.meta new file mode 100644 index 0000000..6fda861 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3e6c7df2af55497c964e70e37ced4f9a +timeCreated: 1675931929 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs new file mode 100644 index 0000000..f9792be --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class FXWndCtrl : BaseCtrl + { + public static FXWndCtrl Instance { get; private set; } + + private FXWndModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs.meta new file mode 100644 index 0000000..48ab242 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b80fe266a6824af6ac721d23dea8b29c +timeCreated: 1675931929 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs new file mode 100644 index 0000000..e1a65b7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class FXWndModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs.meta new file mode 100644 index 0000000..12fcc84 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 448f05696d5d484a8fde8dad54e29a82 +timeCreated: 1675931929 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs new file mode 100644 index 0000000..71b8594 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs @@ -0,0 +1,171 @@ +namespace ScrewsMaster +{ + using System; + using FairyGUI; + using DG.Tweening; + using Spine.Unity; + using UnityEngine; + + public class FXWndUI : BaseUI + { + private FXWndUICtrl ctrl; + private FXWndModel model; + private FGUI.G502_Fx.com_FX ui; + + private Transform parTrf; + + public FXWndUI(FXWndUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.FXWndUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G502_Fx"; + uiInfo.assetName = "com_FX"; + uiInfo.layerType = UILayerType.Animation; + } + + public void PlayFx(FxPlayData fxPlayData) + { + FxPlayData data = fxPlayData; + GameObject arg = null; + Transform trf = null; + Action recFx = null; + if (data.isParticleSystem) + { + ParticleSystem system = FXManager.Instance.GetFx(data.fxType); + system.Play(); + arg = system.gameObject; + trf = system.transform; + recFx = delegate { FXManager.Instance.RecFx(data.fxType, system); }; + } + else + { + SkeletonAnimation system = FXManager.Instance.GetFx(data.fxType); + trf = system.transform; + arg = system.gameObject; + recFx = delegate { FXManager.Instance.RecFx(data.fxType, system); }; + } + + trf.SetParent(parTrf); + arg.SetLayer("UI"); + Action cb = SetSortingOrder(arg); + data.endEvent += (e) => cb?.Invoke(); + + Vector3 startPot = GameHelper.FguiPotToUnityTrfLocalPot(data.startPot); + + trf.localPosition = startPot; + trf.localScale = Vector3.one * data.size; + trf.localEulerAngles = Vector3.zero; + fxPlayData.startEvent?.Invoke(arg); + + DOVirtual.DelayedCall(data.duration, () => + { + data.endEvent?.Invoke(arg); + + recFx?.Invoke(); + FxPlayData.Release(data); + }); + } + + private Action SetSortingOrder(GameObject obj) + { + Action action = null; + Renderer[] renders = obj.GetComponentsInChildren(); + foreach (Renderer render in renders) + { + if (render != null) + { + render.sortingOrder += 300; + action += () => { render.sortingOrder -= 300; }; + } + } + + return action; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G502_Fx.com_FX; + } + + protected override void OnOpenBefore(object args) + { + parTrf = ui.displayObject.cachedTransform; + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + #endregion + } + + public class FxPlayData + { + private static ObjectPool _Pool = new ObjectPool(); + + public static FxPlayData Get(Fx_Type fx_Type, float _duration, Vector2 _pot) + { + FxPlayData data = _Pool.Get(); + if (_pot == Vector2.zero) + { + data.startPot = GRoot.inst.size / 2; + } + else + { + data.startPot = _pot; + } + + if (_duration == 0) + { + data.duration = 1; + } + else + { + data.duration = _duration; + } + + data.fxType = fx_Type; + return data; + } + + public static void Release(FxPlayData data) + { + data.duration = 0; + data.startEvent = null; + data.endEvent = null; + data.isParticleSystem = true; + data.startPot = Vector2.zero; + _Pool.Release(data); + } + + public float duration; + + public Fx_Type fxType; + + public bool isParticleSystem = true; + + public Vector2 startPot; + + public Action startEvent; + + public Action endEvent; + + public int size = 100; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs.meta new file mode 100644 index 0000000..91abdaa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 186b49b6b475454bbadfdf90b0b7d4b2 +timeCreated: 1675931929 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs new file mode 100644 index 0000000..8c771a5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs @@ -0,0 +1,83 @@ +namespace ScrewsMaster +{ + public class FXWndUICtrl : BaseUICtrl + { + private FXWndUI ui; + private FXWndModel model; + + private uint openUIMsg = UICtrlMsg.FXWndUI_Open; + private uint closeUIMsg = UICtrlMsg.FXWndUI_Close; + + private bool isOpen = false; + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null || ui.isClose) + { + ui = new FXWndUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + uiCtrlDispatcher.AddListener(UICtrlMsg.PlayUIFX, PlayFx); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + uiCtrlDispatcher.RemoveListener(UICtrlMsg.PlayUIFX, PlayFx); + } + + private void PlayFx(object obj) + { + if (!isOpen) + { + OpenUI(); + } + + FxPlayData fxType = (FxPlayData)obj; + ui.PlayFx(fxType); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs.meta new file mode 100644 index 0000000..febe382 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FXWnd/FXWndUICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 67c44481d43948a78f1cf27e8df6f06a +timeCreated: 1675931929 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward.meta new file mode 100644 index 0000000..f14770f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5902d91a945346c7b5579b701a08db45 +timeCreated: 1729664385 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs new file mode 100644 index 0000000..18d19e0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class FirstRewardCtrl : BaseCtrl + { + public static FirstRewardCtrl Instance { get; private set; } + + private FirstRewardModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.FirstRewardModel) as FirstRewardModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs.meta new file mode 100644 index 0000000..13ff26a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b10e7a12f76b4e9c9389034c3bcee2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs new file mode 100644 index 0000000..b1e98f7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class FirstRewardModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs.meta new file mode 100644 index 0000000..b682acf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 139c7e95f3a174f9f996d4aaf7465f2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs new file mode 100644 index 0000000..170e33b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs @@ -0,0 +1,150 @@ +using System; +using UnityEngine; +using FGUI.G002_main; +using Spine.Unity; +using DG.Tweening; + +namespace ScrewsMaster +{ + public class FirstRewardUI : BaseUI + { + private FirstRewardUICtrl ctrl; + private FirstRewardModel model; + private FGUI.G002_main.com_firstreward ui; + private Action closeCallback; + private Action open_sign; + private bool is_get = false; + public FirstRewardUI(FirstRewardUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.FirstRewardUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G002_main"; + uiInfo.assetName = "com_firstreward"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + model = ModuleManager.Instance.GetModel(ModelConst.FirstRewardModel) as FirstRewardModel; + } + + protected override void OnClose() + { + closeCallback(); + //open_sign(); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G002_main.com_firstreward; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.money.y += Screen.safeArea.y; + } + InitView(); + } + + protected override void OnOpen(object args) + { + //open_sign = (System.Action)args; + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + + ui.text_num.text = GameHelper.GetPaymentTypeVO().payicon + ConfigSystem.GetConfig().InitialNum; + var sk = FXManager.Instance.SetFx(ui.spine_parent, Fx_Type.fx_first_reward, ref closeCallback); + sk.state.SetAnimation(0, "newbie_reward_an01", false); + sk.state.Complete += (a) => + { + sk.state.SetAnimation(0, "newbie_reward_an02", true); + ui.btn_getreward.SetClick(() => + { + ui.btn_getreward.visible = false; + sk.state.SetAnimation(0, "newbie_reward_an03", false); + sk.state.Complete += (a) => + { + ui.state.selectedIndex = com_firstreward.State_page; + + + + }; + }); + + }; + ui.btn_get.SetClick(GetReward); + ui.btn_close.SetClick(GetReward); + ui.money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102()); + + var lightSk = FXManager.Instance.SetFx(ui.bg_parent, Fx_Type.fx_win_light, ref closeCallback); + lightSk.state.SetAnimation(0, "animation", true); + } + private void GetReward() + { + if (is_get) return; + is_get = true; + + // GameHelper.GetRewardOnly(ConfigSystem.GetConfig().InitialNum, RewardOrigin.OpenReward, ui.btn_get, ui.end_point, isSuccess => + // { + // // PreferencesMgr.Instance.IsShowOpenReward = false; + // // PreferencesMgr.Instance.OpenRewardCount++; + + // }); + var start = GameHelper.GetUICenterPosition(ui.img_cash); + var end = GameHelper.GetUICenterPosition(ui.money.GetChild("number_text")); + + float cash = (float)ConfigSystem.GetConfig().InitialNum; + reward_data temp = new reward_data() { start = start, end = end, change = cash, type = 111 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddMoney(cash); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + Debug.Log(cash); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.Get102(), 1, + value => { ui.money.GetChild("number_text").text = GameHelper.Get102Str((decimal)value); }); + PlayerPrefs.SetInt("FirstReward", 1); + + }); + DOVirtual.DelayedCall(2.5f, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FirstRewardUI_Close); + }); + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs.meta new file mode 100644 index 0000000..b266deb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 10ed78edd8a4f471d8230502a75e04f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs new file mode 100644 index 0000000..eb3eeb6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class FirstRewardUICtrl : BaseUICtrl + { + private FirstRewardUI ui; + private FirstRewardModel model; + + private uint openUIMsg = UICtrlMsg.FirstRewardUI_Open; + private uint closeUIMsg = UICtrlMsg.FirstRewardUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.FirstRewardModel) as FirstRewardModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new FirstRewardUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs.meta new file mode 100644 index 0000000..818c694 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/FirstReward/FirstRewardUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 943432b7abe7d41eb9b023894a945fcf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome.meta new file mode 100644 index 0000000..a37cc32 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7a25bdf932ba72d4c97c6ec5baf10251 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs new file mode 100644 index 0000000..7b08b9d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs @@ -0,0 +1,25 @@ + + +namespace ScrewsMaster +{ + public class GameHomeCtrl : BaseCtrl + { + public static GameHomeCtrl Instance { get; private set; } + + private GameHomeModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.GameHomeModel) as GameHomeModel; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs.meta new file mode 100644 index 0000000..9508af5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1a4f944f53b1184b8abd1ca2a328f37 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs new file mode 100644 index 0000000..ac4de6b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class GameHomeModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs.meta new file mode 100644 index 0000000..8d0e574 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 482684869b96f8941af63ec69ed864c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs new file mode 100644 index 0000000..6ad1fa8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs @@ -0,0 +1,610 @@ + +using System; +using System.Collections.Generic; +using System.Linq; +using DG.Tweening; +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; +using FGUI.G003_play; +using FGUI.G018_GameHome; +using btn_noads = FGUI.A000_common.btn_noads; +using Random = UnityEngine.Random; +using Unity.VisualScripting; +using Newtonsoft.Json; +using System.IO; +using Spine.Unity; + +namespace ScrewsMaster +{ + public class GameHomeUI : BaseUI + { + private GameHomeUICtrl ctrl; + private GameHomeModel model; + private GameHome ui; + + private MakeupTaskData _makeupTaskData; + private Makeup _makeup; + + private bool is_first_login_go_to_h5; + private btn_noads _btnNoAds; + + public GameHomeUI(GameHomeUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.GameHomeUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G018_GameHome"; + uiInfo.assetName = "GameHome"; + uiInfo.layerType = UILayerType.Normal; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.GameHomeModel) as GameHomeModel; + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= UpData; + } + + protected override void OnBind() + { + ui = baseUI as GameHome; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + { + ui.TopBox.y += Screen.safeArea.y; + } + + HallManager.Instance.UpdateSecondEvent += UpData; + + AudioManager.Instance.PlayBGM(AudioConst.MainBg); + InitView(); + UpData(); + + var loginModel = GameHelper.GetLoginModel(); + is_first_login_go_to_h5 = CommonHelper.GetBoolByChance(ConfigSystem.GetConfig().loginhallrate / 100f); + is_first_login_go_to_h5 = false; + GameHelper.is_first_login = loginModel.new_player; + + if (GameHelper.IsGiftSwitch() && !loginModel.new_player && is_first_login_go_to_h5) + { + GotoH5(); + } + else if (GameHelper.IsGiftSwitch() && loginModel.new_player) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.FirstRewardUI_Open); + loginModel.new_player = false; + } + RefreshSaveingPot(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + GameDispatcher.Instance.AddListener(GameMsg.BattleLevelUp, OnBattleLevelUp); + GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr); + GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, SetMoneyCurr); + GameDispatcher.Instance.AddListener(GameMsg.BuyPack, OnBuyPack); + GameDispatcher.Instance.AddListener(GameMsg.BuyRemoveAdPack, OnBuyPack); + + HallManager.Instance.UpdateSecondEvent += TimeEvent; + HallManager.Instance.UpdateEvent += UpdateEvent; + } + protected override void RemoveListener() + { + PreferencesDispatcher.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + GameDispatcher.Instance.RemoveListener(GameMsg.BattleLevelUp, OnBattleLevelUp); + GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr); + GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, SetMoneyCurr); + GameDispatcher.Instance.RemoveListener(GameMsg.BuyPack, OnBuyPack); + GameDispatcher.Instance.RemoveListener(GameMsg.BuyRemoveAdPack, OnBuyPack); + + HallManager.Instance.UpdateSecondEvent -= TimeEvent; + HallManager.Instance.UpdateEvent -= UpdateEvent; + } + + + private void OnBuyPack(object args) + { + SetBtnAds(); + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + // ShowScrews.Instance.gameMode = GameHome.Mode_simple; + ui.switchgift.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0; + + var showH5Btn = false; + if (GameHelper.IsGiftSwitch()) + { + showH5Btn = true; + } + else + { + showH5Btn = GameHelper.GetCommonModel().WVswitch != 0; + // if (showH5Btn) + // { + // var uiBtnH5 = ui.btn_h5 as btn_hall; + // if (uiBtnH5 != null) uiBtnH5.t0.Stop(); + // } + } + /// ui.btn_h5.visible = showH5Btn; + + + //ui.NoAdsBtn.visible = GameHelper.IsGiftSwitch(); + // ui.broadcast.visible = false; + + _btnNoAds = ui.NoAdsBtn as btn_noads; + InitButtons(); + + SetAvatar(); + SetTopCurr(); + SetMoneyCurr(); + SetBtnTask(); + SetBtnAds(); + + + int level = GameHelper.GetLevel(); + ui.PlayBtn.text = "Level " + level; + if (GameHelper.IsGiftSwitch()) + { + ui.Mode.selectedIndex = 1; + ui.PlayBtn.text = "Level " + level; + } + else + { + ui.Mode.selectedIndex = ShowScrews.Instance.gameMode; + } + checkThreeGift(); + } + + void SetTopCurr(object a = null) + { + ui.gold.number_text.text = GameHelper.GetGoldNumber().ToString(); + } + + private List _paidcoinsList; + void UpData() + { + _paidcoinsList ??= ConfigSystem.GetConfig().dataList; + + int time = SaveData.GetSaveobject()._goldtime0; + if (time + _paidcoinsList[0].receive_CD < GameHelper.GetNowTime()) + { + ui.gold.state.selectedIndex = 2; + ui.gold.red.visible = true; + } + else + { + ui.gold.state.selectedIndex = 1; + } + + + ui.BattleBtn.red.visible = SaveData.getRed(); + ui.SignInBtn.red.visible = CheckSignState(); + } + + private bool CheckSignState() + { + var signDays = PreferencesMgr.Instance.SignState.Count; + if (signDays == 0) + { + return true; + } + + var isToday = false; + if (signDays > 0) + isToday = GameHelper.InToday(PreferencesMgr.Instance.SignState[signDays - 1], 0, true); + + return !isToday; + } + + private int _timeCount = 11; + private com_broadcast_text1 _textUI; + void TimeEvent() + { + + if (!GameHelper.IsGiftSwitch()) return; + + RefreshSaveingPot(); + checkThreeGift(); + // _timeCount++; + // if (_timeCount > 10) + // { + // ui.broadcast.visible = false; + // } + // var exBrPoolModel = ConfigSystem.GetConfig(); + // var configNameList = exBrPoolModel.config_name_list; + // var configMoneyList = exBrPoolModel.config_money_list; + // var nameIndex = Random.Range(0, configNameList.Count); + // var moneyIndex = Random.Range(0, configMoneyList.Count); + + // if (_timeCount > 30) + // { + // _timeCount = 0; + // ui.broadcast.visible = true; + + // _textUI ??= ui.broadcast.GetChild("broad_cast_text") as com_broadcast_text1; + // if (_textUI != null) + // { + // _textUI.cast_text.text = String.Format(_textUI.show_text.text, + // configNameList[nameIndex], + // configMoneyList[moneyIndex], + // DateTimeManager.Instance.GetCurrDateTime()); + // _textUI.t0.Play(() => { ui.broadcast.visible = false; }); + // } + // } + + } + + public void SetMoneyCurr(object a = null) + { + ui.money.visible = GameHelper.IsGiftSwitch(); + ui.money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102()); + + if (GameHelper.IsGiftSwitch()) + { + if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0) + { + return; + } + + _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + _makeup = ConfigSystem.GetConfig().GetData(_makeupTaskData.tableId); + } + } + + private void OnChangeAvatar(ChangeValue obj) + { + SetAvatar(); + } + + private void SetAvatar() + { + GameHelper.SetSelfAvatar((ui.btn_menu.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader); + } + + private void OnBattleLevelUp(object obj = null) + { + SetBtnTask(); + } + + void SetBtnTask() + { + ui.BattleBtn.number_text.text = "Lv." + GameHelper.GetBattleLv(); + if (GameHelper.GetBattleLv() >= ConfigSystem.GetConfig().dataList.Count) + { + ui.BattleBtn.progress.width = 135; + } + else + { + ui.BattleBtn.progress.width = + Mathf.Min((float)GameHelper.GetGameExp() / ConfigSystem.GetConfig().dataList[GameHelper.GetBattleLv()].Eliminating_quantity, 1) * 135; + } + + } + + void SetBtnAds() + { + if (!SaveData.GetSaveobject().is_get_removead && !SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Play(-1, 0, null); + } + else if (SaveData.GetSaveobject().is_get_removead && SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Stop(); + _btnNoAds.visible = false; + } + else if (SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Stop(); + _btnNoAds.t1.Play(); + _btnNoAds.img_pack.visible = false; + _btnNoAds.img_ad.visible = true; + + } + else if (SaveData.GetSaveobject().is_get_removead) + { + _btnNoAds.t0.Stop(); + _btnNoAds.t1.Play(); + _btnNoAds.img_pack.visible = true; + _btnNoAds.img_ad.visible = false; + } + + } + + void GotoH5(object obj = null) + { + + uiCtrlDispatcher.Dispatch(UICtrlMsg.H5UI_Open); + GameHelper.showGameUI = false; + } + + private void InitButtons() + { + ui.LeftBtn.SetClick(OnClickLeftBtn); + ui.RightBtn.SetClick(OnClickRightBtn); + ui.LuckySpinBtn.SetClick(OnLuckySpinBtn); + ui.btn_menu.SetClick(OnClickMenuBtn); + ui.btn_setting.SetClick(OnClickSetBtn); + ui.SignInBtn.SetClick(OnClickSignInBtn); + ui.BattleBtn.SetClick(OnClickBattleBtn); + ui.PlayBtn.SetClick(OnClickPlayBtn); + ui.RankBtn.SetClick(OnClickRankBtn); + ui.btn_restore.SetClick(() => + { + PurchasingManager.Instance.IosRestore((success, message) => + { + // Debug.Log("[barry] restore success message: " + message); + if (success) + { + // Debug.Log("[barry] restore success: " + success); + GameHelper.ShowTips("Restore Purchases Success!"); + SaveData.GetSaveobject().is_get_removead = success; + SaveData.GetSaveobject().is_get_battlepass = success; + SaveData.GetSaveobject().have_slot = success; + GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack); + GameDispatcher.Instance.Dispatch(GameMsg.BuyPack); + GameHelper.SetPayBox1(true); + GameHelper.SetPayBox2(true); + SaveData.saveDataFunc(); + } + else + { + // Debug.Log("[barry] restore failed: " + success); + GameHelper.ShowTips("There are no recoverable transactions"); + } + }); + }); + // ui.money.btn_cashout.SetClickDownEffect(0.8f, 1); + ui.money.GetChild("btn_cashout").SetClick(() => + { + if (!GameHelper.IsGiftSwitch()) return; + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData); + }); + // ui.btn_h5.SetClick(() => + // { + // GotoH5(); + // }); + ui.gold.btn_buygold.SetClick(() => + { + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); + GameHelper.showGameUI = false; + }); + + ui.NoAdsBtn.SetClick(() => + { + if (!SaveData.GetSaveobject().is_get_packreward && !SaveData.GetSaveobject().is_get_removead) + { + if (_btnNoAds.img_ad.visible) + { + PackRewardData param = new PackRewardData(); + param.isAutoPop = false; + param.isNeedScroll = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open); + } + + } + else if (SaveData.GetSaveobject().is_get_packreward) + { + PackRewardData param = new PackRewardData(); + param.isAutoPop = false; + param.isNeedScroll = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open); + } + GameHelper.showGameUI = false; + }); + ui.btn_three_day.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open); + }); + ui.btn_failpack.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.ResurgenceUI_Open); + }); + if (ConfigSystem.GetConfig().PiggyBankSwitch == 0 || !GameHelper.IsGiftSwitch()) + { + ui.btn_saveingpot.visible = false; + } + ui.btn_saveingpot.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); }); + + var ske_pot = FXManager.Instance.SetFx((ui.btn_saveingpot as btn_saveingpot).ani_parent, Fx_Type.fx_savepot_icon, ref closeCallback); + ske_pot.state.SetAnimation(0, "animation", true); + if (ConfigSystem.GetConfig().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch()) + { + Debug.Log(PlayerPrefs.GetInt("pot_day", 0)); + Debug.Log(DateTime.Now.Day); + if (PlayerPrefs.GetInt("pot_day", 0) == 0) + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); + PlayerPrefs.SetInt("pot_day", DateTime.Now.Day); + } + else + { + if (DateTime.Now.Day != PlayerPrefs.GetInt("pot_day", 0)) + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); + PlayerPrefs.SetInt("pot_day", DateTime.Now.Day); + } + } + Debug.Log(PlayerPrefs.GetInt("pot_day", 0)); + } + } + private void checkThreeGift(object obj = null) + { + // if (SaveData.GetSaveobject().is_get_ThreeDaysGift) { + var isToday = GameHelper.InToday(SaveData.GetSaveobject().last_got_three_gift_time, 0, true); + int three_gift_got_index = SaveData.GetSaveobject().three_gift_got_index; + if (three_gift_got_index > (int)rewardState.day3) + { + ui.btn_three_day.visible = false; + } + else if (!isToday) + { + ui.btn_three_day.GetChild("red").visible = true; + } + else + { + ui.btn_three_day.GetChild("red").visible = false; + } + } + void UpdateEvent() + { + long t = SaveData.GetSaveobject().failed_pack_time; + + if (SaveData.GetSaveobject().failed_pack_time > GameHelper.GetNowTime()) + { + ui.btn_failpack.visible = true; + long time_ = t * 1000 - GameHelper.getNowTimeByMillisecond(); + DateTime oldDate = new DateTime(1970, 1, 1); + oldDate = oldDate.AddMilliseconds(time_); + ui.btn_failpack.GetChild("lab_time").text = DateTimeManager.Instance.DateTimeToFFFString(oldDate); + } + else + { + ui.btn_failpack.visible = false; + } + + + } + private void RefreshSaveingPot(object isShow = null) + { + (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash); + } + + private Action closeCallback; + private void OnClickLeftBtn() + { + ShowScrews.Instance.gameMode = GameHome.Mode_simple; + ui.Mode.selectedIndex = ShowScrews.Instance.gameMode; + + // int level = GameHelper.GetLevel(); + // ui.PlayBtn.text = "Level " + level; + } + + private void OnClickRightBtn() + { + ShowScrews.Instance.gameMode = GameHome.Mode_difficult; + ui.Mode.selectedIndex = ShowScrews.Instance.gameMode; + } + + private void OnLuckySpinBtn() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrizeWheelUI_Open); + } + + private void OnClickMenuBtn() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open); + } + + private void OnClickSetBtn() + { + int mode = 0; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open, mode); + } + + private void OnClickSignInBtn() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SignInUI_Open); + } + + private void OnClickBattleBtn() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Open); + } + + private void OnClickPlayBtn() + { + CtrlCloseUI(); + // var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? ShowScrews.Instance.GetCurMaxLevel() : GameHelper.GetLevel();; + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + + } + + private void OnClickRankBtn() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RankUI_Open); + } + + // private void OpenFailPack() + // { + // var grade = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); + + + + + // Debug.Log(grade); + + // var index = grade - 1; + + // var levelDataModel = ConfigSystem.GetConfig(); + // var _levelDataList = levelDataModel.dataList; + // index = index < _levelDataList.Count ? index : _levelDataList.Count - 1; + // var levelData = _levelDataList[index]; + // var screwCount = levelData.screwCount; + // var _screwCountForLevel = screwCount; + // var _pendingScrewCount = _screwCountForLevel; + + + + + // var _screwBoxCount = _pendingScrewCount / 3; + // var _curScrewBoxCount = _screwBoxCount; + + // _screwBoxCount = _pendingScrewCount / 3; + + // var progress = (float)(_screwBoxCount - _curScrewBoxCount) / _screwBoxCount; + // Debug.Log(_screwBoxCount); + // Debug.Log(_curScrewBoxCount); + // Debug.Log(progress); + // progress = Mathf.Clamp(progress, 0, 1); + // var endNum = Mathf.RoundToInt(progress * 100); + // Debug.Log(endNum); + // //gameProgressText.text = $"{endNum}%"; + // } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs.meta new file mode 100644 index 0000000..7cb8457 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 166e639996315324196342e45dcc28c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs new file mode 100644 index 0000000..b1b2f65 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs @@ -0,0 +1,73 @@ + + +namespace ScrewsMaster +{ + public class GameHomeUICtrl : BaseUICtrl + { + private GameHomeUI ui; + private GameHomeModel model; + + private uint openUIMsg = UICtrlMsg.GameHomeUI_Open; + private uint closeUIMsg = UICtrlMsg.GameHomeUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.GameHomeModel) as GameHomeModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new GameHomeUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs.meta new file mode 100644 index 0000000..74c384f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameHome/GameHomeUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aff246ed6b496f34db4e209de6989707 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin.meta new file mode 100644 index 0000000..b7025ef --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 47eb9299e68a4344a901834dacddbf41 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs new file mode 100644 index 0000000..39d8a6a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class GameLoginCtrl : BaseCtrl + { + public static GameLoginCtrl Instance { get; private set; } + + private GameLoginModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs.meta new file mode 100644 index 0000000..5fa78ab --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5089dfe313b4fc64c92cf29d58609006 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs new file mode 100644 index 0000000..2dfdbb0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class GameLoginModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs.meta new file mode 100644 index 0000000..0b76419 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b46e3ae2b0959c14ba484e8ead2dc449 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs new file mode 100644 index 0000000..319aa5f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs @@ -0,0 +1,160 @@ +using SGame; +using UnityEngine; + +namespace ScrewsMaster +{ + using DG.Tweening; + using FGUI.A000_common; + using FGUI.G018_GameHome; + using Spine.Unity; + using System; + + public class GameLoginUI : BaseUI + { + private GameLoginUICtrl ctrl; + private GameLoginModel model; + private FGUI.G001_login.com_login ui; + private Action closeCallback; + + public GameLoginUI(GameLoginUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.GameLoginUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G001_login"; + uiInfo.assetName = "com_login"; + uiInfo.layerType = UILayerType.Normal; + } + + protected override void OnInit() + { + } + + protected override void OnClose() + { + netFbloadBindLogin?.Kill(); + CommonHelper.FadeOut(ui); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenBgUI_Close); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G001_login.com_login; + } + + protected override void OnOpenBefore(object args) + { + // var login = FXManager.Instance.SetFx(ui.Title_parent, Fx_Type.fx_title, ref closeCallback); + // login.state.SetAnimation(0, "animation", true); + // + // var rabbit = FXManager.Instance.SetFx(ui.logo_parent, Fx_Type.fx_rabbit, ref closeCallback); + // rabbit.state.SetAnimation(0, "animation", true); + + InitView(); + + var reqData = new RespLoginFunnelData + { + type = "enterButtonShow", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + protected override void AddListener() + { + } + + protected override void RemoveListener() + { + } + + private void InitView() + { + ui.btn_login.SetClick(OnClickBtn, true); + + App.HideLoadingUI(); + ((com_loadingBlacklist)ui.com_blklist1).text_privacy.SetClick(OnClickPrivacy); + ((com_loadingBlacklist)ui.com_blklist1).text_privacy.onClickLink.Add((content) => + { + switch (content.data) + { + case "link_href": + OnClickTerms(); + break; + case "link_href1": + OnClickPrivacy(); + break; + } + }); + + + // Action closeCallback = null; + // var meteor = FXManager.Instance.SetFx(ui.pla1, Fx_Type.meteor, ref closeCallback); + // meteor.state.SetAnimation(0, "liziguang1", true); + + //var login = FXManager.Instance.SetFx(ui.pla, Fx_Type.fx_login, ref closeCallback); + //login.state.SetAnimation(0, "animation", true); + + // var lantern = FXManager.Instance.SetFx(ui.pla1, Fx_Type.lantern, ref closeCallback); + // lantern.state.SetAnimation(0, "deng", true); + + + + } + + private Tween netFbloadBindLogin; + + public void OnClickBtn() + { + UIManagerRegister.AdaptSafeArea(); + var reqData = new RespLoginFunnelData + { + type = "enterButtonClick", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + + CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_Start); + CtrlCloseUI(); + + ShowScrews.Instance.maskImg.gameObject.SetActive(false); + + // ShowScrews.Instance.InitLogic(); + + ShowScrews.Instance.InitAllLeveData(); + ShowScrews.Instance.InitItemBar(); + ShowScrews.Instance.InitSaveData(); + int roomrate = GameHelper.GetCommonModel().roomrate; + if (UnityEngine.Random.Range(1, 100) < roomrate) + { + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Open); + } + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Open); + Debug.Log("dakaidatingjiemian"); + } + + private void OnClickPrivacy() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open); + } + + private void OnClickTerms() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, true); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs.meta new file mode 100644 index 0000000..d149303 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6e6a93efe97683744a3a2ae64d433320 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs new file mode 100644 index 0000000..81a653c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs @@ -0,0 +1,60 @@ +namespace ScrewsMaster +{ + public class GameLoginUICtrl : BaseUICtrl + { + private GameLoginUI ui; + private GameLoginModel model; + + private uint openUIMsg = UICtrlMsg.GameLoginUI_Open; + private uint closeUIMsg = UICtrlMsg.GameLoginUI_Close; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new GameLoginUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs.meta new file mode 100644 index 0000000..43efefe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GameLogin/GameLoginUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 760e515e19f493145b362fec54a155fa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward.meta new file mode 100644 index 0000000..3885a1b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3d4c902793000af4d9f134414c660f48 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs new file mode 100644 index 0000000..81a9fbd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class GetTaskRewardCtrl : BaseCtrl + { + public static GetTaskRewardCtrl Instance { get; private set; } + + private GetTaskRewardModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.GetTaskRewardModel) as GetTaskRewardModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs.meta new file mode 100644 index 0000000..b865a5f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 87ee97ded9a294cd39e08c80f08dd72d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs new file mode 100644 index 0000000..1448bf3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class GetTaskRewardModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs.meta new file mode 100644 index 0000000..3fada8b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4ecff54cb7d2546328d5e92f9f89abad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs new file mode 100644 index 0000000..54ecb80 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs @@ -0,0 +1,374 @@ +using UnityEngine; +using FairyGUI; +using Spine.Unity; +using System; +using System.Linq; +using DG.Tweening; +using FGUI.A000_common; +using FGUI.G008_reward; +using FGUI.G009_video; +using Newtonsoft.Json; +using Roy.Datas; +using Random = UnityEngine.Random; + +namespace ScrewsMaster +{ + public class GetTaskRewardUI : BaseUI + { + private GetTaskRewardUICtrl ctrl; + private GetTaskRewardModel model; + private FGUI.G009_video.com_gettaskreward ui; + + private float _rewardNum; + private float _rateNum; + private SettlementData _settlementData; + private bool _isTaskReward; + private bool _isGiftSwitch; + private string _broadTextTemplate; + + public GetTaskRewardUI(GetTaskRewardUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.GetTaskRewardUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G009_video"; + uiInfo.assetName = "com_gettaskreward"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.GetTaskRewardModel) as GetTaskRewardModel; + } + + protected override void OnClose() + { + + HallManager.Instance.UpdateSecondEvent -= TimeEvent; + closeCallback?.Invoke(); + if (_settlementData != null && _settlementData.is_h5_reward) + { + WebviewManager.Instance.ShowH5View(true); + GameDispatcher.Instance.Dispatch(GameMsg.resetH5progress); + } + + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G009_video.com_gettaskreward; + } + + private Action closeCallback; + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.gold.y += Screen.safeArea.y; + ui.top_money.y += Screen.safeArea.y; + ui.tips_bg.y += Screen.safeArea.y; + ui.tips_text.y += Screen.safeArea.y; + } + + _rateNum = 2; + if (args is SettlementData settlementData) + { + _settlementData = settlementData; + _rewardNum = _settlementData.cash_number; + _rateNum = _settlementData.rate; + + if (_settlementData.is_h5_reward) + { + WebviewManager.Instance.ShowH5View(false); + } + + _isTaskReward = false; + + } + else if (args is int num) + { + _rewardNum = num; + _isTaskReward = true; + + } + + _isGiftSwitch = GameHelper.IsGiftSwitch(); + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + ui.switchgift.selectedIndex = _isGiftSwitch && !_isTaskReward ? 1 : 0; + + if (_isGiftSwitch) + { + InitCashView(); + } + ui.top_money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102()); + ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString(); + + //添加特效动画 + // var sk = FXManager.Instance.SetFx(baseUI.GetChild("bg_parent") as GGraph, Fx_Type.fx_win, ref closeCallback); + // sk.state.SetAnimation(0, "out", true); + + var sk = FXManager.Instance.SetFx(baseUI.GetChild("bg_parent") as GGraph, Fx_Type.fx_win_light, ref closeCallback); + sk.state.SetAnimation(0, "animation", true); + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_adclaim.GetChild("img_saveingpot") as GImage).visible = true; + + // int number = (int)args; + ui.money_text.text = _rewardNum.ToString(); + ui.btn_adclaim.text = $"Claim X{_rateNum}"; + + // ((btn_tabad)ui.btn_adclaim).color.selectedIndex = 1; + + ui.btn_claim.SetClick(() => + { + SetButtonsTouchable(false); + DistributeReward(false); + }); + + ui.btn_adclaim.SetClick(() => + { + SetButtonsTouchable(false); + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + DistributeReward(true); + } + else + { + SetButtonsTouchable(true); + } + }); + + }); + + } + + /// + /// 禁用界面上所有按钮点击 + /// + /// + private void SetButtonsTouchable(bool enable) + { + ui.btn_adclaim.touchable = enable; + ui.btn_claim.touchable = enable; + ui.com_cash.touchable = enable; + ui.top_money.GetChild("btn_cashout").touchable = enable; + } + + private MakeupTaskData _makeupTaskData; + private com_success_cash _com_cash; + private float _progressBarWidth = -1; + private void InitCashView() + { + var exBrPoolModel = ConfigSystem.GetConfig(); + var configNameList = exBrPoolModel.config_name_list; + var configMoneyList = exBrPoolModel.config_money_list; + var nameIndex = + Random.Range(0, configNameList.Count); + var moneyIndex = + Random.Range(0, configMoneyList.Count); + + _com_cash = ui.com_cash as com_success_cash; + if (_com_cash == null) return; + + if (string.IsNullOrEmpty(_broadTextTemplate)) + { + _broadTextTemplate = _com_cash.broad.cast_text.text; + } + + if (_progressBarWidth < 0) + { + _progressBarWidth = _com_cash.progress.width; + } + + _com_cash.broad.cast_text.text = string.Format( + _broadTextTemplate, + configNameList[nameIndex], + configMoneyList[moneyIndex]); + + + _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + var vo = ConfigSystem.GetConfig().GetData(_makeupTaskData.tableId); + // Debug.Log(JsonConvert.SerializeObject(vo)); + + string cashTextStr; + float progressWidth; + string progressTextStr; + + if (GameHelper.GetLevel() <= vo.levels_need) + { + cashTextStr = "Withdrawals can be made through level " + vo.levels_need; + progressWidth = _progressBarWidth * (GameHelper.GetLevel() - 1) / vo.levels_need; + progressTextStr = (GameHelper.GetLevel() - 1) + "/" + vo.levels_need; + } + else if ((float)GameHelper.Get102() < vo.item_need) + { + cashTextStr = "Collect " + GameHelper.Get102Str(vo.item_need) + " to cash out"; + progressWidth = _progressBarWidth * ((float)GameHelper.Get102() / vo.item_need); + progressTextStr = GameHelper.Get102Str(GameHelper.Get102()) + "/" + + GameHelper.Get102Str(vo.item_need); + } + else if ((float)PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need) + { + cashTextStr = "Cumulataive " + (vo.task_need / 60) + @" minutes in ""Game"" to cash out"; + progressWidth = _progressBarWidth * ((float)PreferencesMgr.Instance.MakeupTaskH5Time / vo.task_need); + progressTextStr = Math.Round(((float)(PreferencesMgr.Instance.MakeupTaskH5Time / 60)), 2) + "/" + + (vo.task_need / 60); + } + else if (_makeupTaskData.videoCount < vo.ad_need) + { + cashTextStr = "Watch " + vo.ad_need + " Reward Ads to cash out"; + progressWidth = _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need); + progressTextStr = _makeupTaskData.videoCount + "/" + vo.ad_need; + } + else + { + cashTextStr = "Watch " + vo.ad_need + " Reward Ads to cash out"; + progressWidth = _makeupTaskData.videoCount > vo.ad_need + ? _progressBarWidth + : _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need); + progressTextStr = _makeupTaskData.videoCount > vo.ad_need + ? vo.ad_need + "/" + vo.ad_need + : _makeupTaskData.videoCount + "/" + vo.ad_need; + } + + _com_cash.cash_text.text = cashTextStr; + _com_cash.progress.width = progressWidth; + _com_cash.progress_text.text = progressTextStr; + + _com_cash.btn_cash.SetClick(OnClickCash); + + HallManager.Instance.UpdateSecondEvent += TimeEvent; + } + + private int _timeCount = 0; + void TimeEvent() + { + _timeCount++; + + if (_timeCount > 3) + { + _timeCount = 0; + _com_cash.broad.t0.Play(() => + { + var exBrPoolModel = ConfigSystem.GetConfig(); + var name_index = Random.Range(0, exBrPoolModel.config_name_list.Count); + var money_index = Random.Range(0, exBrPoolModel.config_money_list.Count); + // System.DateTime oldtime = System.DateTime.Now.AddSeconds(-Random.Range(1 * 3600, 2 * 3600)); + // var str = "Congratulations, [color=#e3a13a]" + + // exBrPoolModel.config_name_list[name_index] + + // "[/color] withdrew [color=#83c93c]" + + // exBrPoolModel.config_money_list[money_index] + + // "[/color]dollars"; + var str = string.Format( + _broadTextTemplate, + exBrPoolModel.config_name_list[name_index], + exBrPoolModel.config_money_list[money_index]); + _com_cash.broad.cast_text.text = str; + _com_cash.broad.t1.Play(); + }); + } + + } + /// + /// 点击CashOUt按钮 + /// + private void OnClickCash() + { + SetButtonsTouchable(false); + DistributeReward(false); + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData); + } + + private void DistributeReward(bool isMultiRewardEnabled) + { + if (_isTaskReward) + { + GameDispatcher.Instance.Dispatch(GameMsg.GetTaskReward, isMultiRewardEnabled); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close); + return; + } + + var start = GameHelper.GetUICenterPosition(ui.btn_adclaim); + var end = GameHelper.GetUICenterPosition(_isGiftSwitch + ? ui.top_money.GetChild("number_text") + : ui.gold.GetChild("number_text")); + + var startNum = 0f; + var endNum = 0f; + GObject numText; + + reward_data temp = new reward_data() { start = start, end = end}; + var changeNum = _rewardNum * (isMultiRewardEnabled ? _rateNum : 1); + temp.change = changeNum; + temp.type = 111; + GameHelper.AddMoney(temp.change); + + startNum = (float)GameHelper.Get102() - changeNum; + endNum = (float)GameHelper.Get102(); + numText = ui.top_money.GetChild("number_text") as GTextField; + + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(startNum, endNum, 1f, + value => + { + var str = _isGiftSwitch ? GameHelper.Get102Str((decimal)value) : ((int)value).ToString(); + if (numText != null) + numText.text = str; + }); + + DOVirtual.DelayedCall(1.5f, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Close); + if (!isMultiRewardEnabled) + { + GameHelper.AddInterAdNumber(); + } + }); + + }); + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs.meta new file mode 100644 index 0000000..95ed3ca --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 68d77870ef81f4afaabf33d1c0470495 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs new file mode 100644 index 0000000..91b8534 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class GetTaskRewardUICtrl : BaseUICtrl + { + private GetTaskRewardUI ui; + private GetTaskRewardModel model; + + private uint openUIMsg = UICtrlMsg.GetTaskRewardUI_Open; + private uint closeUIMsg = UICtrlMsg.GetTaskRewardUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.GetTaskRewardModel) as GetTaskRewardModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new GetTaskRewardUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs.meta new file mode 100644 index 0000000..00b20f4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/GetTaskReward/GetTaskRewardUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 89cba9dc9d404422291d75698d7fcb60 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5.meta new file mode 100644 index 0000000..c3c881e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 941cf5d1593450941bb4acff81c032c0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs new file mode 100644 index 0000000..a1c0adb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs @@ -0,0 +1,27 @@ + + +namespace ScrewsMaster + +{ + public class H5Ctrl : BaseCtrl + { + private H5Model model; + public static H5Ctrl Instance { get; private set; } + + #region 生命周期 + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs.meta new file mode 100644 index 0000000..1845bed --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Ctrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 82ac50f0742e4d4093a6da34f4a2576a +timeCreated: 1671094546 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs new file mode 100644 index 0000000..2d1a34f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs @@ -0,0 +1,29 @@ + + +namespace ScrewsMaster +{ + public class H5Model : BaseModel + { + public decimal show102; + + + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + + #endregion + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs.meta new file mode 100644 index 0000000..e5d65d0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5Model.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 52d962fd3bd24ab19816d15a8cb11f9e +timeCreated: 1671094546 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs new file mode 100644 index 0000000..c468c7a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs @@ -0,0 +1,584 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using DG.Tweening; +using FGUI.G004_webview; +using Roy.Datas; +using UnityEngine; +using Random = UnityEngine.Random; + +namespace ScrewsMaster +{ + public class H5UI : BaseUI + { + private Tween bubbleMoveTween; + + private Action closeCallBack; + private CountDownKit countDownKit; + private H5UICtrl ctrl; + + private int currentTabIndex; + + private int flyClickCount; + + private int flyNeedClickCount; + + private int iconClickCount; + + private decimal iconTime; + + + private bool isAddFinger; + + + private bool isCurrentTaskFinish; + + + private bool isCurrentTimeTask; + + + private bool isLoadFinish; + + + private bool isScrolling; + + + private bool isTimeOut = false; + + private decimal makeupTaskH5NeedTime; + private H5Model model; + + private readonly List movePointList = new(); + + private long openTime; + + + private decimal scrollOutTime; + public com_webview ui; + + private decimal updateTime; + + private bool _flySwitch; + private bool _propSwitch; + + private bool isFlyShow = false; + + + public H5UI(H5UICtrl ctrl) : base(ctrl) + { + uiName = UIConst.H5UI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G004_webview"; + uiInfo.assetName = "com_webview"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + uiInfo.uiMaskCustomColor = Color.white; + uiInfo.isTickUpdate = true; + } + + public override void OnUpdate() + { + if (iconTime < ConfigSystem.GetConfig().ThroughRewardCD) + { + iconTime += (decimal)Time.deltaTime; + UpdateIcon(); + } + + updateTime += (decimal)Time.deltaTime; + if (makeupTaskData_saveing.status == SaveingPotTaskStatus.None) + { + if (PreferencesMgr.Instance.ExchangeAccount != null) + { + makeupTaskData_saveing.H5Time += (float)updateTime; + } + } + if (makeupTaskH5NeedTime > 0 && PreferencesMgr.Instance.MakeupTaskH5Time < makeupTaskH5NeedTime) + if (updateTime >= 1) + { + PreferencesMgr.Instance.MakeupTaskH5Time += updateTime; + updateTime = 0; + } + + } + + private void InitData() + { + _flySwitch = GameHelper.GetCommonModel().flyswitch == 1; + _propSwitch = GameHelper.GetCommonModel().propswitch == 1; + WebviewManager.Instance.ShowFlyBtn(true); + + // HallManager.Instance.SetInH5(true); + model.show102 = GameHelper.Get102(); + flyNeedClickCount = Random.Range(ConfigSystem.GetConfig().flyAdTime[0], + ConfigSystem.GetConfig().flyAdTime[1] + 1); + + if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + if (taskData != null) + { + var cardRedeemModel = ConfigSystem.GetConfig(); + var makeupVo = cardRedeemModel.dataList.FirstOrDefault(redeem => redeem.id == taskData.tableId); + if (makeupVo != null) makeupTaskH5NeedTime = makeupVo.task_need; + } + } + +#if UNITY_EDITOR + isLoadFinish = true; +#endif + } + + private void InitView() + { + Set101(); + // WebThroughUtil.WebThroughCreate(H5WebThroughType.OnlineH5, ui.btn_icon); + ui.btn_close.SetClick(() => + { + // uiCtrlDispatcher.Dispatch(UICtrlMsg.MainUI_Open); + // uiCtrlDispatcher.Dispatch(UICtrlMsg.BackgroundUI_Open); + // uiCtrlDispatcher.Dispatch(UICtrlMsg.CurrencyUI_Open); + //CreatSheepCard.instance.SetCameraVisible(true); + // CtrlDispatcher.Instance.Dispatch(CtrlMsg.Webview_StateChange, WebUIType.Game); + uiCtrlDispatcher.Dispatch(UICtrlMsg.H5UI_Close); + + + if (GameHelper.is_first_login) + { + GameDispatcher.Instance.Dispatch(GameMsg.RefreshGame); + } + + // CtrlCloseUI(); + }); + + ui.com_fly.visible = false; + ui.btn_icon.visible = false; + + InitIcon(); + + CheckShowFly(); + ui.com_fly.SetClick(OnClickFlyCash); + DOVirtual.Float(0, (float)GameHelper.Get102(), 1, + value => { ui.com_top.text_num.text = GameHelper.Get102Str((decimal)value); }); + SetMakeup(); + + ui.btn_out.visible = GameHelper.IsGiftSwitch(); + ui.com_top.ContentBox.visible = GameHelper.IsGiftSwitch(); + } + + private void InitIcon() + { + ui.btn_icon.cont_state.selectedIndex = btn_icon.State_none; + ui.btn_icon.fx_ready.Stop(); + ui.btn_icon.SetClick(OnClickIcon); + ui.btn_icon.visible = false; + UpdateIcon(); + } + private SaveingPotClass makeupTaskData_saveing; + void OnRefreshMakeupData(object obj) + { + SetMakeup(); + } + + private void UpdateIcon() + { + + if (!_propSwitch) + { + return; + } + float amount = (float)iconTime / ConfigSystem.GetConfig().ThroughRewardCD; + + + WebviewManager.Instance.SetIconProgress(amount); + + if (!_propSwitch) + { + return; + } + + // if (_propSwitch && !ui.btn_icon.visible) + // { + // ui.btn_icon.visible = true; + // } + ui.btn_icon.pb_time.fillAmount = (float)iconTime / ConfigSystem.GetConfig().ThroughRewardCD; + if (iconTime >= ConfigSystem.GetConfig().ThroughRewardCD) + { + if (!ui.btn_icon.fx_ready.playing) ui.btn_icon.fx_ready.Play(); + + ui.btn_icon.cont_state.selectedIndex = btn_icon.State_ready; + } + else + { + ui.btn_icon.fx_ready.Stop(); + } + } + + private void OnClickIcon() + { + // if (UIManager.Instance.IsExistUI(UIConst.DialogRewardUI)) return; + + // WebThroughUtil.WebThroughClick(H5WebThroughType.OnlineH5, ui.btn_icon); + if (iconTime < ConfigSystem.GetConfig().ThroughRewardCD) return; + + // var rewardData = new RewardData(); + + // var rewardType = GameHelper.GetCommonModel().ThroughRewardType; + float[] cash_array = GameHelper.GetRewardValue(2); + // var temp = new { is_success = true, cash_number = cash_array[0], rate = cash_array[1], is_level_success = false, is_h5_reward = true }; + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp); + + var temp = new SettlementData { cash_number = cash_array[0], rate = cash_array[1], is_h5_reward = true }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, temp); + + // decimal rewardValue = GameHelper.GetCommonModel().ThroughReward.RandomInt(); + + // var rewardSingleData = new RewardSingleData(rewardType, (decimal)cash_array[0], RewardOrigin.H5Icon) + // { + // startPosition = new Vector2(GameHelper.GetUICenterPosition(ui.btn_icon).x - 250, GameHelper.GetUICenterPosition(ui.btn_icon).y - 50),//GameHelper.GetUICenterPosition(ui.btn_icon), + // endPosition = GameHelper.GetUICenterPosition(ui.com_top.icon_101) + // }; + // rewardData.AddReward(rewardSingleData); + // rewardData.AddCompleted(isSuccess => + // { + ui.btn_icon.cont_state.selectedIndex = btn_icon.State_none; + // iconTime = 0; + // SetMakeup(); + // }); + // rewardData.condition = RewardCondition.AD; + // rewardData.displayType = + // RewardDisplayType.Dialog | RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + + // GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + } + + + public void Set101(decimal cash = -1) + { + if (cash < 0) cash = GameHelper.Get102(); + + var cashNumt = GameHelper.Get101String(cash); + ui.com_top.text_num.text = $"{cashNumt}"; + } + + public void OnLoadFinish() + { + isLoadFinish = true; + } + + private void SetMakeup() + { + var comBox = ui.com_top; + comBox.text_num.text = $"{GameHelper.Get101String()}"; + if (!GameHelper.IsGiftSwitch()) return; + if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0) return; + + var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + var vo = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == makeupTaskData.tableId); + if (vo == null) return; + + var leftCash = (double)Math.Max(vo.item_need - GameHelper.Get102(), 0); + comBox.text_more.SetVar("money", $"{GameHelper.Get102Str((decimal)leftCash)}").FlushVars(); + // comBox.text_more.text = GameHelper.Get101Str((decimal)leftCash); + comBox.pb_num.max = vo.item_need; + comBox.pb_num.TweenValue(vo.item_need - leftCash, 0.1f); + comBox.pb_num.GetChild("title").text = + $"{GameHelper.Get102Str((decimal)(vo.item_need - leftCash))}/{GameHelper.Get102Str((decimal)comBox.pb_num.max)}"; + + ui.btn_out.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData); + }); + } + + public void SetCash(string str102 = null) + { + if (str102 == null) + str102 = GameHelper.Get102() == -1 + ? GameHelper.GetCommonModel().InitialNum.ToString("N") + : GameHelper.Get102().ToString("N"); + + + ui.com_top.text_num.text = "$" + str102; + } + + #region 生命周期 + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.H5Model) as H5Model; + } + + protected override void OnClose() + { + GameHelper.showGameUI = true; + + WebviewManager.Instance.setInH5View(false); + WebviewManager.Instance.ShowH5View(false); + // WebThroughUtil.WebThroughDisable(H5WebThroughType.OnlineH5, ui.btn_icon); + StopFly(); + countDownKit?.OnDestroy(); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close); + CommonHelper.FadeOut(ui); + } + public Camera orthoCamera; + + + protected override void OnBind() + { + ui = baseUI as com_webview; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + { + ui.TopBox.height += Screen.safeArea.y; + // ui.TopBox.y += Screen.safeArea.y; + } + + WebviewManager.Instance.setInH5View(true); + WebviewManager.Instance.ShowH5View(true); + makeupTaskData_saveing = SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1]; + InitData(); + InitView(); + } + + protected override void OnOpen(object args) + { + openTime = GameHelper.GetNowTime(); + CommonHelper.FadeIn(ui); + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + HallManager.Instance.AddChangeGiftSwitch(InitView); + GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData); + GameDispatcher.Instance.AddListener(GameMsg.resetH5progress, ResetTime); + + } + + protected override void RemoveListener() + { + HallManager.Instance.RemoveChangeGiftSwitch(InitView); + GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData); + GameDispatcher.Instance.RemoveListener(GameMsg.resetH5progress, ResetTime); + + } + + #endregion + + void ResetTime(object a = null) + { + iconTime = 0; + SetMakeup(); + } + + #region 飞行美元 + + private void CheckShowFly() + { + var nowTime = GameHelper.GetNowTime(); + var leftTime = (int)(PreferencesMgr.Instance.AdCashFlyShowTime - nowTime); + + ui.com_fly.visible = false; + + if (!_flySwitch) return; + + // ui.com_fly.visible = leftTime <= 0; + if (leftTime > 0) + { + WebviewManager.Instance.ShowFlyBtn(false); + isFlyShow = false; + + StopFlyCountdown(); + StartFlyCountdown(leftTime); + } + else + { + if (!isFlyShow) WebviewManager.Instance.ShowFlyBtn(true); + isFlyShow = true; + + StartFly(); + StopFlyCountdown(); + } + } + + private void StartFly() + { + StopFly(); + SetFlyPoints(); + + var bubbleGo = ui.com_fly.displayObject.gameObject; + bubbleMoveTween = bubbleGo.transform + .DOLocalPath(movePointList.ToArray(), 20) + .SetEase(Ease.Linear) + .OnComplete(StartFly) + .SetAutoKill(true) + .OnUpdate(() => + { + // WebThroughUtil.WebThroughCreate(H5WebThroughType.Fly, ui.com_fly); + }); + } + + private void SetFlyPoints() + { + movePointList.Clear(); + + var w = ui.fly_area.width; + var h = ui.fly_area.height - 173; + var startPos = ui.fly_area.position; + w -= ui.com_fly.width; + + var pos1 = new Vector3(startPos.x + w - CommonHelper.RandomRange(30, 100), startPos.y); + ui.com_fly.position = pos1; + movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos1)); + + var pos2 = new Vector3(startPos.x, startPos.y + CommonHelper.RandomRange((int)(h / 4f), (int)(h / 2 - h / 8))); + movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos2)); + + var pos3 = new Vector3(startPos.x + w, startPos.y + h / 2 + CommonHelper.RandomRange((int)(h / 8), (int)(h / 4))); + movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos3)); + + var pos4 = new Vector3(startPos.x + CommonHelper.RandomRange(0, 20), + startPos.y + h + CommonHelper.RandomRange(-20, 20)); + movePointList.Add(GameHelper.FguiPotToUnityTrfLocalPot(pos4)); + } + + private void StopFly() + { + bubbleMoveTween?.Kill(); + } + + private void StartFlyCountdown(int leftTime) + { + countDownKit = new CountDownKit(); + countDownKit.SetTime(leftTime) + .SetCountDownType(CountDownType.Second) + .SetCompletedEvent(CheckShowFly); + + countDownKit.Start(); + } + + private void StopFlyCountdown() + { + countDownKit?.Stop(); + countDownKit = null; + } + + private void CheckShowFlyVideo(int times) + { + var configTimes = ConfigSystem.GetConfig().flytimes; + + Debug.Log($"CheckShowFlyVideo times=== {times} configTimes=== {configTimes}"); + if (times != 0 && configTimes != 0 && times % configTimes == 0) + { + PlayerPrefs.SetInt($"ShowFlyVideo", 0); + GameHelper.AddInterAdNumber(); + } + } + + private long _lastClickFlyCash; + private void OnClickFlyCash() + { + // var nowTime = GameHelper.GetNowTime(); + // if (_lastClickFlyCash == nowTime) + // { + // return; + // } + // _lastClickFlyCash = nowTime; + // + // var times = PlayerPrefs.GetInt($"ShowFlyVideo", 0); + // int localTimes = times + 1; + // + // PlayerPrefs.SetInt($"ShowFlyVideo", localTimes); + // CheckShowFlyVideo(localTimes); + + PreferencesMgr.Instance.AdCashFlyShowTime = + GameHelper.GetNowTime() + ConfigSystem.GetConfig().flyCD; + var rewardData = new RewardData(); + + // WebThroughUtil.WebThroughClick(H5WebThroughType.Fly, ui.com_fly); + + var singleValue = + (decimal)Math.Round( + Random.Range(ConfigSystem.GetConfig().flyReward[0], + ConfigSystem.GetConfig().flyReward[1]), 2); + decimal rewardValue; + + + if (flyClickCount >= flyNeedClickCount) + { + flyClickCount = 0; + rewardValue = singleValue; + GameHelper.ShowVideoAd("reward_fly", isCompleted => + { + if (isCompleted) + { + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + } + }); + } + else + { + rewardValue = singleValue; + } + + var rewardSingleData = new RewardSingleData(102, rewardValue, RewardOrigin.H5Fly101) + { + startPosition = GameHelper.GetUICenterPosition(ui.com_fly), + endPosition = GameHelper.GetUICenterPosition(ui.com_top.icon_101) + }; + + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + rewardData.AddCompleted(isSuccess => + { + if (isSuccess) flyClickCount++; + + SetMakeup(); + }); + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + CheckShowFly(); + } + + #endregion + + public void ClickBtn(string name) + { + // // Debug.Log("[UNITY] Click btn: " + name); + // FGUIHelper.PlayClickSound(); + if (name == "flyBtn") + { + OnClickFlyCash(); + NetworkKit.BuriedPoint(BuriedPointEvent.Hall_behavior, BuriedPointEvent.collect_fly_number, 1); + //NetworkKit.BuriedPoint(BuriedPointEvent.Hall_behavior,BuriedPointEvent.collect_fly_people,1); + } + else if (name == "rewardBtn") + { + OnClickIcon(); + + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs.meta new file mode 100644 index 0000000..8ce00e3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eeb18ea73919462d93e684426ccc498e +timeCreated: 1671094546 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs new file mode 100644 index 0000000..eeb053b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs @@ -0,0 +1,132 @@ +namespace ScrewsMaster +{ + public class H5UICtrl : BaseUICtrl + { + private readonly uint closeUIMsg ; + private H5Model model; + + private readonly uint openUIMsg ; + private H5UI ui; + + private void OnUpdateDollar(object obj) + { + if (obj == null) return; + var changeValue = (decimal)obj; + if (model != null) + { + model.show102 += changeValue; + ui?.SetCash(model.show102.ToString("N")); + } + } + + private void OnUpdateCompletedDollar(object obj = null) + { + if (PreferencesMgr.Instance.IsShowRewardFly101) return; + var value = GameHelper.Get102(); + if (model != null) model.show102 = value; + + ui?.SetCash(); + } + + private void OnDollarChange(object data) + { + } + + private void OnWebviewFinish(object obj) + { + ui?.OnLoadFinish(); + } + + private void OnMakeupSuccess(object obj) + { + } + + private void OnWebview_PageState(object args) + { + } + + #region 生命周期 + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.H5Model) as H5Model; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new H5UI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui is { isClose: false }) ui.Close(); + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + + gameDispatcher.AddListener(GameMsg.H5ViewClickBtn, OnH5ClickBtn); + GameDispatcher.Instance.AddListener(GameMsg.Update101, OnUpdateDollar); + GameDispatcher.Instance.AddListener(GameMsg.Update102Completed, OnUpdateCompletedDollar); + gameDispatcher.AddListener(GameMsg.MakeupSuccess, OnMakeupSuccess); + + CtrlDispatcher.Instance.AddListener(CtrlMsg.Webview_PageState, OnWebview_PageState); + CtrlDispatcher.Instance.AddListener(CtrlMsg.Webview_PageFinish, OnWebviewFinish); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + gameDispatcher.RemoveListener(GameMsg.H5ViewClickBtn, OnH5ClickBtn); + GameDispatcher.Instance.RemoveListener(GameMsg.Update101, OnUpdateDollar); + GameDispatcher.Instance.RemoveListener(GameMsg.Update102Completed, OnUpdateCompletedDollar); + gameDispatcher.RemoveListener(GameMsg.MakeupSuccess, OnMakeupSuccess); + + CtrlDispatcher.Instance.RemoveListener(CtrlMsg.Webview_PageState, OnWebview_PageState); + CtrlDispatcher.Instance.RemoveListener(CtrlMsg.Webview_PageFinish, OnWebviewFinish); + } + + + void OnH5ClickBtn(object arg) + { + ui?.ClickBtn((string)arg); + } + + protected override void AddServerListener() + { + } + + protected override void RemoveServerListener() + { + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs.meta new file mode 100644 index 0000000..3db0fc2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/H5/H5UICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 57c18de9257c442c8f2d51357abf14ad +timeCreated: 1671094546 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast.meta new file mode 100644 index 0000000..52c4ef5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e761018b93dff6245acace69ce894df4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs new file mode 100644 index 0000000..b501e25 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class JoastCtrl : BaseCtrl + { + public static JoastCtrl Instance { get; private set; } + + private JoastModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs.meta new file mode 100644 index 0000000..1886ae0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2da16488a9975f34c9be68a519b0e275 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs new file mode 100644 index 0000000..a3ef6dd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs @@ -0,0 +1,52 @@ +namespace ScrewsMaster +{ + using System.Collections.Generic; + + public class JoastData + { + public string ValueStr; + + public float ShowTipsAniTime = 0.2f; + + public float TipsStayAniTime = 1f; + + public float TipsVanishTime = 1.5f; + + public int TipsVanishMoveDic = 100; + + private static List tempTipsData; + + public static JoastData GetTips(string val) + { + return GetTips(val, 0.2f, 1, 1.5f, 100); + } + + public static JoastData GetTips(string val, float ShowTipsAniTime, float TipsStayAniTime, float TipsVanishTime, + int TipsVanishMoveDic) + { + if (tempTipsData == default) + { + tempTipsData = new List + { + new(), + new() + }; + } + + if (tempTipsData.Count <= 0) return default; + var tips = tempTipsData[0]; + tempTipsData.RemoveAt(0); + tips.ValueStr = val; + tips.ShowTipsAniTime = ShowTipsAniTime; + tips.TipsStayAniTime = TipsStayAniTime; + tips.TipsVanishTime = TipsVanishTime; + tips.TipsVanishMoveDic = TipsVanishMoveDic; + return tips; + } + + public void Rest() + { + tempTipsData.Add(this); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs.meta new file mode 100644 index 0000000..60927dd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c708319d9da2ca499b4c7189c3667d2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs new file mode 100644 index 0000000..302bb35 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs @@ -0,0 +1,32 @@ +namespace ScrewsMaster +{ + using System.Collections.Generic; + + public class JoastModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + private Queue tipsDatas = new Queue(); + + public void AddTips(JoastData joastData) + { + if (tipsDatas.Count > 0) + { + return; + } + + tipsDatas.Enqueue(joastData); + } + + public JoastData GetTips() + { + return tipsDatas.Count > 0 ? tipsDatas.Dequeue() : null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs.meta new file mode 100644 index 0000000..afc0108 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69e2e426856b30041aa4b7e325a0cf10 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs new file mode 100644 index 0000000..e2fe6cc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs @@ -0,0 +1,80 @@ +namespace ScrewsMaster +{ + using DG.Tweening; + using UnityEngine; + using FGUI.SC001_Tips; + + public class JoastUI : BaseUI + { + private JoastUICtrl ctrl; + private JoastModel model; + private FGUI.SC001_Tips.com_Tips ui; + + public JoastUI(JoastUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.JoastUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SC001_Tips"; + uiInfo.assetName = "com_Tips"; + uiInfo.layerType = UILayerType.Tips; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as com_Tips; + } + + protected override void OnOpenBefore(object args) + { + JoastData joastData = args as JoastData; + if (joastData != default) + { + ui.wnd_tips.text_tips.text = joastData.ValueStr; + ui.wnd_tips.scale = Vector2.zero; + float show = joastData.ShowTipsAniTime; + float stay = joastData.TipsStayAniTime; + float vanis = joastData.TipsVanishTime; + int dic = joastData.TipsVanishMoveDic; + + ui.wnd_tips.TweenScale(Vector2.one, joastData.ShowTipsAniTime); + DOVirtual.DelayedCall(show + stay, () => + { + ui.wnd_tips.TweenMoveY(ui.wnd_tips.y - dic, vanis).OnComplete((e) => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.SCTipsUI_Close, joastData); + }); + DG.Tweening.DOTween.To(() => ui.wnd_tips.alpha, (e) => ui.wnd_tips.alpha = e, 0, vanis); + }); + } + else + { + CtrlCloseUI(); + } + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs.meta new file mode 100644 index 0000000..8875551 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d5005af43da49e742865966690c41bdb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs new file mode 100644 index 0000000..5d56c20 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs @@ -0,0 +1,95 @@ +namespace ScrewsMaster +{ + public class JoastUICtrl : BaseUICtrl + { + private JoastUI ui; + private JoastModel model; + + private uint openUIMsg = UICtrlMsg.SCTipsUI_Open; + private uint closeUIMsg = UICtrlMsg.SCTipsUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.JoastModel) as JoastModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new JoastUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, AddTips); + uiCtrlDispatcher.AddListener(closeUIMsg, CheckNext); + } + + private void CheckNext(object obj) + { + JoastData joastData = obj as JoastData; + joastData.Rest(); + CloseUI(); + ShowTips(); + } + + private void ShowTips() + { + if (ui != null) return; + JoastData joastData = model.GetTips(); + if (joastData != default) + { + OpenUI(joastData); + } + } + + private void AddTips(object obj) + { + JoastData joastData = obj as JoastData; + if (joastData == default) return; + model.AddTips(joastData); + ShowTips(); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, AddTips); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CheckNext); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs.meta new file mode 100644 index 0000000..a4c30d3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Joast/JoastUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c303cafc3cceab45a532640f306b2bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess.meta new file mode 100644 index 0000000..5a0b184 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dbdbd9b75e6442f4db4775807b75fdd6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs new file mode 100644 index 0000000..431f76a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class LevelSuccessCtrl : BaseCtrl + { + public static LevelSuccessCtrl Instance { get; private set; } + + private LevelSuccessModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.LevelSuccessModel) as LevelSuccessModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs.meta new file mode 100644 index 0000000..594536c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bf30effd1c1cf4ee7965a785597ebb5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs new file mode 100644 index 0000000..c02eacd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class LevelSuccessModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs.meta new file mode 100644 index 0000000..06380ce --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a82cc7895b244916bf94ffb2678b292 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs new file mode 100644 index 0000000..581be39 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs @@ -0,0 +1,539 @@ +using System; +using System.Linq; +using UnityEngine; +using FairyGUI; +using DG.Tweening; +using FGUI.A000_common; +using FGUI.G018_GameHome; +using Newtonsoft.Json; +using Roy.Datas; +using Spine.Unity; +using SGame; +using Random = UnityEngine.Random; + +namespace ScrewsMaster +{ + public class LevelSuccessUI : BaseUI + { + private LevelSuccessUICtrl ctrl; + private LevelSuccessModel model; + private FGUI.G008_reward.com_lvsuccess ui; + private bool is_success; + private bool is_level_success; + private bool is_h5_reward; + + private SettlementData _data; + private string _broadTextTemplate; + + public LevelSuccessUI(LevelSuccessUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.LevelSuccessUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_lvsuccess"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + model = ModuleManager.Instance.GetModel(ModelConst.LevelSuccessModel) as LevelSuccessModel; + } + + protected override void OnClose() + { + closeCallback?.Invoke(); + if (is_level_success && !GameHelper.is_first_login) + { + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, is_success); + } + GameHelper.SetCloseResult(false); + if (is_h5_reward) + { + // WebviewManager.Instance.ShowH5View(true); + GameDispatcher.Instance.Dispatch(GameMsg.resetH5progress); + } + + + } + private Action closeCallback; + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_lvsuccess; + } + + protected override void OnOpenBefore(object args) + { + if (args is SettlementData settlementData) + { + is_success = settlementData.is_success; + _cashNumber = settlementData.cash_number; + is_level_success = settlementData.is_level_success; + is_h5_reward = settlementData.is_h5_reward; + _rate = is_success ? (int)settlementData.rate : 1; + } + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.gold.y += Screen.safeArea.y; + ui.top_money.y += Screen.safeArea.y; + ui.tips_bg.y += Screen.safeArea.y; + ui.tips_text.y += Screen.safeArea.y; + } + _isGiftSwitch = GameHelper.IsGiftSwitch(); + + ui.switchgift.selectedIndex = _isGiftSwitch ? ui._Switchgift_b : ui._Switchgift_a; + ui.state.selectedIndex = is_success ? ui._State_win : ui._State_lose; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_adclaim.GetChild("img_saveingpot") as GImage).visible = true; + PlayDynamicEffect(); + + // (ui.btn_adclaim as btn_tabad).color.selectedIndex = 1; + + ui.top_money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102()); + + if (is_success) + { + ui.btn_adclaim.GetChild("title").text = "Claim X" + _rate; + var sk = FXManager.Instance.SetFx(ui.bg_parent, Fx_Type.fx_win, ref closeCallback); + sk.state.SetAnimation(0, "out", false); + + sk = FXManager.Instance.SetFx(ui.bg_parent, Fx_Type.fx_win_light, ref closeCallback); + sk.state.SetAnimation(0, "animation", true); + + } + else + { + ui.bg_parent.y += 200; + var sk = FXManager.Instance.SetFx(ui.bg_parent, Fx_Type.fx_lose, ref closeCallback); + sk.state.SetAnimation(0, "animation", false); + GameHelper.SetCloseResult(true); + } + GameHelper.PlayGameTimeEvent(3, () => + { + GameHelper.RequestGameConfig(); + }); + InitView(); + ShowScrews.Instance.TrackGameCompletion(is_success); + } + + #region 新版代码(测试) + + private float _cashNumber; + private int _rate; + private bool _isGiftSwitch; + private MakeupTaskData _makeupTaskData; + + private const int RewardNum = 40; + + private com_success_cash _com_cash; + private float _progressBarWidth = -1; + + //初始化页面逻辑 + private void InitView() + { + + _com_cash = ui.com_cash as com_success_cash; + SetButtonsTouchable(true); + InitButtons(); + + if (_isGiftSwitch) + { + InitCashView(); + } + else + { + ui.money_text.text = RewardNum.ToString(); + ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString(); + } + } + + + private void InitCashView() + { + ui.money_text.text = is_success + ? GameHelper.GetPaymentTypeVO().payicon + _cashNumber + : GameHelper.Get102Str(GameHelper.Get102()); + + var exBrPoolModel = ConfigSystem.GetConfig(); + var configNameList = exBrPoolModel.config_name_list; + var configMoneyList = exBrPoolModel.config_money_list; + var nameIndex = + Random.Range(0, configNameList.Count); + var moneyIndex = + Random.Range(0, configMoneyList.Count); + + + if (_com_cash == null) return; + + if (string.IsNullOrEmpty(_broadTextTemplate)) + { + _broadTextTemplate = _com_cash.broad.cast_text.text; + } + + if (_progressBarWidth < 0) + { + _progressBarWidth = _com_cash.progress.width; + } + + _com_cash.broad.cast_text.text = string.Format( + _broadTextTemplate, + configNameList[nameIndex], + configMoneyList[moneyIndex]); + + + _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + var vo = ConfigSystem.GetConfig().GetData(_makeupTaskData.tableId); + Debug.Log(JsonConvert.SerializeObject(vo)); + + string cashTextStr; + var progressWidth = 676f; + string progressTextStr; + + if (GameHelper.GetLevel() <= vo.levels_need) + { + cashTextStr = "Withdrawals can be made through level " + vo.levels_need; + progressWidth = _progressBarWidth * (GameHelper.GetLevel() - 1) / vo.levels_need; + progressTextStr = (GameHelper.GetLevel() - 1) + "/" + vo.levels_need; + } + else if ((float)GameHelper.Get102() < vo.item_need) + { + cashTextStr = "Collect " + GameHelper.Get102Str(vo.item_need) + " to cash out"; + progressWidth = _progressBarWidth * ((float)GameHelper.Get102() / vo.item_need); + progressTextStr = GameHelper.Get102Str(GameHelper.Get102()) + "/" + + GameHelper.Get102Str(vo.item_need); + } + else if ((float)PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need) + { + cashTextStr = "Cumulataive " + (vo.task_need / 60) + @" minutes in ""Game"" to cash out"; + progressWidth = _progressBarWidth * ((float)PreferencesMgr.Instance.MakeupTaskH5Time / vo.task_need); + progressTextStr = Math.Round(((float)(PreferencesMgr.Instance.MakeupTaskH5Time / 60)), 2) + "/" + + (vo.task_need / 60); + } + else if (_makeupTaskData.videoCount < vo.ad_need) + { + cashTextStr = "Watch " + vo.ad_need + " Reward Ads to cash out"; + progressWidth = _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need); + progressTextStr = _makeupTaskData.videoCount + "/" + vo.ad_need; + } + else + { + cashTextStr = "Watch " + vo.ad_need + " Reward Ads to cash out"; + progressWidth = _makeupTaskData.videoCount > vo.ad_need + ? _progressBarWidth + : _progressBarWidth * ((float)_makeupTaskData.videoCount / vo.ad_need); + progressTextStr = _makeupTaskData.videoCount > vo.ad_need + ? vo.ad_need + "/" + vo.ad_need + : _makeupTaskData.videoCount + "/" + vo.ad_need; + } + + _com_cash.cash_text.text = cashTextStr; + _com_cash.progress.width = progressWidth; + _com_cash.progress_text.text = progressTextStr; + + HallManager.Instance.UpdateSecondEvent += TimeEvent; + } + + + /// + /// 初始化按钮点击事件 + /// + private void InitButtons() + { + ui.btn_restart.SetClick(OnClickRestart); + ui.btn_adclaim.SetClick(OnClickAdClaim); + ui.btn_claim.SetClick(OnClickClaim); + ui.top_money.GetChild("btn_cashout").SetClick(OnClickCashout); + + if (_com_cash == null) return; + _com_cash.btn_cash.SetClick(OnClickCash); + } + + /// + /// 禁用界面上所有按钮点击 + /// + /// + private void SetButtonsTouchable(bool enable) + { + ui.btn_restart.touchable = enable; + ui.btn_adclaim.touchable = enable; + ui.btn_claim.touchable = enable; + ui.com_cash.touchable = enable; + ui.top_money.GetChild("btn_cashout").touchable = enable; + } + + /// + /// 点击重新开始 + /// + private void OnClickRestart() + { + if (!GameHelper.GetCloseResult()) return; + SetButtonsTouchable(false); + GameHelper.AddInterAdNumber(); + // if (!is_success) ShowScrews.instance.OnRestartBtnClick(); //GameHelper.setLevelstate(3); + + ClosePanelLogic(0); + } + + private void OnClickCashout() + { + if (!GameHelper.GetCloseResult()) return; + SetButtonsTouchable(false); + _com_cash.btn_cash.FireClick(false, true); + } + + /// + /// 点击广告Claim + /// + private void OnClickAdClaim() + { + if (!GameHelper.GetCloseResult()) return; + SetButtonsTouchable(false); + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (!isSuccess) + { + SetButtonsTouchable(true); + return; + } + + var start = GameHelper.GetUICenterPosition(ui.btn_adclaim); + var end = GameHelper.GetUICenterPosition(_isGiftSwitch + ? ui.top_money.GetChild("number_text") + : ui.gold.GetChild("number_text")); + + var startNum = 0f; + var endNum = 0f; + GObject numText; + + reward_data temp = new reward_data() { start = start, end = end }; + if (_isGiftSwitch) + { + var changeNum = _cashNumber * _rate; + temp.change = changeNum; + temp.type = 111; + GameHelper.AddMoney(temp.change); + + startNum = (float)GameHelper.Get102() - changeNum; + endNum = (float)GameHelper.Get102(); + numText = ui.top_money.GetChild("number_text") as GTextField; + + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + } + else + { + + startNum = GameHelper.GetGoldNumber(); + temp.change = RewardNum * _rate; + temp.type = 101; + GameHelper.AddGoldNumber((int)temp.change); + + endNum = GameHelper.GetGoldNumber(); + numText = ui.gold.GetChild("number_text"); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(startNum, endNum, 1f, + value => + { + var str = _isGiftSwitch ? GameHelper.Get102Str((decimal)value) : ((int)value).ToString(); + if (numText != null) + numText.text = str; + }); + }); + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + ClosePanelLogic(); + }); + } + + /// + /// 点击Claim按钮 + /// + private void OnClickClaim() + { + if (!GameHelper.GetCloseResult()) return; + SetButtonsTouchable(false); + var start = GameHelper.GetUICenterPosition(ui.btn_claim); + var end = GameHelper.GetUICenterPosition(_isGiftSwitch + ? ui.top_money.GetChild("number_text") + : ui.gold.GetChild("number_text")); + + var startNum = 0f; + var endNum = 0f; + GObject numText; + + reward_data temp = new reward_data() { start = start, end = end }; + if (_isGiftSwitch) + { + temp.change = _cashNumber; + temp.type = 111; + GameHelper.AddMoney(_cashNumber); + + startNum = (float)GameHelper.Get102() - _cashNumber; + endNum = (float)GameHelper.Get102(); + numText = ui.top_money.GetChild("number_text") as GTextField; + + DOVirtual.DelayedCall(2.5f, () => + { + GameHelper.AddInterAdNumber(); + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Close); + }); + + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + } + else + { + temp.change = RewardNum; + temp.type = 101; + GameHelper.AddGoldNumber(RewardNum); + + startNum = 0; + endNum = GameHelper.GetGoldNumber(); + numText = ui.gold.GetChild("number_text"); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(startNum, endNum, 1f, + value => + { + var str = _isGiftSwitch ? GameHelper.Get102Str((decimal)value) : ((int)value).ToString(); + if (numText != null) numText.text = str; + }); + }); + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + ClosePanelLogic(); + } + + /// + /// 点击CashOUt按钮 + /// + private void OnClickCash() + { + if (!GameHelper.GetCloseResult()) return; + SetButtonsTouchable(false); + + if (is_success) + { + var start = GameHelper.GetUICenterPosition(ui.btn_claim); + var end = GameHelper.GetUICenterPosition(ui.top_money.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start, end = end, change = _cashNumber, type = 111 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddMoney(_cashNumber); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.Get102(), 1f, + value => + { + (ui.top_money.GetChild("number_text") as GTextField).text = + GameHelper.Get102Str((decimal)value); + }); + }); + + DOVirtual.DelayedCall(2f, () => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData); + GameHelper.AddInterAdNumber(); + + }); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + } + else + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData); + } + + ClosePanelLogic(); + } + + /// + /// 播放音效 + /// + private void PlayDynamicEffect() + { + AudioManager.Instance.PlayDynamicEffect(is_success ? AudioConst.Victory : AudioConst.Defeat); + } + + + /// + /// 关闭界面逻辑 + /// + private void ClosePanelLogic(float delayTime = 2f) + { + DOVirtual.DelayedCall(delayTime, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Close); + ShowScrews.Instance.InitLogic(ShowScrews.Instance.gameMode == GameHome.Mode_simple ? GameHelper.GetLevel() : ShowScrews.Instance.GetCurMaxLevel()); + }); + } + + #endregion + + + private int _timeCount = 0; + void TimeEvent() + { + _timeCount++; + + if (_timeCount > 3) + { + _timeCount = 0; + _com_cash.broad.t0.Play(() => + { + var exBrPoolModel = ConfigSystem.GetConfig(); + var name_index = Random.Range(0, exBrPoolModel.config_name_list.Count); + var money_index = Random.Range(0, exBrPoolModel.config_money_list.Count); + // System.DateTime oldtime = System.DateTime.Now.AddSeconds(-Random.Range(1 * 3600, 2 * 3600)); + // var str = "Congratulations, [color=#e3a13a]" + + // exBrPoolModel.config_name_list[name_index] + + // "[/color] withdrew [color=#83c93c]" + + // exBrPoolModel.config_money_list[money_index] + + // "[/color]dollars"; + var str = string.Format( + _broadTextTemplate, + exBrPoolModel.config_name_list[name_index], + exBrPoolModel.config_money_list[money_index]); + _com_cash.broad.cast_text.text = str; + _com_cash.broad.t1.Play(); + }); + } + + } + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + } + protected override void RemoveListener() + { + HallManager.Instance.UpdateSecondEvent -= TimeEvent; + } + #endregion + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs.meta new file mode 100644 index 0000000..b101e51 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fd55f74e693624c269d3d70e211b2e6a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs new file mode 100644 index 0000000..34f372c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class LevelSuccessUICtrl : BaseUICtrl + { + private LevelSuccessUI ui; + private LevelSuccessModel model; + + private uint openUIMsg = UICtrlMsg.LevelSuccessUI_Open; + private uint closeUIMsg = UICtrlMsg.LevelSuccessUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.LevelSuccessModel) as LevelSuccessModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new LevelSuccessUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs.meta new file mode 100644 index 0000000..ed34f11 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/LevelSuccess/LevelSuccessUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e11350d8494e4786a5913ed38689cbc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading.meta new file mode 100644 index 0000000..08f0bb2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eeedfa67a1fb49e6baa12777bfa4eb94 +timeCreated: 1676622067 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs new file mode 100644 index 0000000..4b091a6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class LoadingCtrl : BaseCtrl + { + public static LoadingCtrl Instance { get; private set; } + + private LoadingModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs.meta new file mode 100644 index 0000000..9a6c484 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 341654c8a54544e9aefdab73ec4873a4 +timeCreated: 1676622067 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs new file mode 100644 index 0000000..402f596 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class LoadingModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs.meta new file mode 100644 index 0000000..e50804b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fcfcdf9f5d1c4197b3049bca9336855a +timeCreated: 1676622067 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs new file mode 100644 index 0000000..ef9fe31 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs @@ -0,0 +1,170 @@ +using DG.Tweening; + +namespace ScrewsMaster +{ + using System; + using System.Collections; + using FairyGUI; + using Spine.Unity; + using UnityEngine; + using Object = UnityEngine.Object; + + public class LoadingUI : BaseUI + { + private LoadingUICtrl ctrl; + private LoadingModel model; + private FGUI.SLoading.com_loading ui; + + protected GProgressBar pb_loading; + private Tweener tweener; + private Action closeCallback; + + + protected int currValue; + + public LoadingUI(LoadingUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.LoadingUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SLoading"; + uiInfo.assetName = "com_loading"; + uiInfo.layerType = UILayerType.Loading; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.SLoading.com_loading; + } + + protected override void OnOpenBefore(object args) + { + + // var login = FXManager.Instance.SetFx(ui.title_parent, Fx_Type.fx_title, ref closeCallback); + // login.state.SetAnimation(0, "animation", true); + // var rabbit = FXManager.Instance.SetFx(ui.logo_parent, Fx_Type.fx_rabbit, ref closeCallback); + // rabbit.state.SetAnimation(0, "animation", true); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenBgUI_Open); + pb_loading = this.ui.pb_loading; + pb_loading.max = 100; + pb_loading.value = 0; + // DOVirtual.Float(0, 100, 2.8f, (value) => + // { + // // ui.pb_loading.title = $"Loading...{(int)value}%"; + + // ui.pb_loading.value = (int)value; + // }); + CrazyAsyKit.StartCoroutine(SetProgressState()); + + var splashCanvas = GameObject.Find("SplashCanvas"); + if (splashCanvas != null) + { + splashCanvas.SetActive(false); + Object.Destroy(splashCanvas); + } + } + + public IEnumerator SetProgressState() + { + tweener = DOTween.To(() => ui.pb_loading.value, + x => ui.pb_loading.value = x, 97, 5.0f).SetEase(Ease.Linear); + + // RotateImageObject(); + ui.pb_loading.grip.TweenRotate(1800, 5) // 1 秒内旋转 360 度 + .SetEase(EaseType.Linear); + ui.pb_loading.grip.TweenMoveX(ui.pb_loading.grip.x + ui.pb_loading.Progress.width - ui.pb_loading.grip.width, 5).SetEase(EaseType.Linear); + + + yield return tweener; + } + + + private int _loopCount = 0; + private const int maxLoops = 5; // 设定最大循环次数 + void RotateImageObject() + { + // 如果旋转次数还没有达到最大值,继续旋转 + if (_loopCount < maxLoops) + { + // 使用 FairyGUI 自带的 TweenRotate 让图片旋转 360 度 + ui.pb_loading.grip.TweenRotate(359, 1f) // 1 秒内旋转 360 度 + .SetEase(EaseType.Linear) // 匀速旋转 + .OnComplete(() => + { + _loopCount++; // 每次完成后递增计数 + RotateImageObject(); // 递归调用实现循环 + }); + } + else + { + Debug.Log("Rotation completed 5 times"); + } + } + + protected override void OnOpen(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.UpdateHotFixMax, OnUpdateHotFixMax); + GameDispatcher.Instance.AddListener(GameMsg.UpdateHotFixProgress, OnUpdateHotFixProgress); + } + + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.UpdateHotFixMax, OnUpdateHotFixMax); + GameDispatcher.Instance.RemoveListener(GameMsg.UpdateHotFixProgress, OnUpdateHotFixProgress); + } + + #endregion + + private bool isAgree = true; + + public void CheckAgree() + { + if (!isAgree) return; + ctrl.CloseUI(); + } + + private void OnUpdateHotFixMax(object obj) + { + if (obj != null) + { + var max = (int)obj; + // ui.pb_loading.max = max; + } + } + + private void OnUpdateHotFixProgress(object obj) + + { + if (obj != null) + { + tweener.Kill(); + var value = (int)obj; + pb_loading.value = value; + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs.meta new file mode 100644 index 0000000..7be6892 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0873adccf5e64e15a037be3341254d6c +timeCreated: 1676622067 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs new file mode 100644 index 0000000..6ec2808 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs @@ -0,0 +1,70 @@ +namespace ScrewsMaster +{ + public class LoadingUICtrl : BaseUICtrl + { + private LoadingUI ui; + private LoadingModel model; + + private uint openUIMsg = 0; + private uint closeUIMsg = 0; + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new LoadingUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui is { isClose: false }) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + AppDispatcher.Instance.AddListener(AppMsg.UI_DisplayLoadingUI, OpenUI); + AppDispatcher.Instance.AddListener(AppMsg.UI_HideLoadingUI, OnHideLoading); + } + + protected override void RemoveListener() + { + AppDispatcher.Instance.RemoveListener(AppMsg.UI_DisplayLoadingUI, OpenUI); + AppDispatcher.Instance.RemoveListener(AppMsg.UI_HideLoadingUI, OnHideLoading); + } + + private void OnHideLoading(object obj) + { + if (ui == null) return; + ui.CheckAgree(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs.meta new file mode 100644 index 0000000..973649c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Loading/LoadingUICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5f7cb8eec2bb493fb2e95f287120770e +timeCreated: 1676622067 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm.meta new file mode 100644 index 0000000..3b5deca --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6c23019fa9fe43929244ca1d635cb1ae +timeCreated: 1729592799 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs new file mode 100644 index 0000000..5e13684 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs @@ -0,0 +1,48 @@ +namespace ScrewsMaster +{ + public class MakeupConfirmCtrl : BaseCtrl + { + public static MakeupConfirmCtrl Instance { get; private set; } + + private MakeupConfirmModel model; + + #region 生命周期 + + protected override void OnInit() + { + Instance = this; + + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs.meta new file mode 100644 index 0000000..efd9a48 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f3c22f134c92094198982eae9ecf41e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs new file mode 100644 index 0000000..0f3a031 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs @@ -0,0 +1,54 @@ +namespace ScrewsMaster +{ + public class MakeupConfirmModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + + // #endregion + + // #region 读取数据 + + // protected override void OnReadData() + // { + // } + + // #endregion + + // #region 本地存储 + + + + // protected override void WriteLocalStorage() + // { + + // } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs.meta new file mode 100644 index 0000000..8413770 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 818318a1dea7cbf49a3adfe94249fb81 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs new file mode 100644 index 0000000..3979fc4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs @@ -0,0 +1,810 @@ +using System; +using FairyGUI; +using FGUI.G007_makeup; +using Newtonsoft.Json; +using UnityEngine; +using System.Collections.Generic; +using System.Linq; +using FGUI.A000_common; +using FGUI.G018_GameHome; + +namespace ScrewsMaster +{ + public class MakeupConfirmUI : BaseUI + { + private MakeupConfirmUICtrl ctrl; + private MakeupConfirmModel model; + private com_confirm ui; + + public int ad_cool_down = 120; + private long userUid; + + + private MakeupTaskData makeupTaskData; + private bool is_pt = false; + + public MakeupConfirmUI(MakeupConfirmUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.MakeupConfirmUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G007_makeup"; + uiInfo.assetName = "com_confirm"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= updateSpeedCD; + + GameHelper.showGameUI = true; + WebviewManager.Instance.SetDarkThough(true); + gameDispatcher.Dispatch(GameMsg.MakeUpConfirmUIClosed); + } + + protected override void OnBind() + { + ui = baseUI as com_confirm; + } + + protected override void OnOpenBefore(object args) + { + + userUid = GameHelper.GetLoginModel().uid; + ad_cool_down = ConfigSystem.GetConfig().WithdrawalaccelerationCD; + //PreferencesMgr.Instance.MakeupTaskH5Time = 999999999; + WebviewManager.Instance.SetDarkThough(false); + if (AppConst.isPt()) + { + ui.lang.selectedIndex = com_confirm.Lang_pt; + } + else ui.lang.selectedIndex = com_confirm.Lang_en; + + makeupTaskData = args as MakeupTaskData; + cash_index = makeupTaskData.tableId - 1; + ui.btn_pay1.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Open, 1); + }); + ui.com_task.btn_pay2.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Open, 2); + }); + + ui.btn_watch.SetClick(WatchBtnClick); + + HallManager.Instance.UpdateSecondEvent += updateSpeedCD; + updateSpeedCD(); + + InitView(); + initButtom(); + //PixPayUI.getOrderState(); + GameHelper.SetSelfAvatar((ui.com_pay.btn_menu.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.PaySuccess, InitView); + } + + protected override void RemoveListener() + { + } + + #endregion + + private void InitView(object a = null) + { + if (makeupTaskData == null) + { + return; + } + initTop(); + ui.btn_close.SetClick(CtrlCloseUI); + if (makeupTaskData.status == MakeupTaskStatus.None) + { + if (PreferencesMgr.Instance.ExchangeAccount == null) + { + OnEnter(); + return; + } + if (GameHelper.needShowLevelstate(now_selectindex)) + { + ui.cont_state.selectedIndex = 5; + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + + ui.text_cashneedlv.text = string.Format(ui.text_cashneedlv.text, vo.levels_need); + ui.text_nowcash.text = GameHelper.Get102Str(PreferencesMgr.Instance.Currency102); + ui.Text_Title.text = "Level " + vo.levels_need; + if (GameHelper.GetLevel() <= vo.levels_need) + { + (ui.btn_check_level as btn_tabblue).state.selectedIndex = 1; + ui.btn_check_level.SetClick(() => + { + GameHelper.ShowTips("withdrawal level not reached."); + }); + } + else + { + ui.btn_check_level.SetClick(() => + { + PlayerPrefs.SetInt("cash_lv", vo.id); + InitView(); + }); + } + return; + + } + + OnConfirm(); + + } + else if (makeupTaskData.status == MakeupTaskStatus.Task) + { + OnTask(); + } + else if (makeupTaskData.status == MakeupTaskStatus.Inline) + { + OnInline(); + } + + } + private int now_selectindex = 0; + private int cash_index = 0; + void initTop() + { + Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.MakeupTaskHistory)); + List btn_list = new List() { ui.com_cashlevel.btn_0, ui.com_cashlevel.btn_1, ui.com_cashlevel.btn_2 }; + + List makeup_list = ConfigSystem.GetConfig().dataList; + now_selectindex = makeupTaskData.tableId - 1; + for (int i = 0; i < btn_list.Count; i++) + { + btn_list[i].text_Level0.text = "Level " + makeup_list[i].levels_need; + btn_list[i].text_Level1.text = "Level " + makeup_list[i].levels_need; + btn_list[i].text_Level2.text = "Level " + makeup_list[i].levels_need; + // btn_list[i].text_level1.text = "Level " + makeup_list[i].levels_need; + if (i < cash_index) + { + btn_list[i].img_check.visible = true; + } + else + { + btn_list[i].img_check.visible = false; + } + if (i == now_selectindex) + { + btn_list[i].btn_state.selectedIndex = 1; + } + else if (i > cash_index) + { + btn_list[i].btn_state.selectedIndex = 2; + int _temp_index = i; + btn_list[i].SetClick(() => + { + GameHelper.ShowTips("Complete level " + makeup_list[_temp_index].levels_need + " to unlock."); + }); + } + else + { + btn_list[i].btn_state.selectedIndex = 0; + int index = i; + btn_list[i].SetClick(() => + { + for (int i = PreferencesMgr.Instance.MakeupTaskHistory.Count - 1; i >= 0; i--) + { + if (PreferencesMgr.Instance.MakeupTaskHistory[i].tableId == index + 1) + { + makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory[i]; + now_selectindex = index; + break; + } + } + + InitView(); + }); + } + } + + } + void initButtom() + { + int day = DateTime.Now.Day; + int hour = DateTime.Now.Hour; + Debug.Log(day); + if (day != SaveData.GetSaveobject().login_day) + { + SaveData.GetSaveobject().login_day = day; + SaveData.GetSaveobject().login_hour = 0; + // public int cash_people; + // public float cash_people_1; + // public float cash_people_2; + SaveData.GetSaveobject().cash_people = UnityEngine.Random.Range(500, 800); + SaveData.GetSaveobject().cash_people_1 = UnityEngine.Random.Range(20, 30); + SaveData.GetSaveobject().cash_people_2 = UnityEngine.Random.Range(3, 6) * 100; + SaveData.saveDataFunc(); + } + if (hour != SaveData.GetSaveobject().login_hour) + { + + SaveData.GetSaveobject().cash_people += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(8, 10); + SaveData.GetSaveobject().cash_people_1 += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(10, 15); + SaveData.GetSaveobject().cash_people_2 += ((hour - SaveData.GetSaveobject().login_hour) / 3) * UnityEngine.Random.Range(1, 3) * 100; + if (hour - SaveData.GetSaveobject().login_hour >= 3) SaveData.GetSaveobject().login_hour = hour; + SaveData.saveDataFunc(); + } + + + + ui.text_number0.text = SaveData.GetSaveobject().cash_people.ToString(); + ui.text_number1.text = SaveData.GetSaveobject().cash_people_1.ToString(); + ui.text_number2.text = GameHelper.GetPaymentTypeVO().payicon + SaveData.GetSaveobject().cash_people_2; + ui.text_cashdate.text = string.Format(ui.text_cashdate.text, DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day); + + } + + private void OnEnter() + { + GTextInput enter_input = null; + + ui.Text_Title.SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars(); + ui.text_smaill_title.SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars(); + // if (AppConst.isPt()) + // { + // ui.text_title.SetVar("payer", "Pix").FlushVars(); + // ui.text_smaill_title.SetVar("payer", "Pix").FlushVars(); + // } + if (GameHelper.GetCurrCountry().ToUpper().Equals("RU")) + { + ui.com_info.cont_type.selectedIndex = com_enter.Type_phone; + enter_input = ui.com_info.enter_phone; + } + else + { + ui.com_info.cont_type.selectedIndex = com_enter.Type_email; + enter_input = ui.com_info.enter_email; + } + + ui.cont_state.selectedIndex = ui._State_enter; + ui.btn_tab.SetClick(() => + { + var account = enter_input.text.Replace(" ", ""); + if (account == null || account == "") + { + GameHelper.ShowTips("Please enter the correct account information", true); + return; + } + + if (!GameHelper.CheckAccountValidly(account)) + { + GameHelper.ShowTips("Please enter the correct account information", true); + return; + } + + var fname = ui.com_fname.enter_fname.text.Replace(" ", ""); + if (!GameHelper.CheckNameValidly(fname)) + { + GameHelper.ShowTips("Please enter the correct account information", true); + return; + } + + var lname = ui.com_lname.enter_lname.text.Replace(" ", ""); + if (!GameHelper.CheckNameValidly(lname) && !AppConst.isPt()) + { + GameHelper.ShowTips("Please enter the correct account information", true); + return; + } + PreferencesMgr.Instance.ExchangeAccount = account; + PreferencesMgr.Instance.ExchangeName = $"{fname} {lname}"; + PreferencesMgr.Instance.short_name = fname; + PreferencesMgr.Instance.long_name = lname; + showPaypal(); + //uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupStepUI_Open, makeupTaskData); + //CtrlCloseUI(); + }); + + ui.btn_back.SetClick(() => + { + CtrlCloseUI(); + // GuideCtrl.Instance.Dispatch("second"); + }); + } + + void showPaypal() + { + ui.cont_state.selectedIndex = 4; + + if (makeupTaskData == null) + { + return; + } + + + ui.com_pay.text_name.text = PreferencesMgr.Instance.ExchangeName; + ui.com_pay.text_email.text = PreferencesMgr.Instance.ExchangeAccount; + + ui.com_pay.btn_change.SetClick(() => + { + PreferencesMgr.Instance.ExchangeName = null; + PreferencesMgr.Instance.ExchangeAccount = null; + ui.cont_state.selectedIndex = 0; + + // uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData); + // CtrlCloseUI(); + }); + + //ui.btn_confirm.touchable = false; + //GameHelper.PlayFGUIFx(ui.fx_in, true, () => { ui.btn_confirm.touchable = true; }); + + ui.btn_confirm.SetClick(() => + { + var info = new + { + email = PreferencesMgr.Instance.ExchangeAccount, + first_name = PreferencesMgr.Instance.short_name, + last_name = PreferencesMgr.Instance.long_name + }; + NetworkKit.PostWithHeader("shop/payOutUserInfo", info, (isSuccess, obj) => + { + if (isSuccess) + { + } + }); + // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_message, 1); + InitView(); + // uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData); + //CtrlCloseUI(); + }); + + //TextureHelper.GetCardIcon(true, spr => { ui.loader_payer.texture = spr; }); + + // ui.text_warn.SetVar("app", Application.productName).FlushVars(); + // if (GameHelper.GetCurrCountry().ToUpper().Equals("RU")) + // { + // ui.text_warn.SetVar("payer", "Qiwi").FlushVars(); + // ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_ru; + // ui.btn_confirm.country.selectedIndex = btn_confirm.Country_ru; + // ui.com_trans.cont_country.selectedIndex = com_trans.Country_ru; + // ui.lang.selectedIndex = com_step.Lang_en; + // } + // else if (AppConst.isPt()) + // { + // ui.text_warn.SetVar("payer", "Pix").FlushVars(); + // ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_pt; + // ui.btn_confirm.country.selectedIndex = btn_confirm.Country_ru; + // ui.com_trans.cont_country.selectedIndex = com_trans.Country_pt; + // ui.lang.selectedIndex = com_step.Lang_pt; + // } + // else + // { + // ui.text_warn.SetVar("payer", "Paypal").FlushVars(); + // ui.com_info.cont_counrty.selectedIndex = com_info.Counrty_default; + // ui.btn_confirm.country.selectedIndex = btn_confirm.Country_default; + // ui.com_trans.cont_country.selectedIndex = com_trans.Country_default; + // ui.lang.selectedIndex = com_step.Lang_en; + // } + + + } + + private void OnConfirm() + { + ui.cont_state.selectedIndex = ui._State_confirm; + + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + if (vo == null) + { + return; + } + + ui.text_condi1.SetVar("cash", GameHelper.Get102Str(vo.item_need)).FlushVars(); + ui.pb_condi1.max = vo.item_need; + var curValue = Math.Min(GameHelper.Get102(), vo.item_need); + ui.pb_condi1.value = (double)curValue; + ui.pay_text1.text = + String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios", + (ConfigSystem.GetConfig().purchase1 + ",00")); + var textTitle = ui.pb_condi1.GetChild("title"); + if (textTitle != null) + { + textTitle.text = $"{GameHelper.Get102Str(curValue)}/{GameHelper.Get102Str(vo.item_need)}"; + } + + + var taskTime = (int)((float)vo.task_need / 60 * 100) * 0.01F; + var completeTaskTime = (int)((float)PreferencesMgr.Instance.MakeupTaskH5Time / 60 * 100) * 0.01F; + var completeTaskValue = Math.Min(completeTaskTime, taskTime); + ui.text_condi2.SetVar("hot", taskTime.ToString()).FlushVars(); + ui.pb_condi2.max = taskTime; + ui.pb_condi2.value = completeTaskValue; + ui.pb_condi2.title.text = $"{completeTaskValue}/{taskTime}"; + if (PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need && AppConst.isPt()) + { + ui.show_pay.selectedIndex = com_confirm.Show_pay_true; + } + else ui.show_pay.selectedIndex = com_confirm.Show_pay_false; + + ui.text_wallet.SetVar("Payer", GameHelper.GetPaymentPayer()).FlushVars(); + if (AppConst.isPt()) ui.text_wallet.text = "Pix"; + ui.text_cash.text = makeupTaskData.GetAmountStr(); + ui.text_account.text = PreferencesMgr.Instance.ExchangeAccount; + + if (GameHelper.Get102() >= vo.item_need && + completeTaskTime >= taskTime) + { + ui.cont_confirm.selectedIndex = ui._Confirm_ready; + (ui.btn_earn as btn_tabblue).state.selectedIndex = 0; + ui.btn_earn.SetClick(() => + { + AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone); + + makeupTaskData.SetStatus(MakeupTaskStatus.Task); + PreferencesMgr.Instance.SaveMakeupTaskHistory(); + OnTask(); + }); + } + else + { + ui.cont_confirm.selectedIndex = ui._Confirm_none; + // (ui.btn_earn as btn_tabblue).state.selectedIndex = 1; + ui.btn_earn.SetClick(() => + { + if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close); + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + } + CtrlCloseUI(); + // AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone); + // // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open); + // GameDispatcher.Instance.Dispatch(GameMsg.GotoH5); + + // //GameDispatcher.Instance.Dispatch(GameMsg.MainTab, 1); + + // CtrlCloseUI(); + // WebviewManager.Instance.SetDarkThough(true); + }); + } + } + + private void OnTask() + { + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + if (vo == null) + { + return; + } + + ui.cont_state.selectedIndex = ui._State_task; + ui.com_task.text_orderid.text = makeupTaskData.orderID; + ui.com_task.text_task_title.SetVar("ad", vo.ad_need.ToString()).FlushVars(); + ui.com_task.text_ads.text = $"{makeupTaskData.videoCount}/{vo.ad_need}"; + if (AppConst.isPt() && makeupTaskData.videoCount < vo.ad_need) ui.com_task.lang.selectedIndex = com_task.Lang_pt; + else ui.com_task.lang.selectedIndex = com_task.Lang_en; + ui.com_task.pay_text1.text = String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios", + (ConfigSystem.GetConfig().purchase2 + ",00")); + ui.com_task.text_payer.SetVar("amt", makeupTaskData.GetAmountStr()) + .SetVar("payer", GameHelper.GetPaymentPayer()).FlushVars(); + if (makeupTaskData.videoCount >= vo.ad_need) + { + ui.com_task.cont_process.selectedIndex = 1; + } + else ui.com_task.cont_process.selectedIndex = 0; + if (makeupTaskData.videoCount >= vo.ad_need) + { + (ui.btn_cashout as btn_tabblue).state.selectedIndex = 0; + ui.btn_cashout.SetClick(() => + { + + + GameHelper.ShowLoading(1, 2, () => + { + ConsumeSystem.Consume(vo.item, vo.item_need, isSuccess => + { + makeupTaskData.SetStatus(MakeupTaskStatus.Inline); + makeupTaskData.inlineInitNum = + CommonHelper.RandomRange(ConfigSystem.GetConfig().inlineInitNum[0], + ConfigSystem.GetConfig().inlineInitNum[1]); + makeupTaskData.inlineNum = CommonHelper.RandomRange( + ConfigSystem.GetConfig().inlineInitNum[0], + makeupTaskData.inlineInitNum); + makeupTaskData.order_time = GameHelper.GetNowTime(); + PreferencesMgr.Instance.SaveMakeupTaskHistory(); + //OnInline(); + Debug.Log(JsonConvert.SerializeObject(vo)); + if (vo.id == 1) + { + // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash1, 1); + } + else if (vo.id == 2) + { + // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash2, 1); + } + else if (vo.id == 3) + { + // NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash3, 1); + } + if (vo.id != 3) + { + cash_index++; + } + InitView(); + if (vo.id == 3) + { + PlayerPrefs.SetInt("cash_lv", 2); + makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + } + + }); + }); + + + + }); + } + else + { + // (ui.btn_cashout as btn_tabblue).state.selectedIndex = 1; + ui.btn_cashout.SetClick(() => + { + if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close); + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + } + CtrlCloseUI(); + }); + } + + } + + private void OnInline() + { + CheckBtnWatchStatus(); + + ui.cont_state.selectedIndex = ui._State_query; + + ui.text_payhint.SetVar("account", PreferencesMgr.Instance.ExchangeAccount).FlushVars(); + + ui.text_query.SetVar("cur", makeupTaskData.inlineNum.ToString()) + .SetVar("tol", makeupTaskData.inlineInitNum.ToString()).FlushVars(); + + CheckActive(makeupTaskData.tableId); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + ui.btn_tab.SetClick(CtrlCloseUI); + + ui.btn_record.SetClick(() => + { + //uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupRecordUI_Open); + // MainTabUI.getIns().OnGameTab(3); + CtrlCloseUI(); + }); + + RefreshRecordData(); + } + + #region 兑换加速 + private void RefreshRecordData() + { + var data = makeupTaskData; + var com_rank = ui.com_newRecord.com_rank; + var com_cord = ui.com_newRecord.com_cord; + + com_cord.email_text.text = PreferencesMgr.Instance.ExchangeAccount; + com_cord.number_text.text = data.inlineNum + "/" + data.inlineInitNum; + + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == data.tableId); + if (redeemVOModel == null) return; + + if (redeemVOModel.AD_Limit_times <= data.WatchVideoSpeedNum) + { + ui.btn_watch.enabled = false; + ui.btn_watch.visible = false; + com_rank.content1.selectedIndex = 1;//com_rank.Content1_complete; + com_rank.text_rank1.SetVar("rank", data.WatchVideoSpeedNum.ToString()).FlushVars(); + } + else + { + ui.btn_watch.enabled = true; + ui.btn_watch.visible = true; + com_rank.content1.selectedIndex = 0;//com_rank.Content1_speeding; + com_rank.text_rank1.SetVar("rank", redeemVOModel.AD_Down.ToString()).FlushVars(); + } + + if (redeemVOModel.Login_Limit_times <= data.loginSpeedNum) + { + com_rank.content2.selectedIndex = 1;//com_rank.Content2_complete; + com_rank.text_rank2.SetVar("rank", redeemVOModel.Login_Limit_times.ToString()).FlushVars(); + } + else + { + com_rank.content2.selectedIndex = 0;//com_rank.Content2_speeding; + var loginRans = GameHelper.GetCommonModel().inlineLoginDown[0] + "-" + GameHelper.GetCommonModel().inlineLoginDown[1]; + com_rank.text_rank2.SetVar("rank", loginRans).FlushVars(); + } + + if (redeemVOModel.Active_Limit_times <= data.activeSpeedNum) + { + com_rank.content3.selectedIndex = 1;//com_rank.Content3_complete; + com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_Limit_times.ToString()).FlushVars(); + } + else + { + com_rank.content3.selectedIndex = 0;//com_rank.Content3_speeding; + + com_rank.text_rank3.SetVar("time", redeemVOModel.Active_time.ToString()).FlushVars(); + com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_time_Down.ToString()).FlushVars(); + + if (CommonHelper.activeTimes.TryGetValue(data.tableId, out int openTimes)) + { + Debug.Log($"openTimes ===== {openTimes}, data.tableId=== activeTimes_{data.tableId}"); + if (openTimes > 1) + { + //活跃的分钟数 + int min_num = ((int)Time.time - data.activeMinute) / 60; + + //是配置的活跃时间的多少倍 + int active_times = min_num / redeemVOModel.Active_time; + + Debug.Log($"min_num=== {min_num} {active_times} "); + if (active_times > 0) + { + data.activeMinute = (int)Time.time; + // 可以加速多少排名 + int rank_num = active_times * redeemVOModel.Active_time_Down; + var last = data.activeSpeedNum; + data.activeSpeedNum += rank_num; + Debug.Log($"rank_num=== {rank_num} {last} {data.activeSpeedNum} {redeemVOModel.Active_Limit_times}"); + if (data.activeSpeedNum > redeemVOModel.Active_Limit_times) + { + rank_num = redeemVOModel.Active_Limit_times - last; + data.activeSpeedNum = redeemVOModel.Active_Limit_times; + } + data.inlineNum -= rank_num; + + Debug.Log($"订单为: {data.tableId} 通过活跃时间减少的排名为:{rank_num}"); + + if (data.inlineNum < GameHelper.GetCommonModel().inlineMin) + { + data.inlineNum = GameHelper.GetCommonModel().inlineMin; + } + } + } + else + { + data.activeMinute = (int)Time.time; + } + } + } + + com_cord.text_amt.text = $"+{data.amountStr}"; + if (data.order_time != 0) + { + com_cord.time_text.text = DateTimeManager.Instance.TimestampToString(data.order_time); + } + + com_rank.text_ranks.text = data.inlineNum.ToString(); + } + + void CheckBtnWatchStatus() + { + var data = makeupTaskData; + + if (data == null) + { + return; + } + var CardRedeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == data.tableId); + if (CardRedeemVOModel == null) return; + + bool isShow = CardRedeemVOModel.AD_Limit_times > data.WatchVideoSpeedNum && data.inlineNum > GameHelper.GetCommonModel().inlineMin; + + ui.btn_watch.enabled = isShow; + + } + + void updateSpeedCD() + { + var lastTimes = PlayerPrefs.GetInt($"speed_ad_cool_times_{userUid}", 0); + if (GameHelper.GetNowTime() < lastTimes + ad_cool_down) + { + ui.btn_watch.enabled = false; + ui.btn_watch.show_cd.selectedIndex = 1;//btn_watch.Show_cd_cd; + ui.btn_watch.text_cd.text = CommonHelper.TimeFormat( + lastTimes + ad_cool_down - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Hour); + } + else + { + HallManager.Instance.UpdateSecondEvent -= updateSpeedCD; + ui.btn_watch.enabled = true; + ui.btn_watch.show_cd.selectedIndex = 0;//btn_watch.Show_cd_none; + } + + } + + private void CheckActive(int index) + { + if (CommonHelper.activeTimes.TryGetValue(index, out int value)) + { + value++; + // Debug.Log($"CheckActive2: {index} {value}"); + CommonHelper.activeTimes[index] = value; + + } + else + { + CommonHelper.activeTimes.Add(index, 1); + } + + } + + void WatchBtnClick() + { + + HallManager.Instance.UpdateSecondEvent -= updateSpeedCD; + if (GameHelper.GetNowTime() <= PlayerPrefs.GetInt($"speed_ad_cool_times_{userUid}", 0) + ad_cool_down) + { + Debug.Log("not click"); + return; + } + + GameHelper.ShowVideoAd("reward_OpeningDollarBills", isSuccess => + { + if (isSuccess) + { + ui.btn_watch.enabled = false; + TimerHelper.mEasy.AddTimer(1.5f, () => + { + var ad_times = Convert.ToInt32(GameHelper.GetNowTime()); + PlayerPrefs.SetInt($"speed_ad_cool_times_{userUid}", ad_times); + HallManager.Instance.UpdateSecondEvent += updateSpeedCD; + InitView(); + }); + + } + }); + + // var adNum = PreferencesMgr.Instance.RealWatchVideo; + // Debug.Log($"adNum========: {adNum}"); + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs.meta new file mode 100644 index 0000000..958d9e8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0dc409e12bb31e642af8b173f98f9772 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs new file mode 100644 index 0000000..d03a631 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs @@ -0,0 +1,79 @@ +namespace ScrewsMaster +{ + public class MakeupConfirmUICtrl : BaseUICtrl + { + private MakeupConfirmUI ui; + private MakeupConfirmModel model; + + private uint openUIMsg = UICtrlMsg.MakeupConfirmUI_Open; + private uint closeUIMsg = UICtrlMsg.MakeupConfirmUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new MakeupConfirmUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs.meta new file mode 100644 index 0000000..161f2a6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupConfirm/MakeupConfirmUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0f8a5752907ebb341bf7d7f04c5a23fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord.meta new file mode 100644 index 0000000..45b6976 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 621de1d602f246f790b876c398066849 +timeCreated: 1729594688 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs new file mode 100644 index 0000000..7202f92 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs @@ -0,0 +1,49 @@ + +namespace ScrewsMaster +{ + public class MakeupRecordCtrl : BaseCtrl + { + public static MakeupRecordCtrl Instance { get; private set; } + + private MakeupRecordModel model; + + #region 生命周期 + + protected override void OnInit() + { + Instance = this; + + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs.meta new file mode 100644 index 0000000..0af74c0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22221344f928ae243a73c843198d1159 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs new file mode 100644 index 0000000..80851df --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs @@ -0,0 +1,55 @@ + +namespace ScrewsMaster +{ + public class MakeupRecordModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + + // #endregion + + // #region 读取数据 + + // protected override void OnReadData() + // { + // } + + // #endregion + + // #region 本地存储 + + + + // protected override void WriteLocalStorage() + // { + + // } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs.meta new file mode 100644 index 0000000..4b083ac --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 445d612eb56d45d4387e01dc7ca24292 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs new file mode 100644 index 0000000..5dc1529 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs @@ -0,0 +1,133 @@ +using FairyGUI; +using FGUI.G007_makeup; +using System.Collections.Generic; +using UnityEngine; + +namespace ScrewsMaster +{ + public class MakeupRecordUI : BaseUI + { + private MakeupRecordUICtrl ctrl; + private MakeupRecordModel model; + private com_record ui; + + public MakeupRecordUI(MakeupRecordUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.MakeupRecordUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G007_makeup"; + uiInfo.assetName = "com_record"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as com_record; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + #endregion + + private List makeupdataList = new List(); + + private void InitView() + { + // if (Screen.safeArea.y != 0) + // {//刘海屏 + // ui.group_.y += Screen.safeArea.y; + // } + makeupdataList.Clear(); + + foreach (var makeupTaskData in PreferencesMgr.Instance.MakeupTaskHistory) + { + if (makeupTaskData.status != MakeupTaskStatus.Inline) + { + continue; + } + + makeupdataList.Add(makeupTaskData); + } + + if (makeupdataList.Count == 0) + { + ui.cont_show.selectedIndex = ui._Show_none; + } + else + { + ui.cont_show.selectedIndex = ui._Show_list; + ui.list_record.itemRenderer = ItemRenderer; + ui.list_record.numItems = makeupdataList.Count; + } + + ui.closeButton.SetClick(CtrlCloseUI); + ui.btn_help.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RegulationUI_Open); }); + } + + private void ItemRenderer(int index, GObject gObject) + { + var data = makeupdataList[index]; + var item = gObject as com_cord; + if (data == null || item == null) + { + return; + } + + TextureHelper.GetCardIcon(true, spr => { item.loader_logo.texture = spr; }); + // item.text_name.SetVar("cur", data.inlineNum.ToString()).SetVar("tol", data.inlineInitNum.ToString()) + // .FlushVars(); + item.text_amt.text = "+" + GameHelper.GetPaymentTypeVO().payicon + (int)data.amount; + item.email_text.text = PreferencesMgr.Instance.ExchangeAccount; + item.number_text.text = data.inlineNum + "/" + data.inlineInitNum; + item.time_text.text = DateTimeManager.Instance.TimestampToString(data.order_time); + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs.meta new file mode 100644 index 0000000..fd79189 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8584b898ff07afe46a8da65f08dcdfce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs new file mode 100644 index 0000000..961b973 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs @@ -0,0 +1,80 @@ + +namespace ScrewsMaster +{ + public class MakeupRecordUICtrl : BaseUICtrl + { + private MakeupRecordUI ui; + private MakeupRecordModel model; + + private uint openUIMsg = UICtrlMsg.MakeupRecordUI_Open; + private uint closeUIMsg = UICtrlMsg.MakeupRecordUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new MakeupRecordUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs.meta new file mode 100644 index 0000000..6aa7120 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/MakeupRecord/MakeupRecordUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57cb7e1089555e0489a2d13e892a61cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask.meta new file mode 100644 index 0000000..bbf84c6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ae970a2e684826146bbc40194570fb30 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs new file mode 100644 index 0000000..21a46d4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class MaskCtrl : BaseCtrl + { + public static MaskCtrl Instance { get; private set; } + + private MaskModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs.meta new file mode 100644 index 0000000..7ed35f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef115f18b65ea084c8bbaa65a89f60b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs new file mode 100644 index 0000000..bffab3c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class MaskModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs.meta new file mode 100644 index 0000000..cf0c78e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d729819703a86b341a2476cd1848fa02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs new file mode 100644 index 0000000..b809478 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs @@ -0,0 +1,54 @@ +namespace ScrewsMaster +{ + public class MaskUI : BaseUI + { + private MaskUICtrl ctrl; + private MaskModel model; + private FGUI.SC004_Mask.com_Mask ui; + + public MaskUI(MaskUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.MaskUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SC004_Mask"; + uiInfo.assetName = "com_Mask"; + uiInfo.layerType = UILayerType.System; + } + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + + } + + protected override void OnOpenBefore(object args) + { + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + + + #endregion + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs.meta new file mode 100644 index 0000000..e7d4577 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f53dfcef6a2e05440b6a22773c677b5b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs new file mode 100644 index 0000000..7dffb4f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class MaskUICtrl : BaseUICtrl + { + private MaskUI ui; + private MaskModel model; + + private uint openUIMsg = UICtrlMsg.MaskUI_Open; + private uint closeUIMsg = UICtrlMsg.MaskUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new MaskUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs.meta new file mode 100644 index 0000000..883ac85 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Mask/MaskUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0f1b0b5f55e05e846b044c8fb93f77d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu.meta new file mode 100644 index 0000000..145445e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 257d09b8bafb4a1d84a600618c4316fd +timeCreated: 1676360265 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs new file mode 100644 index 0000000..499503e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs @@ -0,0 +1,50 @@ + + +namespace ScrewsMaster +{ + public class MenuCtrl : BaseCtrl + { + public static MenuCtrl Instance { get; private set; } + + private MenuModel model; + + #region 生命周期 + + protected override void OnInit() + { + Instance = this; + + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs.meta new file mode 100644 index 0000000..296ab1d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f454d607f8ad454fb11ae4756ed84dfd +timeCreated: 1676360266 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs new file mode 100644 index 0000000..396e64b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs @@ -0,0 +1,107 @@ + +using System.Linq; +namespace ScrewsMaster +{ + public class MenuModel : BaseModel + { + public bool IsOpenMusic + { + get { return AudioManager.Instance.IsOpenBGM; } + set { AudioManager.Instance.IsOpenBGM = value; } + } + + public bool IsOpenEffect + { + get { return AudioManager.Instance.IsOpenEffect; } + set { AudioManager.Instance.IsOpenEffect = value; } + } + + #region 生命周期 + private int currLangId; + private LangDisplayModel langDisplayModel; + public int CurrLangId + { + get + { + string code = ""; + + code = AppConst.CurrMultiLangue; + + currLangId = GetIdByLanguageCode(code); + return currLangId; + } + set + { + currLangId = value; + + var vo = langDisplayModel.dataList[0]; + foreach (var langDisplay in langDisplayModel.dataList.Where(langDisplay => langDisplay.id == currLangId)) + { + vo = langDisplay; + } + PlayerPrefsKit.WriteString(LangIdKey, vo.language); + UIManager.Instance.SetSwitchLanguage(vo.language); + } + } + int GetIdByLanguageCode(string code) + { + if (langDisplayModel == null) + { + langDisplayModel = ConfigSystem.GetConfig(); + } + + var vo = langDisplayModel.dataList.Find((tmp) => tmp.language == code); + if (vo != null) + return vo.id; + return GetIdByLanguageCode(AppConst.DefaultLangue); + } + + public string LangIdKey = "LangIdKey"; + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + + // #endregion + + // #region 读取数据 + + // protected override void OnReadData() + // { + // } + + // #endregion + + // #region 本地存储 + + + + // protected override void WriteLocalStorage() + // { + + // } + + #endregion + + #region 消息 + + protected override void AddListener() + { + + } + + protected override void RemoveListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs.meta new file mode 100644 index 0000000..e71e92e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f1ea9acdf2dc4281b6ce4ce36ecf131e +timeCreated: 1676360266 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs new file mode 100644 index 0000000..9bcdb93 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs @@ -0,0 +1,268 @@ +using System; +using FairyGUI; +using FGUI.G006_menu; +using UnityEngine; + +namespace ScrewsMaster +{ + public class MenuUI : BaseUI + { + private MenuUICtrl ctrl; + private MenuModel model; + private FGUI.G006_menu.com_menu ui; + + public MenuUI(MenuUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.MenuUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G006_menu"; + uiInfo.assetName = "com_menu"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.MenuModel) as MenuModel; + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G006_menu.com_menu; + } + + protected override void OnOpenBefore(object args) + { + // var mode = (int)args; + // ui.switchgift.selectedIndex = mode; + + InitView(); + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.playerName, OnChangeName); + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + HallManager.Instance.AddChangeGiftSwitch(InitView); + } + + protected override void RemoveListener() + { + PreferencesDispatcher.Instance.RemoveListener(PreferencesMsg.playerName, OnChangeName); + PreferencesDispatcher.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + HallManager.Instance.RemoveChangeGiftSwitch(InitView); + } + + #endregion + + private void InitView() + { + if (GameHelper.IsGiftSwitch()) + { + ui.switchgift.selectedIndex = 1; + } + else + { + ui.switchgift.selectedIndex = 0; + } + InitButtons(); + + SetUID(); + SetVersion(); + RefreshMusicUI(); + } + + private void InitButtons() + { + ui.btn_pri.btn_state.selectedIndex = ui.btn_pri._Btn_state__1; + ui.btn_terms.btn_state.selectedIndex = ui.btn_pri._Btn_state__2; + ui.btn_contact.btn_state.selectedIndex = ui.btn_pri._Btn_state__3; + + ui.btn_close.SetClick(OnCloseView); + ui.btn_music.SetClick(OnClickSetMusic); + ui.btn_sound.SetClick(OnClickSoundBtn); + ui.btn_contact.SetClick(OnClickContact); + ui.btn_record.SetClick(OnClickRedeem); + ui.btn_pri.SetClick(OnClickPrivacy); + ui.btn_terms.SetClick(OnClickTerms); + + ui.ExitBtn.SetClick(() => + { + CloseMenu(); + ShowScrews.Instance.TrackGameCompletion(false); + ShowScrews.Instance.ClearLevelData(); + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Open); + }); + ui.btn_restore.SetClick(() => + { + PurchasingManager.Instance.IosRestore((success, message) => + { + // Debug.Log("[barry] restore success message: " + message); + if (success) + { + // Debug.Log("[barry] restore success: " + success); + GameHelper.ShowTips("Restore Purchases Success!"); + SaveData.GetSaveobject().is_get_removead = success; + SaveData.GetSaveobject().is_get_battlepass = success; + SaveData.GetSaveobject().have_slot = success; + GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack); + GameDispatcher.Instance.Dispatch(GameMsg.BuyPack); + GameHelper.SetPayBox1(true); + GameHelper.SetPayBox2(true); + SaveData.saveDataFunc(); + } + else + { + // Debug.Log("[barry] restore failed: " + success); + GameHelper.ShowTips("There are no recoverable transactions"); + } + }); + CtrlCloseUI(); + }); + } + + private void ItemRenderer(int index, GObject item) + { + var btnLang = item as btn_lang; + var langVO = ConfigSystem.GetConfig().dataList[index]; + btnLang.text_lang.text = langVO.name; + btnLang.onClick.Set(() => + { + model.CurrLangId = langVO.id; + }); + if (langVO.id == model.CurrLangId) + { + btnLang.cont_btn.selectedIndex = btn_lang.Btn_select; + } + else + { + btnLang.cont_btn.selectedIndex = btn_lang.Btn_none; + } + } + + public override void OnSwitchLanguage() + { + base.OnSwitchLanguage(); + + SetVersion(); + SetUID(); + } + + private void SetUID() + { + ui.text_uid.text = $"UID:{GameHelper.GetLoginModel().uid}"; + } + + private void SetVersion() + { + ui.text_version.text = $"Version:{Application.version}"; + } + + private void CloseMenu(Action action = null) + { + CtrlCloseUI(); + action?.Invoke(); + } + + private void OnChangeName(ChangeValue obj) + { + } + + private void OnChangeAvatar(ChangeValue obj) + { + } + + private void OnCloseView() + { + CloseMenu(); + } + + private void OnClickRedeem() + { + CloseMenu(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MakeupRecordUI_Open); }); + } + + private void OnClickLanguage() + { + CloseMenu(); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LanguageWinUI_Open); + } + + private void OnClickAvatar() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open); + } + + private void OnClickProfile() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open); + } + + private void OnClickPrivacy() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open); + } + + private void OnClickTerms() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrivacyUI_Open, true); + } + + private void OnClickContact() + { + GameHelper.OpenEmail(); + //Application.OpenURL("https://official.nutboltparty.fun/"); + } + + private void OnClickSetMusic() + { + model.IsOpenMusic = !model.IsOpenMusic; + RefreshMusicUI(); + } + + private void OnClickSoundBtn() + { + model.IsOpenEffect = !model.IsOpenEffect; + RefreshMusicUI(); + } + + private void RefreshMusicUI() + { + ui.btn_music.cont_button.selectedIndex = + model.IsOpenMusic ? btn_switch_music.Button_on : btn_switch_music.Button_off; + ui.btn_sound.cont_button.selectedIndex = + model.IsOpenEffect ? btn_switch_sound.Button_on : btn_switch_sound.Button_off; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs.meta new file mode 100644 index 0000000..ed35f6e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0dee91b0289945b88b3c9216e12a7758 +timeCreated: 1676360265 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs new file mode 100644 index 0000000..aba8b8e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs @@ -0,0 +1,80 @@ + +namespace ScrewsMaster +{ + public class MenuUICtrl : BaseUICtrl + { + private MenuUI ui; + private MenuModel model; + + private uint openUIMsg = UICtrlMsg.MenuUI_Open; + private uint closeUIMsg = UICtrlMsg.MenuUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new MenuUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + + protected override void RemoveServerListener() + { + + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs.meta new file mode 100644 index 0000000..fe91f90 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Menu/MenuUICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bee553769448494792af2ea30744bfe1 +timeCreated: 1676360266 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading.meta new file mode 100644 index 0000000..0a88b33 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 33a14af05dea3134db279f8736ea1201 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs new file mode 100644 index 0000000..d832a94 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class NetLoadingCtrl : BaseCtrl + { + public static NetLoadingCtrl Instance { get; private set; } + + private NetLoadingModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs.meta new file mode 100644 index 0000000..3f9e7e0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6142496ef0da2704a863845e488d9bc2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs new file mode 100644 index 0000000..dff3037 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class NetLoadingModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs.meta new file mode 100644 index 0000000..f48e695 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d00cea29eaa93cf4aa58cd57918caf6c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs new file mode 100644 index 0000000..6c99e65 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs @@ -0,0 +1,62 @@ +namespace ScrewsMaster +{ + using FairyGUI; + + public class NetLoadingUI : BaseUI + { + private NetLoadingUICtrl ctrl; + private NetLoadingModel model; + private FGUI.SC005_NetIdle.com_Netidle ui; + + public NetLoadingUI(NetLoadingUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.NetLoadingUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SC005_NetIdle"; + uiInfo.assetName = "com_Netidle"; + uiInfo.layerType = UILayerType.Loading; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.SC005_NetIdle.com_Netidle; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + #endregion + + + private void InitView() + { + ui.com_net_loading.loader_gameicon.texture = + new NTexture(LoadKit.Instance.LoadSprite("Atlas.Game", "icon512")); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs.meta new file mode 100644 index 0000000..e633063 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78e634966cfe17a46a62a8ef22398204 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs new file mode 100644 index 0000000..5e4e739 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs @@ -0,0 +1,64 @@ +namespace ScrewsMaster +{ + public class NetLoadingUICtrl : BaseUICtrl + { + private NetLoadingUI ui; + private NetLoadingModel model; + + private uint openUIMsg = UICtrlMsg.NetLoadingUI_Open; + private uint closeUIMsg = UICtrlMsg.NetLoadingUI_Close; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new NetLoadingUI(this); + ui.Open(args); + } + else + { + ui.Display(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs.meta new file mode 100644 index 0000000..1ab50f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NetLoading/NetLoadingUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07064e3ce59096d43a4629e1e38a38ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask.meta new file mode 100644 index 0000000..68577f1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: db70f0801ba18ab449db90917899914b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs new file mode 100644 index 0000000..1bcaf8f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class NewTaskCtrl : BaseCtrl + { + public static NewTaskCtrl Instance { get; private set; } + + private NewTaskModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.NewTaskModel) as NewTaskModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs.meta new file mode 100644 index 0000000..8f579e3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d10e44523448459c81d72c5a7df0bee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs new file mode 100644 index 0000000..70d63c4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs @@ -0,0 +1,107 @@ +namespace ScrewsMaster +{ + public class NewTaskModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + + + + // private static string jsonFilePath = Path.Combine(Application.persistentDataPath, "taskrecord1.json"); + + // public static void saveRecord(List list) + // { + + // string save = JsonConvert.SerializeObject(list); + // Debug.Log(save); + // if (File.Exists(jsonFilePath)) File.Delete(jsonFilePath); + // File.WriteAllText(jsonFilePath, save); + + // } + // public static List getTaskRecord() + // { + // if (File.Exists(jsonFilePath)) + // { + // string jsonstr = File.ReadAllText(jsonFilePath); + + // Debug.Log("-------------------------"); + // Debug.Log(jsonstr); + // return JsonConvert.DeserializeObject>(jsonstr); + // //return JsonUtility.FromJson(json); + + // } + // else + // { + // Debug.Log("Data file not found!"); + // return new List(); + // } + // } + + // private static string jsonFilePath_time = Path.Combine(Application.persistentDataPath, "timerecord2.json"); + + // public static void saveTimeRecord(List list) + // { + + // string save = JsonConvert.SerializeObject(list); + // Debug.Log(save); + // if (File.Exists(jsonFilePath_time)) File.Delete(jsonFilePath_time); + // File.WriteAllText(jsonFilePath_time, save); + + // } + // public static List getTimeRecord() + // { + // if (File.Exists(jsonFilePath_time)) + // { + // string jsonstr = File.ReadAllText(jsonFilePath_time); + + // Debug.Log("-------------------------"); + // Debug.Log(jsonstr); + // return JsonConvert.DeserializeObject>(jsonstr); + // //return JsonUtility.FromJson(json); + + // } + // else + // { + // Debug.Log("Data file not found!"); + // return new List(); + // } + // } + } + +} diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs.meta new file mode 100644 index 0000000..a1679f9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a5db545b1de547e98645de6b166cae2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs new file mode 100644 index 0000000..8ef27f3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs @@ -0,0 +1,818 @@ +using System.Collections.Generic; +using UnityEngine; +using FairyGUI; +using FGUI.G009_video; +using DG.Tweening; +using System; +using System.Linq; +using Roy.Datas; + +namespace ScrewsMaster +{ + public class NewTaskUI : BaseUI + { + private NewTaskUICtrl ctrl; + private NewTaskModel model; + private com_newtask ui; + List passing_list = new List(); + List Durationtasks_list = new List(); + List Passportrewards_list = new List(); + private Vector2 start_pos; + private int reward_number; + private int task_id = 0; + private List recored_list; + private List time_recored_list; + private int reward_type = 0; + + private const float DefaultProgressWidth = 379; + private float _defaultTopBgHeight; + + + public NewTaskUI(NewTaskUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.NewTaskUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G009_video"; + uiInfo.assetName = "com_newtask"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + model = ModuleManager.Instance.GetModel(ModelConst.NewTaskModel) as NewTaskModel; + } + + protected override void OnClose() + { + GameHelper.showGameUI = true; + HallManager.Instance.UpdateSecondEvent -= upData; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G009_video.com_newtask; + } + + protected override void OnOpenBefore(object args) + { + _defaultTopBgHeight = ui.TopBg.height; + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.TopBox.y += Screen.safeArea.y; + ui.TopBg.height += Screen.safeArea.y; + ui.pass_com.TopBox.y += Screen.safeArea.y; + ui.pass_com.pass_list.height -= Screen.safeArea.y; + } + + if (GameHelper.getGameday() != DateTime.Now.Day) + { + PlayerPrefs.SetInt("_time", 0); + SaveData.GetSaveobject().time_task_record = new List(); + GameHelper.setGameday(); + } + + InitData(); + + HallManager.Instance.UpdateSecondEvent += upData; + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.GetTaskReward, getRewardSuccess); + // GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, OnGoldRefresh); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.GetTaskReward, getRewardSuccess); + // GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, OnGoldRefresh); + } + + private void OnGoldRefresh(object args) + { + SetMakeup(); + } + #endregion + + + void pay_success(object str) + { + string type = (string)str; + //2024年9月24日A面 包注释 + if (type == MaxPayManager.battle_pass) + { + OnPurchasePassSuccess(); + + } + } + + //初始化页面逻辑 + private void InitView() + { + ui.money.visible = GameHelper.IsGiftSwitch(); + + ui.pass_com.visible = true; + ui.task_list.visible = false; + ui.MiddleBg.visible = false; + ui.com_toptab.btn_battle.SetClick(() => { SwitchPage(0); }); + ui.com_toptab.btn_pass.SetClick(() => { SwitchPage(1); }); + ui.com_toptab.btn_time.SetClick(() => { SwitchPage(2); }); + ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Close); }); + + passing_list = ConfigSystem.GetConfig().dataList; + Durationtasks_list = ConfigSystem.GetConfig().dataList; + Passportrewards_list = ConfigSystem.GetConfig().dataList; + setPassCom(); + ui.com_toptab.red_0.visible = SaveData.battlepassred(); + ui.com_toptab.red_1.visible = SaveData.passtaskred(); + ui.com_toptab.red_2.visible = SaveData.timetaskred(); + ui.pass_com.btn_showtips.SetClick(() => + { + ui.pass_com.t0.Stop(); + ui.pass_com.t0.Play(); + }); + SetMakeup(); + + CheckState(); + } + + private void CheckState() + { + if (SaveData.battlepassred()) + { + SwitchPage(0); + return; + } + + if (SaveData.passtaskred()) + { + SwitchPage(1); + return; + } + + if (SaveData.timetaskred()) + { + SwitchPage(2); + return; + } + + SwitchPage(0); + + } + + private void SwitchPage(int page) + { + ui.com_toptab.tab.selectedIndex = page; + + var height = _defaultTopBgHeight; + switch (page) + { + case 0: + ui.pass_com.visible = true; + ui.MiddleBg.visible = false; + ui.task_list.visible = false; + height = _defaultTopBgHeight + Screen.safeArea.y; + break; + case 1: + sortTaskList(); + ui.pass_com.visible = false; + ui.MiddleBg.visible = true; + ui.task_list.visible = true; + break; + case 2: + sortTimeList(); + ui.pass_com.visible = false; + ui.MiddleBg.visible = true; + ui.task_list.visible = true; + break; + } + + ui.TopBg.height = height; + } + + void SetMakeup(object a = null) + { + ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString(); + ui.money.GetChild("number_text").text = GameHelper.Get102Str(GameHelper.Get102()); + + DOVirtual.Float(0, (float)GameHelper.Get102(), 1, + value => { ui.money.GetChild("number_text").text = GameHelper.Get102Str((decimal)value); }); + + if (GameHelper.IsGiftSwitch()) + { + + var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + + if (vo == null) + { + return; + } + var leftCash = (double)Math.Max(vo.item_need - GameHelper.Get102(), 0); + + (ui.money.GetChild("btn_cashout") as GButton).SetClickDownEffect(0.8f, 1); + ui.money.GetChild("btn_cashout").SetClick(() => + { + // if (GameHelper.CanGuide() && !GuideCtrl.Instance.IsFinishGuide(1)) + // { + // GuideCtrl.Instance.Dispatch("ClickButton"); + // ui.com_box.finger_place.visible = false; + // } + GameHelper.showGameUI = false; + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, makeupTaskData); + //CtrlCloseUI(); + }); + } + } + + void upData() + { + ui.pass_com.remain_time.text = CommonHelper.TimeFormat( + SaveData.GetSaveobject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600 - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Day); + + if ((SaveData.GetSaveobject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime()) + { + SaveData.GetSaveobject().battle_pass_time = (int)GameHelper.GetNowTime(); + SaveData.GetSaveobject().battle_pass_freelist.Clear(); + SaveData.GetSaveobject().battle_pass_paylist.Clear(); + SaveData.GetSaveobject().is_get_battlepass = false; + GameHelper.ResetGameExp(); + SaveData.saveDataFunc(); + setPassCom(); + } + + } + void setPassCom() + { + if ((SaveData.GetSaveobject().battle_pass_time + Passportrewards_list[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime()) + { + SaveData.GetSaveobject().battle_pass_time = (int)GameHelper.GetNowTime(); + GameHelper.ResetGameExp(); + SaveData.GetSaveobject().battle_pass_freelist.Clear(); + SaveData.GetSaveobject().battle_pass_paylist.Clear(); + SaveData.GetSaveobject().is_get_battlepass = false; + SaveData.saveDataFunc(); + } + upData(); + ui.pass_com.pass_list.itemRenderer = battle_itemRender; + // ui.pass_com.pass_list.numItems = Passportrewards_list.Count + 1; + + ui.pass_com.pass_list.numItems = Passportrewards_list.Count; + + ui.pass_com.now_level.text = GameHelper.GetBattleLv().ToString(); + if (GameHelper.GetBattleLv() >= Passportrewards_list.Count) + { + ui.pass_com.now_exp.text = GameHelper.GetGameExp().ToString(); + ui.pass_com.progress.width = 328; + } + else + { + ui.pass_com.now_exp.text = GameHelper.GetGameExp() + "/" + Passportrewards_list[GameHelper.GetBattleLv()].Eliminating_quantity; + ui.pass_com.progress.width = Mathf.Min((float)GameHelper.GetGameExp() / Passportrewards_list[GameHelper.GetBattleLv()].Eliminating_quantity, 1) * 328; + } + + + ui.pass_com.btn_pay.visible = !SaveData.GetSaveobject().is_get_battlepass; + ui.pass_com.btn_pay.SetClick(OnClickBuyPass); + + + } + + + void setItemUrl(GLoader loader, int urltype) + { + if (urltype == 0) loader.url = "ui://G009_video/master_pass_jbd2"; + else if (urltype == 4) loader.url = "ui://G009_video/master_pass_jbd1"; + else if (urltype == 1) loader.url = "ui://G009_video/yxjm_bottom_add_hole"; + else if (urltype == 2) loader.url = "ui://G009_video/yxjm_bottom_merge_box"; + else if (urltype == 3) loader.url = "ui://G009_video/yxjm_bottom_clear"; + } + void seItemClick(com_passreward item, int number, int type) + { + var start = GameHelper.GetUICenterPosition(item); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + + if (type == 0) + { + reward_data temp = new reward_data() { start = start, end = end, change = number, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddGoldNumber(number); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + } + else + { + + GameHelper.AddItemNumber((ItemEnum)type - 1, number); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + + // GameHelper.ShowTips("Received successfully"); + } + + ui.pass_com.pass_list.numItems = Passportrewards_list.Count; + ui.com_toptab.red_0.visible = SaveData.battlepassred(); + } + + void battle_itemRender(int index, GObject obj) + { + index = index + 1; + com_passitem item = (com_passitem)obj; + + item.index_text.text = index.ToString(); + item.free_item.type.selectedIndex = 0; + item.pay_item.type.selectedIndex = 1; + + var passportReward = Passportrewards_list[index - 1]; + item.free_item.number_text.text = "x" + passportReward.Free_rewards_num; + item.pay_item.number_text.text = "x" + passportReward.Paid_rewards_num; + + setItemUrl(item.free_item.item_loader, + passportReward.Free_rewards_type == 0 + ? 0 + : passportReward.Paid_rewards_type); + + setItemUrl(item.pay_item.item_loader, + passportReward.Paid_rewards_type == 0 + ? 4 + : passportReward.Paid_rewards_type); + + item.full.selectedIndex = com_passitem.Full_full; + + if (index == 1) + { + item.state.selectedIndex = 0; + + if (_passLevel > 0) + { + item.progress_0_top.height = 135; + + Debug.Log((((float)(GameHelper.GetGameExp() - Passportrewards_list[0].Eliminating_quantity) / ((Passportrewards_list[1].Eliminating_quantity - Passportrewards_list[0].Eliminating_quantity)))) * 2); + if (((float)(GameHelper.GetGameExp() - Passportrewards_list[0].Eliminating_quantity) / (Passportrewards_list[1].Eliminating_quantity - Passportrewards_list[0].Eliminating_quantity)) > 0.5) + { + item.progress_0_down.height = 175; + } + else + { + + item.progress_0_down.height = (((float)(GameHelper.GetGameExp() - Passportrewards_list[0].Eliminating_quantity) / ((Passportrewards_list[1].Eliminating_quantity - Passportrewards_list[0].Eliminating_quantity)))) * 2 * 175; + } + + } + else + { + item.progress_0_top.height = (float)GameHelper.GetGameExp() / Passportrewards_list[0].Eliminating_quantity * 135; + item.progress_0_down.height = 0; + + } + } + else if (index == Passportrewards_list.Count) + { + item.state.selectedIndex = 2; + + + if (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (passportReward.Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) > 0.5) + { + float height = (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (passportReward.Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) - 0.5f) * 2 * 167; + if (height > 167) height = 167; + item.progress_2_top.height = height; + } + else item.progress_2_top.height = 0; + + } + else + { + item.state.selectedIndex = 1; + + if (_passLevel >= index) + { + item.progress_1_top.height = 167; + } + else + { + if (_passLevel == (index - 1)) + { + + if (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (passportReward.Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) > 0.5) + { + float height = (((float)(GameHelper.GetGameExp() - Passportrewards_list[index - 2].Eliminating_quantity) / (passportReward.Eliminating_quantity - Passportrewards_list[index - 2].Eliminating_quantity)) - 0.5f) * 2 * 167; + if (height > 167) height = 167; + item.progress_1_top.height = height; + } + else item.progress_1_top.height = 0; + + + } + else + { + item.progress_1_top.height = 0; + } + } + + if (_passLevel == index) + { + Debug.Log("-----------------"); + Debug.Log(((float)(GameHelper.GetGameExp() - passportReward.Eliminating_quantity) / (Passportrewards_list[index].Eliminating_quantity - passportReward.Eliminating_quantity))); + if (((float)(GameHelper.GetGameExp() - passportReward.Eliminating_quantity) / (Passportrewards_list[index].Eliminating_quantity - passportReward.Eliminating_quantity)) <= 0.5) + { + float height = (((float)(GameHelper.GetGameExp() - passportReward.Eliminating_quantity) / (Passportrewards_list[index].Eliminating_quantity - passportReward.Eliminating_quantity))) * 2 * 167; + if (height > 167) height = 167; + item.progress_1_down.height = height; + } + else + { + item.progress_1_down.height = 167; + } + + } + else + { + if (_passLevel > index) item.progress_1_down.height = 167; + else item.progress_1_down.height = 0; + } + } + + InitItemState(index, item); + item.free_item.SetClick(() => { OnClickFullItemButton(index, item); }); + item.pay_item.SetClick(() => { OnClickPayItemButton(index, item); }); + } + + #region 新版代码 + + private List _freeList; + private List _payList; + private int _passLevel; + private void InitData() + { + _passLevel = GameHelper.GetBattleLv(); + _freeList = SaveData.GetSaveobject().battle_pass_freelist; + _payList = SaveData.GetSaveobject().battle_pass_paylist; + + time_recored_list = SaveData.GetSaveobject().time_task_record; + recored_list = SaveData.GetSaveobject().pass_task_record; + } + + private void InitItemState(int index, com_passitem item) + { + int fullItemState; + int payItemState; + + // item.Mask.visible = index > _passLevel; + + if (index <= _passLevel) //等级达到了 + { + fullItemState = _freeList.Contains(index) ? 2 : 1; + + if (!SaveData.GetSaveobject().is_get_battlepass)//是否有通行证 + { + payItemState = 4; + } + else + { + payItemState = _payList.Contains(index) ? 2 : 1; + } + } + else + { + //等级还没到 + fullItemState = 3; + payItemState = 3; + } + + + item.free_item.state.selectedIndex = fullItemState; + item.pay_item.state.selectedIndex = payItemState; + } + + private void OnClickFullItemButton(int index, com_passitem item) + { + if (index <= _passLevel) + { + if (!_freeList.Contains(index)) + { + _freeList.Add(index); + SaveData.saveDataFunc(); + GameHelper.ShowTips("Successfully claimed"); + seItemClick(item.free_item, Passportrewards_list[index - 1].Free_rewards_num, Passportrewards_list[index - 1].Free_rewards_type); + } + } + else + { + GameHelper.ShowTips("Receiving level not reached"); + } + } + + private void OnClickPayItemButton(int index, com_passitem item) + { + if (index <= _passLevel) + { + if (!SaveData.GetSaveobject().is_get_battlepass) + { + if (GameHelper.IsGiftSwitch()) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open); + } + return; + } + + if (!_payList.Contains(index)) + { + _payList.Add(index); + SaveData.saveDataFunc(); + GameHelper.ShowTips("Successfully claimed"); + seItemClick(item.pay_item, Passportrewards_list[index - 1].Paid_rewards_num, Passportrewards_list[index - 1].Paid_rewards_type); + } + } + else + { + GameHelper.ShowTips("Receiving level not reached"); + } + } + + private void OnClickBuyPass() + { + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PassunlockUI_Open); + + } + + private void OnPurchasePassSuccess() + { + SaveData.GetSaveobject().is_get_battlepass = true; + int gold = 0; + int out_ = 0; + int back_ = 0; + int refresh_ = 0; + + for (int i = 0; i < Passportrewards_list.Count; i++) + { + if (_passLevel > i) + { + switch (Passportrewards_list[i].Paid_rewards_type) + { + case 0: + gold += Passportrewards_list[i].Paid_rewards_num; + break; + case 1: + out_ += Passportrewards_list[i].Paid_rewards_num; + break; + case 2: + back_ += Passportrewards_list[i].Paid_rewards_num; + break; + case 3: + refresh_ += Passportrewards_list[i].Paid_rewards_num; + break; + } + + SaveData.GetSaveobject().battle_pass_paylist.Add(i + 1); + } + else break; + } + + if (gold > 0) + { + var start = GameHelper.GetUICenterPosition(ui.pass_com.btn_pay); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + + reward_data temp = new reward_data() { start = start, end = end, change = gold, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddGoldNumber(gold); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + + } + GameHelper.AddItemNumber(ItemEnum.AddHole, out_); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + ui.pass_com.pass_list.numItems = Passportrewards_list.Count; + ui.pass_com.btn_pay.visible = false; + SaveData.saveDataFunc(); + } + #endregion + + + void sortTaskList() + { + // recored_list = NewTaskModel.getTaskRecord(); + + List templist = new List(); + passing_list.Sort((x, y) => x.id - y.id); + for (int i = 0; i < passing_list.Count; i++) + { + if (recored_list.Contains(passing_list[i].id)) + { + passing_list[i].is_get = true; + templist.Add(passing_list[i]); + passing_list.Remove(passing_list[i]); + i--; + } + } + passing_list.AddRange(templist); + + ui.task_list.itemRenderer = passingTaskrRender; + ui.task_list.numItems = passing_list.Count; + ui.com_toptab.red_1.visible = SaveData.passtaskred(); + } + void sortTimeList() + { + //time_recored_list = NewTaskModel.getTimeRecord(); + List templist = new List(); + Durationtasks_list.Sort((x, y) => x.id - y.id); + + for (int i = 0; i < Durationtasks_list.Count; i++) + { + if (time_recored_list.Contains(Durationtasks_list[i].id)) + { + Durationtasks_list[i].is_get = true; + templist.Add(Durationtasks_list[i]); + Durationtasks_list.Remove(Durationtasks_list[i]); + i--; + } + } + Durationtasks_list.AddRange(templist); + + ui.task_list.itemRenderer = durationRender; + ui.task_list.numItems = Durationtasks_list.Count; + ui.com_toptab.red_2.visible = SaveData.timetaskred(); + } + + void passingTaskrRender(int index, GObject obj) + { + task_item item = (task_item)obj; + // item.content_text.text=string .Format(passing_list[index].text_read,passing_list[index].tol_num); + + item.content_text.text = passing_list[index].text_read; + item.number_text.text = "x" + passing_list[index].reward_num; + + item.ez_img.visible = item.text_ez.visible = false; + item.diff_img.visible = item.text_diff.visible = false; + // if (passing_list[index].id % 3 == 0) + // { + // item.ez_img.visible = item.text_ez.visible = false; + // item.diff_img.visible = item.text_diff.visible = true; + // } + // else + // { + // item.ez_img.visible = item.text_ez.visible = true; + // item.diff_img.visible = item.text_diff.visible = false; + // } + if ((GameHelper.GetLevel() - 1) < passing_list[index].tol_num) + { + item.progress_text.text = (GameHelper.GetLevel() - 1) + "/" + passing_list[index].tol_num; + item.progress.width = DefaultProgressWidth * Math.Min((float)(GameHelper.GetLevel() - 1) / passing_list[index].tol_num, 1); + item.btn_get.state.selectedIndex = 1; + item.btn_get.progress_text.text = "To complete"; + item.btn_get.SetClick(() => + { + + }); + } + else + { + item.progress_text.text = passing_list[index].tol_num + "/" + passing_list[index].tol_num; + item.progress.width = DefaultProgressWidth; + + item.btn_get.touchable = !passing_list[index].is_get; + if (!passing_list[index].is_get) + { + item.btn_get.state.selectedIndex = 0; + item.btn_get.SetClick(() => + { + start_pos = GameHelper.GetUICenterPosition(item.gold_img); + reward_number = passing_list[index].reward_num; + task_id = passing_list[index].id; + reward_type = 1; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, passing_list[index].reward_num); + }); + item.btn_get.progress_text.text = "Claim"; + } + else + { + item.btn_get.progress_text.text = "Claimed"; + item.btn_get.state.selectedIndex = 1; + } + + } + } + void getRewardSuccess(object a = null) + { + + if ((bool)a) reward_number *= 2; + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start_pos, end = end, change = reward_number, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddGoldNumber(reward_number); + + if (reward_type == 1) + { + recored_list.Add(task_id); + sortTaskList(); + } + else + { + time_recored_list.Add(task_id); + sortTimeList(); + } + + SaveData.saveDataFunc(); + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.GetGoldNumber(), 1f, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + GameHelper.AddInterAdNumber(); + + }); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + + void durationRender(int index, GObject obj) + { + task_item item = (task_item)obj; + + item.content_text.text = Durationtasks_list[index].text_read; + item.number_text.text = "x" + Durationtasks_list[index].reward_num; + + item.ez_img.visible = item.text_ez.visible = false; + item.diff_img.visible = item.text_diff.visible = false; + + if ((GameHelper.getGameTime() / 60) < Durationtasks_list[index].tol_num) + { + item.progress_text.text = Math.Round((float)GameHelper.getGameTime() / 60, 2) + "/" + Durationtasks_list[index].tol_num; + item.progress.width = DefaultProgressWidth * + Math.Min((float)GameHelper.getGameTime() / 60 / Durationtasks_list[index].tol_num, + 1); + item.btn_get.state.selectedIndex = 1; + item.btn_get.SetClick(() => + { + + }); + item.btn_get.progress_text.text = "To complete"; + } + else + { + item.progress_text.text = Durationtasks_list[index].tol_num + "/" + Durationtasks_list[index].tol_num; + item.progress.width = DefaultProgressWidth; + item.btn_get.touchable = !Durationtasks_list[index].is_get; + if (!Durationtasks_list[index].is_get) + { + item.btn_get.state.selectedIndex = 0; + item.btn_get.SetClick(() => + { + start_pos = GameHelper.GetUICenterPosition(item.gold_img); + reward_number = Durationtasks_list[index].reward_num; + task_id = Durationtasks_list[index].id; + reward_type = 2; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GetTaskRewardUI_Open, Durationtasks_list[index].reward_num); + }); + item.btn_get.progress_text.text = "Claim"; + } + else + { + item.btn_get.progress_text.text = "Claimed"; + item.btn_get.state.selectedIndex = 1; + } + + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs.meta new file mode 100644 index 0000000..88b2030 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c5e4db4d12a94c1aaecba7ecf0b768c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs new file mode 100644 index 0000000..2b8043e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class NewTaskUICtrl : BaseUICtrl + { + private NewTaskUI ui; + private NewTaskModel model; + + private uint openUIMsg = UICtrlMsg.NewTaskUI_Open; + private uint closeUIMsg = UICtrlMsg.NewTaskUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.NewTaskModel) as NewTaskModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new NewTaskUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs.meta new file mode 100644 index 0000000..989156d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/NewTask/NewTaskUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b25d00163eecd4ac8aed9dc94897ee9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg.meta new file mode 100644 index 0000000..75ae686 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 265c5520e8df2c148b28e67aa7c46d9d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs new file mode 100644 index 0000000..8b58b36 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class OpenBgCtrl : BaseCtrl + { + public static OpenBgCtrl Instance { get; private set; } + + private OpenBgModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs.meta new file mode 100644 index 0000000..93cdeef --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d93c061f221d2524495f19969909b20e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs new file mode 100644 index 0000000..8007660 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs @@ -0,0 +1,17 @@ +namespace ScrewsMaster +{ + public class OpenBgModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs.meta new file mode 100644 index 0000000..ea21e67 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e41bf58566c9474418dc04b26ce9d9ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs new file mode 100644 index 0000000..4f12b0c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs @@ -0,0 +1,78 @@ +using FairyGUI; +using Spine.Unity; +using System; + +namespace ScrewsMaster +{ + public class OpenBgUI : BaseUI + { + private OpenBgUICtrl ctrl; + private OpenBgModel model; + private FGUI.A001_bigImg.com_loadingbg ui; + private Action closeCallback; + + public OpenBgUI(OpenBgUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.OpenBgUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "A001_bigImg"; + uiInfo.assetName = "com_loadingbg"; + uiInfo.layerType = UILayerType.Background; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + CommonHelper.FadeOut(ui); + } + + protected override void AddListener() + { + UICtrlDispatcher.Instance.AddListener(UICtrlMsg.GameLoginUI_Open, OpenLogin); + } + + protected override void RemoveListener() + { + UICtrlDispatcher.Instance.RemoveListener(UICtrlMsg.GameLoginUI_Open, OpenLogin); + } + + private void OpenLogin(object args) + { + // ui.icon_logo.TweenFade(0, 0.1f); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.A001_bigImg.com_loadingbg; + } + + protected override void OnOpenBefore(object args) + { + //var sk = FXManager.Instance.SetFx(baseUI.GetChild("bg_parent") as GGraph, Fx_Type.fx_login, ref closeCallback); + //sk.state.SetAnimation(0, "animation", true); + var bg = FXManager.Instance.SetFx(ui.bg_parent, Fx_Type.fx_title, ref closeCallback); + bg.state.SetAnimation(0, "animation", true); + var light = FXManager.Instance.SetFx(ui.light_parent, Fx_Type.fx_title_light, ref closeCallback); + light.state.SetAnimation(0, "animation", true); + } + + protected override void OnOpen(object args) + { + // CommonHelper.FadeIn(ui); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs.meta new file mode 100644 index 0000000..b159486 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 599f5082a5c3c754db1a8fd910cca80a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs new file mode 100644 index 0000000..3f56647 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class OpenBgUICtrl : BaseUICtrl + { + private OpenBgUI ui; + private OpenBgModel model; + + private uint openUIMsg = UICtrlMsg.OpenBgUI_Open; + private uint closeUIMsg = UICtrlMsg.OpenBgUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new OpenBgUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs.meta new file mode 100644 index 0000000..b920e43 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenBg/OpenBgUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2818baa7360f3b449a73a290dc9594c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame.meta new file mode 100644 index 0000000..07d4f9f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 29e89f5ab120c944eb04ca465b81ad37 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs new file mode 100644 index 0000000..5a6cffb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class OpenGameCtrl : BaseCtrl + { + public static OpenGameCtrl Instance { get; private set; } + + private OpenGameModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.OpenGameModel) as OpenGameModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs.meta new file mode 100644 index 0000000..a794e29 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 619b238dcaf0147a28182583aa7f4f0b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs new file mode 100644 index 0000000..76e0b82 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class OpenGameModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + #endregion + + #region 读取数据 + // protected override void OnReadData() + // { + // } + #endregion + + #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs.meta new file mode 100644 index 0000000..fa1802f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e175d106ca664d5bb372aa27dbb9be4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs new file mode 100644 index 0000000..3615e24 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs @@ -0,0 +1,111 @@ +using System; +using DG.Tweening; +using Spine.Unity; + +namespace ScrewsMaster +{ + public class OpenGameUI : BaseUI + { + private OpenGameUICtrl ctrl; + private OpenGameModel model; + private FGUI.G003_play.com_opengame ui; + + public OpenGameUI(OpenGameUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.OpenGameUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G003_play"; + uiInfo.assetName = "com_opengame"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.OpenGameModel) as OpenGameModel; + } + + protected override void OnClose() + { + + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G003_play.com_opengame; + } + + protected override void OnOpenBefore(object args) + { + // DOVirtual.DelayedCall(0.7f, () => { GameDispatcher.Instance.Dispatch(GameMsg.reset_game, args); }); + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + private Action closeCallback; + //初始化页面逻辑 + private void InitView() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Open); + ui.GoWordart.visible = ShowScrews.Instance.gameMode == 1; + ui.LevelWordart.visible = ShowScrews.Instance.gameMode != 1; + ui.lv_text.visible = ShowScrews.Instance.gameMode != 1; + ui.lv_text.text = GameHelper.GetLevel().ToString(); + if (GameHelper.IsShowLevelTips()) + { + DOVirtual.DelayedCall(0.2f, () => + { + ui.tips_node.visible = true; + var meteor1 = FXManager.Instance.SetFx(ui.tips_node, Fx_Type.fx_tips, ref closeCallback); + meteor1.state.SetAnimation(0, "animation", false); + // meteor1.state.Complete += (a) => + // { + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Close); + // }; + }); + } + // ui.t0.Play(() => + // { + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Close); + // }); + } + + public void PlayAnim() + { + ui.t0.Play(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Close); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MaskUI_Close); + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs.meta new file mode 100644 index 0000000..615d2b8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0726da6c334349c994d257574585439 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs new file mode 100644 index 0000000..d82d269 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs @@ -0,0 +1,80 @@ +namespace ScrewsMaster +{ + public class OpenGameUICtrl : BaseUICtrl + { + private OpenGameUI ui; + private OpenGameModel model; + + private uint openUIMsg = UICtrlMsg.OpenGameUI_Open; + private uint closeUIMsg = UICtrlMsg.OpenGameUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.OpenGameModel) as OpenGameModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new OpenGameUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + public void PlayAnim(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.PlayAnim(); + } + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + uiCtrlDispatcher.AddListener(UICtrlMsg.OpenGameUI_PlayAnim, PlayAnim); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + uiCtrlDispatcher.RemoveListener(UICtrlMsg.OpenGameUI_PlayAnim, PlayAnim); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs.meta new file mode 100644 index 0000000..8c0e366 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/OpenGame/OpenGameUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f819527a7b9184743b3fbc1d52f7c307 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward.meta new file mode 100644 index 0000000..5f1432c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b030db855ecf4736830f6180290e3582 +timeCreated: 1729595784 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs new file mode 100644 index 0000000..4117888 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class PackRewardCtrl : BaseCtrl + { + public static PackRewardCtrl Instance { get; private set; } + + private PackRewardModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PackrewardModel) as PackrewardModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs.meta new file mode 100644 index 0000000..5b19ed6 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6716776f97890437d8a618c997ea689d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs new file mode 100644 index 0000000..015afaf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class PackRewardModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs.meta new file mode 100644 index 0000000..921ec51 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f3f1bbd4dedd499bb4917a0a83b8d09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs new file mode 100644 index 0000000..6b5a9fa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs @@ -0,0 +1,504 @@ +using System; +using System.Collections.Generic; +using DG.Tweening; +using FairyGUI; +using FGUI.G008_reward; +using UnityEngine; + +namespace ScrewsMaster +{ + public class PackRewardUI : BaseUI + { + private PackRewardUICtrl ctrl; + private PackRewardModel model; + private FGUI.G008_reward.com_packreward ui; + + private int _packPrice; + private int _removeADPrice; + private GTextField _packCooldownText; + private GTextField _removeADCooldownText; + private pack_panel _panel; + private bool _inAdRewardCooldown; + + public PackRewardUI(PackRewardUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PackrewardUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_packreward"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PackrewardModel) as PackrewardModel; + } + + protected override void OnClose() + { + + HallManager.Instance.UpdateSecondEvent -= UpdateButtonState; + GameHelper.showGameUI = true; + GameDispatcher.Instance.Dispatch(GameMsg.pack_close); + int three_gift_got_index = SaveData.GetSaveobject().three_gift_got_index; + if (isAutoPop && (three_gift_got_index <= (int)rewardState.day3)) + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open); + } + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_packreward; + } + + private bool isAutoPop = false; + protected override void OnOpenBefore(object args) + { + + ui.panel_parent.panel.height += GRoot.inst.height * 0.25f; + + bool need_scroll = false; + PackRewardData Datas = args as PackRewardData; + if (args != null) + { + Datas = args as PackRewardData; + need_scroll = Datas.isNeedScroll; + isAutoPop = Datas.isAutoPop; + } + if (need_scroll) ui.panel_parent.scrollPane.ScrollDown(300, false); + + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.remove_ad_show, 1); + + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pack_show, 1); + + ui.gold.GetChild("number_text").text = GameHelper.GetGoldNumber().ToString(); + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.AdRewardClaimed, OnUpdateAdReward); + GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnUpdateAdReward); + GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward); + } + + private void OnUpdateAdReward(object data) + { + UpdateAdsText(); + UpdateButtonState(); + } + #endregion + void pay_success(object str) + { + string type = (string)str; + if (type == MaxPayManager.pack_reward) + { + GameHelper.AddGoldNumber(gold_num); + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + + var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + + reward_data temp = new reward_data() { start = start, end = end, change = list[0].coins_quantity, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + + SaveData.GetSaveobject().is_get_packreward = true; + + SaveData.saveDataFunc(); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyPack); + InitView(); + } + if (type == MaxPayManager.remove_ad) + { + GameHelper.AddGoldNumber(_removeAdAddGoldNum); + var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum2); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start, end = end, change = _removeAdAddGoldNum, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close); + + SaveData.GetSaveobject().is_get_removead = true; + SaveData.saveDataFunc(); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack); + InitView(); + + + } + } + //初始化页面逻辑 + private int gold_num = 300; + private int _removeAdAddGoldNum; + private int back_num = 1; + private int out_num = 1; + private int refresh_num = 1; + private List list; + private void InitView() + { + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.gold.y += Screen.safeArea.y; + } + + _panel = ui.panel_parent.panel; + _panel.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1; + list = ConfigSystem.GetConfig().dataList; + + gold_num = list[0].coins_quantity; + back_num = list[0].props_quantity[1]; + out_num = list[0].props_quantity[0]; + refresh_num = list[0].props_quantity[2]; + + + + _packPrice = (int)list[0].Paid_price; + _removeADPrice = (int)list[1].Paid_price; + + _panel.btn_close0.SetClick(CtrlCloseUI); + _panel.btn_close1.SetClick(CtrlCloseUI); + _panel.text_goldnum.text = "x" + gold_num; + _panel.text_backnum1.text = "x" + back_num; + _panel.text_outnum.text = "x" + out_num; + _panel.text_refreshnum.text = "x" + refresh_num; + + _removeAdAddGoldNum = list[1].coins_quantity; + ui.panel_parent.panel.text_goldnum2.text = "x" + list[1].coins_quantity; + + _panel.btn_buyPackClaim.SetClick(OnClickBuyPack); + _panel.btn_buypack.SetClick(OnClickBuyPackWatchAdsBtn); + _panel.btn_RemoveAdClaim.SetClick(OnClickBuyRemoveAd); + _panel.btn_buyremovead.SetClick(OnClickBuyRemoveAdWatchAdsBtn); + + UpdateAdsText(); + HallManager.Instance.UpdateSecondEvent += UpdateButtonState; + UpdateButtonState(); + } + + private void UpdateAdsText() + { + ui.panel_parent.panel.text_hasAdCount.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}"; + ui.panel_parent.panel.text_needAdCount1.text = $"Need ADs:{_packPrice}"; + ui.panel_parent.panel.text_needAdCount2.text = $"Need ADs:{_removeADPrice}"; + } + + private void UpdateButtonState() + { + _inAdRewardCooldown = GameHelper.InAdRewardCooldown(); + + UpdateBtnBuyPackState(); + UpdateBtnBuyRemoveAdState(); + } + + private void UpdateBtnBuyPackState() + { + + if (SaveData.GetSaveobject().is_get_packreward) + { + _panel.btn_buyPackClaim.grayed = true; + _panel.btn_buyPackClaim.visible = true; + _panel.btn_buypack.visible = false; + _panel.btn_max_pack.visible = false; + return; + } + + if (!GameHelper.IsAdModelOfPay()) + { + _panel.btn_buyPackClaim.visible = false; + decimal price_pack = (decimal)list[0].Paid_price2; + ui.panel_parent.panel.btn_max_pack.title = "$ "+price_pack; + bool is_get = SaveData.GetSaveobject().is_get_packreward; + if (is_get) + { + ui.panel_parent.panel.btn_max_pack.enabled = false; + ui.panel_parent.panel.btn_max_pack.SetClick(() => { }); + } + else + { + ui.panel_parent.panel.btn_max_pack.SetClick(() => + { + ApplePayClass maxPayData = new ApplePayClass + { + amount = (int)Math.Round(price_pack * 100), + sku = MaxPayManager.pack_reward, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + } + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (_panel.btn_max_pack.GetChild("img_saveingpot") as GImage).visible = true; + } + else + { + _panel.btn_buyPackClaim.visible = GameHelper.CheckAdWatchCount(_packPrice); + _panel.btn_buypack.visible = !_panel.btn_buyPackClaim.visible; + + _panel.btn_buypack.grayed = _inAdRewardCooldown; + _panel.btn_buypack.touchable = !_inAdRewardCooldown; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (_panel.btn_buypack.GetChild("img_saveingpot") as GImage).visible = true; + + if (_packCooldownText == null && _panel.btn_buypack.GetChild("text_cooldown") is GTextField packCooldownText) + { + _packCooldownText = packCooldownText; + } + + if (_packCooldownText != null) + { + _packCooldownText.visible = _inAdRewardCooldown; + + if (_inAdRewardCooldown) + { + _packCooldownText.text = CommonHelper.TimeFormat( + (int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Hour); + } + } + + _panel.btn_buypack.GetChild("title").visible = !_inAdRewardCooldown; + _panel.btn_buypack.GetChild("icon").visible = !_inAdRewardCooldown; + } + + } + private void UpdateBtnBuyRemoveAdState() + { + if (SaveData.GetSaveobject().is_get_removead) + { + _panel.btn_RemoveAdClaim.grayed = true; + _panel.btn_RemoveAdClaim.visible = true; + _panel.btn_buyremovead.visible = false; + _panel.btn_max_remove.visible = false; + return; + } + if (!GameHelper.IsAdModelOfPay()) + { + _panel.btn_RemoveAdClaim.visible = false; + decimal price_remove = (decimal)list[1].Paid_price2; + ui.panel_parent.panel.btn_max_remove.title = "$ "+price_remove; + bool is_get1 = SaveData.GetSaveobject().is_get_removead; + if (is_get1) + { + ui.panel_parent.panel.btn_max_remove.enabled = false; + ui.panel_parent.panel.btn_max_remove.SetClick(() => { }); + } + else + { + ui.panel_parent.panel.btn_max_remove.SetClick(() => + { + ApplePayClass maxPayData = new ApplePayClass + { + amount = (int)Math.Round(price_remove * 100), + sku = MaxPayManager.remove_ad, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + } + + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (_panel.btn_max_remove.GetChild("img_saveingpot") as GImage).visible = true; + + } + else + { + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (_panel.btn_buyremovead.GetChild("img_saveingpot") as GImage).visible = true; + _panel.btn_RemoveAdClaim.visible = GameHelper.CheckAdWatchCount(_removeADPrice); + _panel.btn_buyremovead.visible = !_panel.btn_RemoveAdClaim.visible; + _panel.btn_buyremovead.grayed = _inAdRewardCooldown; + _panel.btn_buyremovead.touchable = !_inAdRewardCooldown; + if (_removeADCooldownText == null && _panel.btn_buyremovead.GetChild("text_cooldown") is GTextField removeADCooldownText) + { + _removeADCooldownText = removeADCooldownText; + } + + if (_removeADCooldownText != null) + { + _removeADCooldownText.visible = _inAdRewardCooldown; + + if (_inAdRewardCooldown) + { + _removeADCooldownText.text = CommonHelper.TimeFormat( + (int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Hour); + } + } + + _panel.btn_buyremovead.GetChild("title").visible = !_inAdRewardCooldown; + _panel.btn_buyremovead.GetChild("icon").visible = !_inAdRewardCooldown; + } + + } + + private void OnClickBuyPackWatchAdsBtn() + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, + BuriedPointEvent.first_pack_click, 1); + + GameHelper.ShowVideoAd("BuyPack", success => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + } + private void OnClickBuyRemoveAdWatchAdsBtn() + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, + BuriedPointEvent.remove_ad_click, 1); + GameHelper.ShowVideoAd("BuyRemoveAd", success => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + } + + private void OnClickBuyPack() + { + + if (SaveData.GetSaveobject().is_get_packreward) return; + + if (GameHelper.CheckAdWatchCount((int)list[0].Paid_price)) + { + GameHelper.AddAdWatchCount(-(int)list[0].Paid_price); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + return; + } + + GameHelper.AddGoldNumber(gold_num); + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + + var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + + reward_data temp = new reward_data() { start = start, end = end, change = list[0].coins_quantity, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + + SaveData.GetSaveobject().is_get_packreward = true; + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, + BuriedPointEvent.first_pack_success, 1); + SaveData.saveDataFunc(); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyPack); + InitView(); + } + + private void OnClickBuyRemoveAd() + { + // GooglePayClass info = new GooglePayClass() + // { + // transactionId = "", + // amount = (int)(list[1].Paid_price * 100), + // sku = GooglePaymentManager.remove_ad, + // currency = "USD" + // }; + // + // GooglePaymentManager.Instance.BuyProduct(GooglePaymentManager.remove_ad, info); + if (SaveData.GetSaveobject().is_get_removead) return; + + if (GameHelper.CheckAdWatchCount((int)list[1].Paid_price)) + { + GameHelper.AddAdWatchCount(-(int)list[1].Paid_price); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + return; + } + + GameHelper.AddGoldNumber(_removeAdAddGoldNum); + var start = GameHelper.GetUICenterPosition(ui.panel_parent.panel.text_goldnum2); + var end = GameHelper.GetUICenterPosition(ui.gold.GetChild("number_text")); + + reward_data temp = new reward_data() { start = start, end = end, change = _removeAdAddGoldNum, type = 101 }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1, + value => { ui.gold.GetChild("number_text").text = ((int)value).ToString(); }); + }); + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close); + + SaveData.GetSaveobject().is_get_removead = true; + SaveData.saveDataFunc(); + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, + BuriedPointEvent.remove_ad_success, 1); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack); + InitView(); + } + } +} +public class PackRewardData +{ + public bool isAutoPop; + public bool isNeedScroll; +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs.meta new file mode 100644 index 0000000..d508d02 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e683256807814283b0ddd73c92ca520 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs new file mode 100644 index 0000000..580ca21 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class PackRewardUICtrl : BaseUICtrl + { + private PackRewardUI ui; + private PackRewardModel model; + + private uint openUIMsg = UICtrlMsg.PackrewardUI_Open; + private uint closeUIMsg = UICtrlMsg.PackrewardUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PackrewardModel) as PackrewardModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PackRewardUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs.meta new file mode 100644 index 0000000..2abdc43 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PackReward/PackRewardUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 485f5d5cee496478b8c94d2649adcb49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock.meta new file mode 100644 index 0000000..1fe05ce --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4134198de21f41fbbaa5fef2629c3067 +timeCreated: 1729676956 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs new file mode 100644 index 0000000..17fd6d8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class PassunlockCtrl : BaseCtrl + { + public static PassunlockCtrl Instance { get; private set; } + + private PassunlockModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PassunlockModel) as PassunlockModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs.meta new file mode 100644 index 0000000..5a2ba20 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b53fa48e580b4882a9c0441fac55e15 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs new file mode 100644 index 0000000..5086e12 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class PassunlockModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs.meta new file mode 100644 index 0000000..0557970 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb4bc378cc43143cdaa3c2fa20c27548 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs new file mode 100644 index 0000000..130109a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using FairyGUI; +using UnityEngine; + +namespace ScrewsMaster +{ + public class PassunlockUI : BaseUI + { + private PassunlockUICtrl ctrl; + private PassunlockModel model; + private FGUI.G009_video.com_passunlock ui; + + private int _price = 1; + private GTextField _textCooldown; + public PassunlockUI(PassunlockUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PassunlockUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G009_video"; + uiInfo.assetName = "com_passunlock"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + model = ModuleManager.Instance.GetModel(ModelConst.PassunlockModel) as PassunlockModel; + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= UpdateButtonState; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G009_video.com_passunlock; + } + + protected override void OnOpenBefore(object args) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_show, 1); + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed); + GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnAdRewardClaimed); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnAdRewardClaimed); + GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnAdRewardClaimed); + } + + private void OnAdRewardClaimed(object args) + { + UpdateADsText(); + UpdateButtonState(); + + } + #endregion + void pay_success(object str) + { + string type = (string)str; + Debug.Log(str); + if (type == MaxPayManager.battle_pass) + { + CtrlCloseUI(); + } + } + //初始化页面逻辑 + private void InitView() + { + ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1; + _price = (int)ConfigSystem.GetConfig().Passportgift; + ui.btn_close.SetClick(CtrlCloseUI); + int gold = 0; + + UpdateADsText(); + UpdateButtonState(); + + + List Passportrewards_list = ConfigSystem.GetConfig().dataList; + for (int i = 0; i < Passportrewards_list.Count; i++) + { + + if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num; + + } + ui.text_allgold.text = gold.ToString(); + // ui.btn_buypass.GetChild("title").text = GameHelper.GetPaymentTypeVO().payicon + ConfigSystem.GetConfig().Passportgift; + // ui.btn_buypass.GetChild("title").text = $"{_price}"; + + + ui.btn_buypass.SetClick(OnClickWatchAdsBtn); + ui.btn_Claim.SetClick(OnClickBuyPassBtn); + + if (!GameHelper.IsAdModelOfPay()) + { + ui.pay_type.selectedIndex = 1; + decimal price = (decimal)GameHelper.GetCommonModel().Passportgift2; + ui.btn_max_pay.title = "$ "+price; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) + { + (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = true; + } + else + { + (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = false; + } + ui.btn_max_pay.SetClick(() => + { + ApplePayClass maxPayData = new ApplePayClass + { + amount = (int)Math.Round(price * 100), + sku = MaxPayManager.battle_pass, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + } + + } + + private void UpdateADsText() + { + ui.text_YourHaveAds.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}"; + ui.text_NeedAds.text = $"Need ADs:{_price}"; + } + + private void UpdateButtonState() + { + var inAdRewardCooldown = GameHelper.InAdRewardCooldown(); + + ui.btn_Claim.visible = GameHelper.CheckAdWatchCount(_price); + ui.btn_buypass.visible = !ui.btn_Claim.visible; + + ui.btn_buypass.grayed = inAdRewardCooldown; + ui.btn_buypass.touchable = !inAdRewardCooldown; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_buypass.GetChild("img_saveingpot") as GImage).visible = true; + if (_textCooldown == null && ui.btn_buypass.GetChild("text_cooldown") is GTextField textCooldown) + { + _textCooldown = textCooldown; + HallManager.Instance.UpdateSecondEvent += UpdateButtonState; + } + + _textCooldown.visible = inAdRewardCooldown; + + if (inAdRewardCooldown) + { + _textCooldown.text = CommonHelper.TimeFormat( + (int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Hour); + } + + ui.btn_buypass.GetChild("title").visible = !inAdRewardCooldown; + ui.btn_buypass.GetChild("icon").visible = !inAdRewardCooldown; + } + + private void OnClickWatchAdsBtn() + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_click, 1); + GameHelper.ShowVideoAd("PassUnlock", (success) => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + } + + private void OnClickBuyPassBtn() + { + if (GameHelper.CheckAdWatchCount(_price)) + { + GameHelper.AddAdWatchCount(-_price); + CtrlCloseUI(); + GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success,MaxPayManager.battle_pass); + + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.pass_success, 1); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + } + // GooglePayClass test = new GooglePayClass() + // { + // transactionId = "", + // amount = (int)(ConfigSystem.GetConfig().Passportgift * 100), + // sku = GooglePaymentManager.battle_pass, + // currency = "USD" + // }; + // + // GooglePaymentManager.Instance.BuyProduct(GooglePaymentManager.battle_pass, test); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs.meta new file mode 100644 index 0000000..d4777a2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6923c290d351644508b81cee1a88e1d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs new file mode 100644 index 0000000..bf14e69 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class PassunlockUICtrl : BaseUICtrl + { + private PassunlockUI ui; + private PassunlockModel model; + + private uint openUIMsg = UICtrlMsg.PassunlockUI_Open; + private uint closeUIMsg = UICtrlMsg.PassunlockUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PassunlockModel) as PassunlockModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PassunlockUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs.meta new file mode 100644 index 0000000..68052a1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Passunlock/PassunlockUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9730d87819cc94ea5b1f8a5871d19ccc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading.meta new file mode 100644 index 0000000..2304d44 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 12136aca88e2c1e468b2aaf7c6162af8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs new file mode 100644 index 0000000..107db5b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class PayloadingCtrl : BaseCtrl + { + public static PayloadingCtrl Instance { get; private set; } + + private PayloadingModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PayloadingModel) as PayloadingModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs.meta new file mode 100644 index 0000000..5790be1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 105d69bbdd9dd46bea6cd8bc0593c98f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs new file mode 100644 index 0000000..e4a4213 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class PayloadingModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs.meta new file mode 100644 index 0000000..9843a3e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3537c81351e541aaa7d6078f65f5e6f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs new file mode 100644 index 0000000..68521f9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs @@ -0,0 +1,81 @@ +using DG.Tweening; + +namespace ScrewsMaster +{ + public class PayloadingUI : BaseUI + { + private PayloadingUICtrl ctrl; + private PayloadingModel model; + private FGUI.G008_reward.com_payloading ui; + + public PayloadingUI(PayloadingUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PayloadingUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_payloading"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PayloadingModel) as PayloadingModel; + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_payloading; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + DOVirtual.DelayedCall(5, () => + { + CtrlCloseUI(); + }); + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs.meta new file mode 100644 index 0000000..7390caf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7234ad021bd9d48578a2006435070883 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs new file mode 100644 index 0000000..94da788 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class PayloadingUICtrl : BaseUICtrl + { + private PayloadingUI ui; + private PayloadingModel model; + + private uint openUIMsg = UICtrlMsg.PayloadingUI_Open; + private uint closeUIMsg = UICtrlMsg.PayloadingUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PayloadingModel) as PayloadingModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PayloadingUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs.meta new file mode 100644 index 0000000..cf7ec9d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Payloading/PayloadingUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e860c5f33db524b09a94aa6a6a461036 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay.meta new file mode 100644 index 0000000..bb80b2d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b10faee21d20402cab622e39944b31ee +timeCreated: 1729593270 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs new file mode 100644 index 0000000..8f0e819 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class PixPayCtrl : BaseCtrl + { + public static PixPayCtrl Instance { get; private set; } + + private PixPayModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PixPayModel) as PixPayModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs.meta new file mode 100644 index 0000000..8bfad21 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 143473f2c6453423f80a6e48992b9884 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs new file mode 100644 index 0000000..ec02650 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class PixPayModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs.meta new file mode 100644 index 0000000..c5a52a0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9918b9480495c4f7ea129aa33e5efbf1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs new file mode 100644 index 0000000..05634b5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs @@ -0,0 +1,290 @@ +// using System.Linq; +// using UnityEngine; + +// namespace ScrewsMaster +// { +// public class PixPayUI : BaseUI +// { +// private PixPayUICtrl ctrl; +// private PixPayModel model; +// private FGUI.G007_makeup.com_PixPay ui; +// private int pay_Type = 0; + +// public PixPayUI(PixPayUICtrl ctrl) : base(ctrl) +// { +// uiName = UIConst.PixPayUI; +// this.ctrl = ctrl; +// } + +// protected override void SetUIInfo(UIInfo uiInfo) +// { +// uiInfo.packageName = "G007_makeup"; +// uiInfo.assetName = "com_PixPay"; +// uiInfo.layerType = UILayerType.Popup; +// uiInfo.isNeedOpenAnim = true; +// uiInfo.isNeedCloseAnim = true; +// uiInfo.isNeedUIMask = true; +// } + +// #region 生命周期 +// protected override void OnInit() +// { +// //model = ModuleManager.Instance.GetModel(ModelConst.PixPayModel) as PixPayModel; +// } + +// protected override void OnClose() +// { +// } + +// protected override void OnBind() +// { +// ui = baseUI as FGUI.G007_makeup.com_PixPay; +// } + +// protected override void OnOpenBefore(object args) +// { +// pay_Type = (int)args; +// InitView(); +// } + +// protected override void OnOpen(object args) +// { +// } + +// protected override void OnHide() +// { +// } + +// protected override void OnDisplay(object args) +// { +// } +// #endregion + +// #region 消息 +// protected override void AddListener() +// { +// GameDispatcher.Instance.AddListener(GameMsg.PaySuccess, closeView); +// } +// protected override void RemoveListener() +// { + +// } +// #endregion + +// void closeView(object a) +// { +// UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Close); +// // ULiteWebView.Ins.Close(); +// } + +// //初始化页面逻辑 +// private void InitView() +// { +// ui.btn_close.SetClick(() => { UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Close); }); +// ui.btn_comfirmar.SetClick(BtnComfirmarClick); +// ui.btn_close_view.visible = false; +// ui.btn_close_view.SetClick(() => +// { +// getOrderState(); +// ui.btn_close_view.visible = false; +// UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Close); +// // ULiteWebView.Ins.Close(); +// }); +// } + +// public static void getOrderState() +// { +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// var orderId = PlayerPrefs.GetString("PAYFORH5", ""); +// var pay1_incheck = false; +// if (orderId == "") +// { + +// } +// else +// { +// //orderId = "1710323239_1000498_10"; +// var test = new { order_id = orderId }; + +// MakeupTaskData makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last() as MakeupTaskData; +// //makeupTaskData.videoCount = 100; +// var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); +// if (vo != null) +// { +// //vo.task_need +// //PreferencesMgr.Instance.MakeupTaskH5Time\ +// HallManager.Instance.UpdateFiveSecondEvent += getOrderState; +// NetworkKit.PostWithHeader("shop/pixPayOrderQuery", test, (isSuccess, obj) => +// { +// if (isSuccess) +// { +// if (obj.status == 1) +// { +// pay1_incheck = true; +// } +// else if (obj.status == 2) +// { +// if (PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need) +// { +// PreferencesMgr.Instance.MakeupTaskH5Time = vo.task_need; +// } +// PlayerPrefs.SetString("PAYFORH5", ""); +// GameHelper.ShowTips("Parabéns pelo pagamento bem-sucedido, pulei a tarefa para você"); +// GameDispatcher.Instance.Dispatch(GameMsg.PaySuccess); +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// } +// else if (obj.status == 3) +// { +// PlayerPrefs.SetString("PAYFORH5", ""); +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// } +// } + +// }); +// } +// } + +// orderId = PlayerPrefs.GetString("PAYFORADS", ""); +// if (orderId == "") +// { + +// } +// else +// { +// //orderId = "1710323239_1000498_10"; +// var test = new { order_id = orderId }; + +// MakeupTaskData makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last() as MakeupTaskData; +// //makeupTaskData.videoCount = 100; +// var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); +// if (vo != null) +// { +// //vo.task_need +// //PreferencesMgr.Instance.MakeupTaskH5Time\ +// if (!pay1_incheck) HallManager.Instance.UpdateFiveSecondEvent += getOrderState; +// NetworkKit.PostWithHeader("shop/pixPayOrderQuery", test, (isSuccess, obj) => +// { + + +// if (isSuccess) +// { +// if (obj.status == 1) +// { + +// } +// else if (obj.status == 2) +// { +// if (makeupTaskData.videoCount < vo.ad_need) +// { +// makeupTaskData.videoCount = vo.ad_need; +// } +// PlayerPrefs.SetString("PAYFORADS", ""); +// GameHelper.ShowTips("Parabéns pelo pagamento bem-sucedido, pulei a tarefa para você"); +// GameDispatcher.Instance.Dispatch(GameMsg.PaySuccess); +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; + +// } +// else if (obj.status == 3) +// { +// PlayerPrefs.SetString("PAYFORADS", ""); +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// HallManager.Instance.UpdateFiveSecondEvent -= getOrderState; +// } +// } +// }); +// } +// } +// } + + +// void BtnComfirmarClick() +// { + + +// var email = ui.input_1.text.Trim(); +// var phone = ui.input_2.text.Trim(); +// var account = ui.input_3.text.Trim(); + +// if (email == "" || phone == "" || account == "") +// { +// GameHelper.ShowTips("Por favor, digite o conteúdo correto"); +// return; +// } + +// if ((PlayerPrefs.GetString("PAYFORH5", "") != "") || (PlayerPrefs.GetString("PAYFORADS", "") != "")) +// { +// GameHelper.ShowTips("Ordem em pagamento"); +// getOrderState(); +// return; +// } + + +// if (pay_Type == 1) +// { +// PayerData test = new PayerData() +// { +// name = account, +// tel = phone, +// email = email, +// amount = ConfigSystem.GetConfig().purchase1, + +// }; +// NetworkKit.PostWithHeader("shop/pixPayIn", test, (isSuccess, obj) => +// { +// // ULiteWebView.Ins.LoadUrl(obj.pay_url); +// // ULiteWebView.Ins.Show(0, 150, 0, 0); +// ui.btn_close_view.visible = true; +// PlayerPrefs.SetString("PAYFORH5", obj.order_id); +// }); +// } +// else if (pay_Type == 2) +// { +// PayerData test = new PayerData() +// { +// name = account, +// tel = phone, +// email = email, +// amount = ConfigSystem.GetConfig().purchase2, + +// }; +// NetworkKit.PostWithHeader("shop/pixPayIn", test, (isSuccess, obj) => +// { +// // ULiteWebView.Ins.LoadUrl(obj.pay_url); +// // ULiteWebView.Ins.Show(0, 150, 0, 0); +// ui.btn_close_view.visible = true; +// PlayerPrefs.SetString("PAYFORADS", obj.order_id); +// }); +// } + + + +// } + + +// } +// } + +// public class PayerData +// { +// public string name; +// public string tel; +// public string email; +// public int amount; +// } +// public class orderData +// { +// public string order_id; +// public string pay_url; + +// } +// public class orderState +// { +// public string order_id; +// public int status; + +// } \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs.meta new file mode 100644 index 0000000..ecf6681 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: efced3c2dfe304d8fa3ca0a3347a3f39 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs new file mode 100644 index 0000000..5eeff25 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs @@ -0,0 +1,71 @@ +// namespace ScrewsMaster +// { +// public class PixPayUICtrl : BaseUICtrl +// { +// private PixPayUI ui; +// private PixPayModel model; + +// private uint openUIMsg = UICtrlMsg.PixPayUI_Open; +// private uint closeUIMsg = UICtrlMsg.PixPayUI_Close; + +// #region 生命周期 +// protected override void OnInit() +// { +// //model = ModuleManager.Instance.GetModel(ModelConst.PixPayModel) as PixPayModel; +// } + +// protected override void OnDispose() +// { +// } + +// public override void OpenUI(object args = null) +// { +// if (ui == null) +// { +// ui = new PixPayUI(this); +// ui.Open(args); +// } +// } + +// public override void CloseUI(object args = null) +// { +// if (ui != null && !ui.isClose) +// { +// ui.Close(); +// } +// ui = null; +// } +// #endregion + +// #region 消息 +// public override uint GetOpenUIMsg(string uiName) +// { +// return openUIMsg; +// } +// public override uint GetCloseUIMsg(string uiName) +// { +// return closeUIMsg; +// } + +// protected override void AddListener() +// { +// uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); +// uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); +// } +// protected override void RemoveListener() +// { +// uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); +// uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); +// } + +// protected override void AddServerListener() +// { + +// } +// protected override void RemoveServerListener() +// { + +// } +// #endregion +// } +// } \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs.meta new file mode 100644 index 0000000..942aff0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PixPay/PixPayUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 351e95d87df2b4f9eb180d0f2f3a14ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy.meta new file mode 100644 index 0000000..5774465 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 121b9b7125bbe9b40be286ae11cd4564 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs new file mode 100644 index 0000000..e6c65eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class PrivacyCtrl : BaseCtrl + { + public static PrivacyCtrl Instance { get; private set; } + + private PrivacyModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs.meta new file mode 100644 index 0000000..bd77c01 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 33119cc76673ef04c93c6b8541ad9a8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs new file mode 100644 index 0000000..2beb5d3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class PrivacyModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs.meta new file mode 100644 index 0000000..b6767a0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7dfdb69313292dc4cb7b2cd1af68779e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs new file mode 100644 index 0000000..bc51a34 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs @@ -0,0 +1,111 @@ +namespace ScrewsMaster +{ + using System; + using FairyGUI; + using UnityEngine; + using System.Globalization; + + public class PrivacyUI : BaseUI + { + private PrivacyUICtrl ctrl; + private PrivacyModel model; + private FGUI.SC006_privacy.com_privacy ui; + + private string content; + + private bool isTerm; + + public PrivacyUI(PrivacyUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PrivacyUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SC006_privacy"; + uiInfo.assetName = "com_privacy"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnClose() + { + ui?.FadeOut(); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.SC006_privacy.com_privacy; + } + + protected override void OnOpenBefore(object args) + { + if (args != null) + { + isTerm = (bool)args; + } + + InitView(); + } + + protected override void OnOpen(object args) + { + ui?.FadeIn(); + } + + #endregion + + private void InitView() + { + ui.txt_title.text = isTerm ? "Terms of Service" : "Privacy Policy"; + + LoadKit.Instance.LoadAsset("TextAsset", isTerm ? "Term" : "Privacy", (txt) => + { + content = txt.text; + + var str = getstr(content, 16327); + + foreach (var t in str) + { + var aRichTextField = new GRichTextField(); + aRichTextField.SetSize(GRoot.inst.width, 100); + aRichTextField.color = new Color(0.32f, 0.32f, 0.32f, 1f); + // aRichTextField.strokeColor = Color.black; + // aRichTextField.stroke = 1; + aRichTextField.textFormat.size = 44; + aRichTextField.autoSize = AutoSizeType.Height; + aRichTextField.AddRelation(GRoot.inst, RelationType.Width); + aRichTextField.text = t; + ui.list_privacy.AddChild(aRichTextField); + } + + ui.list_privacy.EnsureBoundsCorrect(); + }); + + ui.closeButton.SetClick(CtrlCloseUI); + } + + public string[] getstr(string strs, int len) + { + double i = strs.Length; + var array = new string[int.Parse(Math.Ceiling(i / len).ToString(CultureInfo.InvariantCulture))]; + for (var j = 0; j < array.Length; j++) + { + len = len <= strs.Length ? len : strs.Length; + array[j] = strs[..len]; + strs = strs.Substring(len, strs.Length - len); + } + + return array; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs.meta new file mode 100644 index 0000000..f6e9d71 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b3692c5a5b53a141bb168b2616166a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs new file mode 100644 index 0000000..6f6bd22 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs @@ -0,0 +1,68 @@ +namespace ScrewsMaster +{ + public class PrivacyUICtrl : BaseUICtrl + { + private PrivacyUI ui; + private PrivacyModel model; + + private uint openUIMsg = UICtrlMsg.PrivacyUI_Open; + private uint closeUIMsg = UICtrlMsg.PrivacyUI_Close; + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PrivacyUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs.meta new file mode 100644 index 0000000..dc1f41f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Privacy/PrivacyUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 895ffa70583bb1e4eb5e369eab12180b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel.meta new file mode 100644 index 0000000..4a6d4c2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 58ce8422295f56243bdc756b2683079d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs new file mode 100644 index 0000000..4194205 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs @@ -0,0 +1,25 @@ + + +namespace ScrewsMaster +{ + public class PrizeWheelCtrl : BaseCtrl + { + public static PrizeWheelCtrl Instance { get; private set; } + + private PrizeWheelModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PrizeWheelModel) as PrizeWheelModel; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs.meta new file mode 100644 index 0000000..4432096 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 679f97dc3c1914b4fbcc72bf570a28c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs new file mode 100644 index 0000000..8f38a11 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class PrizeWheelModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs.meta new file mode 100644 index 0000000..a717799 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 971c12bf974d04742a7b9f73f30966e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs new file mode 100644 index 0000000..961bf88 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs @@ -0,0 +1,362 @@ + +using System; +using System.Collections.Generic; +using DG.Tweening; +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; +using FGUI.G020_PrizeWheel; +using Spine.Unity; +using Random = UnityEngine.Random; + +namespace ScrewsMaster +{ + public class PrizeWheelUI : BaseUI + { + + private const string GreenStr = ""; + private const string RedStr = ""; + private const string RemainingCountTextStr = "Left Spin Times: "; + private PrizeWheelUICtrl ctrl; + private PrizeWheelModel model; + private PrizeWheelPanel ui; + + private SkeletonAnimation prizeWheelAnim; + private Action closeCallback; + + private List _prizeWheelDataList; + private int[] _wheelTimes; + + private List _spinWheelRewardItems; + + private int _rewardIndex = 0; + private long _cooldown; + private bool _inCooldown; + private bool _canUse; + private bool _inAnim; + + private AudioSource _audioSource; + + private GTextField _goldNumText; + + public PrizeWheelUI(PrizeWheelUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PrizeWheelUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G020_PrizeWheel"; + uiInfo.assetName = "PrizeWheelPanel"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PrizeWheelModel) as PrizeWheelModel; + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= UpdateData; + + if (_audioSource != null && _audioSource.isPlaying) + { + _audioSource.Stop(); + } + } + + protected override void OnBind() + { + ui = baseUI as PrizeWheelPanel; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + { + ui.TopBox.y += Screen.safeArea.y; + } + + DateTime dateTime1 = DateTimeOffset.FromUnixTimeSeconds(GameHelper.GetNowTime()).LocalDateTime; + DateTime dateTime2 = DateTimeOffset.FromUnixTimeSeconds(PreferencesMgr.Instance.PrizeWheelTime).LocalDateTime; + + bool isSameDay = dateTime1.Date == dateTime2.Date; + if (!isSameDay) + { + PreferencesMgr.Instance.PrizeWheelTime = 0; + PreferencesMgr.Instance.PrizeWheelCount = 0; + } + + var commonModel = ConfigSystem.GetConfig(); + _wheelTimes = commonModel.wheelTimes; + InitAllPrizeWheelData(); + InitView(); + + } + + protected override void OnOpen(object args) + { + ui.Open.Play(() => + { + prizeWheelAnim.SetActive(true); + }); + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + ui.StartSpinBtn.CountdownText.visible = false; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) ui.StartSpinBtn.img_saveingpot.visible = true; + else ui.StartSpinBtn.img_saveingpot.visible = false; + _goldNumText = ui.gold.GetChild("number_text") as GTextField; + + prizeWheelAnim = FXManager.Instance.SetFx(ui.PrizeWheelAnimParent, Fx_Type.fx_prize_wheel, ref closeCallback); + prizeWheelAnim.state.SetAnimation(0, "daiji", true); + prizeWheelAnim.SetActive(false); + + _goldNumText.text = GameHelper.GetGoldNumber().ToString(); + + InitButtons(); + InitPrizeWheelList(); + + HallManager.Instance.UpdateSecondEvent += UpdateData; + UpdateView(); + } + + private void UpdateData() + { + if (_inAnim) + return; + + _cooldown = GameHelper.GetNowTime() - PreferencesMgr.Instance.PrizeWheelTime; + _canUse = PreferencesMgr.Instance.PrizeWheelCount < _wheelTimes[0]; + _inCooldown = _cooldown < _wheelTimes[1]; + + if (_inCooldown) + { + TimeSpan timeSpan = TimeSpan.FromSeconds(_wheelTimes[1] - _cooldown); + + // 格式化为 "hh:mm:ss" 的字符串 + string formattedTime = string.Format("{0:D2}:{1:D2}:{2:D2}", + timeSpan.Hours, + timeSpan.Minutes, + timeSpan.Seconds); + ui.StartSpinBtn.CountdownText.text = formattedTime; + } + + ui.StartSpinBtn.grayed = _inCooldown || !_canUse; + ui.StartSpinBtn.CountdownText.visible = _inCooldown && _canUse; + ui.StartSpinBtn.BtnTitleBox.visible = !ui.StartSpinBtn.CountdownText.visible; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1 && !ui.StartSpinBtn.grayed) ui.StartSpinBtn.img_saveingpot.visible = true; + else ui.StartSpinBtn.img_saveingpot.visible = false; + } + + private void UpdateView() + { + UpdateRemainingCountText(); + UpdateData(); + ui.StartSpinBtn.grayed = _inCooldown || !_canUse; + ui.StartSpinBtn.CountdownText.visible = _inCooldown; + ui.StartSpinBtn.touchable = true; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1 && !ui.StartSpinBtn.grayed) ui.StartSpinBtn.img_saveingpot.visible = true; + else ui.StartSpinBtn.img_saveingpot.visible = false; + } + + private void UpdateRemainingCountText() + { + var canUse = PreferencesMgr.Instance.PrizeWheelCount < _wheelTimes[0]; + var color = canUse ? "#b7e25a" : "#fb8a87"; + // ui.RemainingCountText.text = + // $"{RemainingCountTextStr} {PreferencesMgr.Instance.PrizeWheelCount} " + + // $"/ {_wheelTimes[0]}"; + ui.RemainingCountText.text = + $"{RemainingCountTextStr}" + + $"{PreferencesMgr.Instance.PrizeWheelCount}" + + $"/{_wheelTimes[0]}"; + } + + private void InitPrizeWheelList() + { + _spinWheelRewardItems = new List(8); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_1); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_2); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_3); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_4); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_5); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_6); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_7); + _spinWheelRewardItems.Add(ui.PrizeWheel.item_8); + + + for (int i = 0; i < _spinWheelRewardItems.Count; i++) + { + var data = _prizeWheelDataList[i]; + _spinWheelRewardItems[i].num.text = Mathf.CeilToInt(data.quantity).ToString(); + } + } + + private void PlayPrizeWheelAnim() + { + prizeWheelAnim.state.SetAnimation(0, "zhuandong", true); + ui.PrizeWheel.rotation = 0; + _audioSource = AudioManager.Instance.PlayDynamicEffect(AudioConst.PlayPrizeWheelAnim); + ui.PrizeWheel.TweenRotate(-360 * 10 + _rewardIndex * -45, 6.8f).SetEase(EaseType.QuadInOut).OnComplete(() => + { + _inAnim = false; + prizeWheelAnim.state.AddAnimation(0, "zhongjiang", false, 0f); + prizeWheelAnim.state.AddAnimation(0, "daiji", true, 0f); + DispatchReward(); + UpdateView(); + }); + } + + private int CalRewardResult() + { + var sum = 0; + for (int i = 0; i < _prizeWheelDataList.Count; i++) + { + var data = _prizeWheelDataList[i]; + sum += data.weight; + } + + var random = Random.Range(0, sum + 1); + + sum = 0; + for (int i = 0; i < _prizeWheelDataList.Count; i++) + { + var data = _prizeWheelDataList[i]; + sum += data.weight; + if (random <= sum) + { + return i; + } + } + + return 0; + } + + private void DispatchReward() + { + PreferencesMgr.Instance.PrizeWheelCount += 1; + PreferencesMgr.Instance.PrizeWheelTime = GameHelper.GetNowTime(); + + var startPos = GameHelper.GetUICenterPosition(_spinWheelRewardItems[_rewardIndex]); + var data = _prizeWheelDataList[_rewardIndex]; + + var curGoldNum = GameHelper.GetGoldNumber(); + var rewardModel = new RewardData(); + var rewardData = new RewardSingleData(data.wheel_item, Mathf.CeilToInt(data.quantity), RewardOrigin.PrizeWheel) + { + startPosition = startPos, + endPosition = GameHelper.GetUICenterPosition(ui.gold), + + }; + rewardModel.AddReward(rewardData); + + rewardModel.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + + // if (vo.is_double) rewardModel.condition = RewardCondition.None; + rewardModel.AddCompleted(isSuccess => + { + if (isSuccess) + { + AudioManager.Instance.PlayDynamicEffect(AudioConst.DailyBonusCollect); + + DOVirtual.Float(curGoldNum, GameHelper.GetGoldNumber(), 1f, + value => { _goldNumText.text = ((int)value).ToString(); });//金币变化动画 + } + else + { + // GameHelper.ShowTips("Not time to check in yet"); + + } + }); + + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardModel); + } + + + private void InitButtons() + { + ui.CloseBtn.SetClick(OnClickCloseBtn); + ui.StartSpinBtn.SetClick(OnClickStartSpinBtn); + } + + private void OnClickCloseBtn() + { + + prizeWheelAnim.SetActive(false); + ui.Close.Play(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PrizeWheelUI_Close); + }); + } + + private void OnClickStartSpinBtn() + { + if (!_canUse) + { + GameHelper.ShowTips("Today's quota is exhausted."); + return; + } + if (_inCooldown) + { + _cooldown = GameHelper.GetNowTime() - PreferencesMgr.Instance.PrizeWheelTime; + GameHelper.ShowTips($"In cooldown, {_wheelTimes[1] - _cooldown} seconds left."); + return; + } + ui.StartSpinBtn.grayed = true; + ui.StartSpinBtn.touchable = false; + ui.StartSpinBtn.img_saveingpot.visible = false; + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + _inAnim = true; + _rewardIndex = CalRewardResult(); + PlayPrizeWheelAnim(); + } + else + { + ui.StartSpinBtn.grayed = false; + ui.StartSpinBtn.touchable = true; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) ui.StartSpinBtn.img_saveingpot.visible = true; + else ui.StartSpinBtn.img_saveingpot.visible = false; + } + }); + } + + + public void InitAllPrizeWheelData() + { + var prizeWheelDataModel = ConfigSystem.GetConfig(); + _prizeWheelDataList = prizeWheelDataModel.dataList; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs.meta new file mode 100644 index 0000000..e2e9a2c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7c35c7a5573bd54e8cfb1fee6d6f05f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs new file mode 100644 index 0000000..b30786d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs @@ -0,0 +1,73 @@ + + +namespace ScrewsMaster +{ + public class PrizeWheelUICtrl : BaseUICtrl + { + private PrizeWheelUI ui; + private PrizeWheelModel model; + + private uint openUIMsg = UICtrlMsg.PrizeWheelUI_Open; + private uint closeUIMsg = UICtrlMsg.PrizeWheelUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PrizeWheelModel) as PrizeWheelModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PrizeWheelUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs.meta new file mode 100644 index 0000000..bc8a0df --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/PrizeWheel/PrizeWheelUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb16273c4ca15aa4b880d53323607a95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile.meta new file mode 100644 index 0000000..9dda499 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f019d847152d274fadbe9dc1405ff58 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs new file mode 100644 index 0000000..4e4365b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs @@ -0,0 +1,19 @@ +namespace ScrewsMaster +{ + public class ProfileCtrl : BaseCtrl + { + public static ProfileCtrl Instance { get; private set; } + + private ProfileModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs.meta new file mode 100644 index 0000000..0fcccb9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 970255a4b82f460d9def10244e6f0065 +timeCreated: 1676361371 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs new file mode 100644 index 0000000..4ae0309 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs @@ -0,0 +1,15 @@ +namespace ScrewsMaster +{ + public class ProfileModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs.meta new file mode 100644 index 0000000..47d4956 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3edb59af67134ff28c25fcc70c05c652 +timeCreated: 1676361371 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs new file mode 100644 index 0000000..9edcbfd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs @@ -0,0 +1,124 @@ +namespace ScrewsMaster +{ + using FairyGUI; + using FGUI.G006_menu; + + public class ProfileUI : BaseUI + { + private ProfileUICtrl ctrl; + private ProfileModel model; + private FGUI.G006_menu.com_edit ui; + private LoginModel loginModel; + + private int selectIndex = -1; + + private int avatarTotal; + + public ProfileUI(ProfileUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.ProfileUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G006_menu"; + uiInfo.assetName = "com_edit"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.ProfileModel) as ProfileModel; + loginModel = moduleManager.GetModel(ModelConst.LoginModel) as LoginModel; + } + + protected override void OnClose() + { + WebviewManager.Instance.SetDarkThough(true); + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G006_menu.com_edit; + } + + protected override void OnOpenBefore(object args) + { + WebviewManager.Instance.SetDarkThough(false); + InitData(); + InitView(); + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + } + + private void InitData() + { + selectIndex = PreferencesMgr.Instance.PlayerAvatarId; + avatarTotal = 12; + } + + private void InitView() + { + ui.closeButton.onClick.Set(OnCloseView); + + GameHelper.SetName(ui.textp_name); + + ui.btn_ok.onClick.Set(OnClickOK); + + ui.list_avatar.itemRenderer = ItemRenderer; + ui.list_avatar.numItems = avatarTotal; + } + + private void OnClickOK() + { + var name = ui.textp_name.text; + OnCloseView(); + + if (selectIndex != -1) + { + PreferencesMgr.Instance.PlayerAvatarId = selectIndex; + } + + if (string.IsNullOrEmpty(name) || name.IsNullOrWhiteSpace()) + { + GameHelper.ShowTips("The input cannot be null", true); + return; + } + + if (!name.Equals(PreferencesMgr.Instance.PlayerName)) + { + PreferencesMgr.Instance.PlayerName = name; + } + } + + private void ItemRenderer(int index, GObject item) + { + var btnImg = item as btn_img; + var currentIndex = index + 1; + + TextureHelper.SetAvatarToLoader(currentIndex, btnImg.head_loader.GetChild("loader_avatar") as GLoader); + btnImg.cont_select.selectedIndex = selectIndex == currentIndex + ? btn_img.Select_select + : btn_img.Select_none; + + btnImg.SetClick(() => + { + selectIndex = currentIndex; + ui.list_avatar.numItems = avatarTotal; + }); + } + + private void OnCloseView() + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Close); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs.meta new file mode 100644 index 0000000..07fca01 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 41f063f214894f10a07d3e0716925cce +timeCreated: 1676361371 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs new file mode 100644 index 0000000..2cf4fbe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs @@ -0,0 +1,60 @@ +namespace ScrewsMaster +{ + public class ProfileUICtrl : BaseUICtrl + { + private ProfileUI ui; + private ProfileModel model; + + private uint openUIMsg = UICtrlMsg.ProfileUI_Open; + private uint closeUIMsg = UICtrlMsg.ProfileUI_Close; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new ProfileUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui is { isClose: false }) + { + ui.Close(); + } + + ui = null; + } + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs.meta new file mode 100644 index 0000000..f021ce7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Profile/ProfileUICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a7882350acc64942a9f041db31da1c52 +timeCreated: 1676361371 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop.meta new file mode 100644 index 0000000..0c70f0e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a2013929fb538c94c885dac558280c0b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs new file mode 100644 index 0000000..b95975d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs @@ -0,0 +1,25 @@ + + +namespace ScrewsMaster +{ + public class PropCtrl : BaseCtrl + { + public static PropCtrl Instance { get; private set; } + + private PropModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.PropModel) as PropModel; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs.meta new file mode 100644 index 0000000..da3a58a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 928a5b70f9183a045ace640e15286dfc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs new file mode 100644 index 0000000..3a1cebb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class PropModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs.meta new file mode 100644 index 0000000..b013519 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e846616b07c9d14d8d171c4ea879ee0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs new file mode 100644 index 0000000..435d41d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs @@ -0,0 +1,288 @@ + +using System; +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; +using Roy.Datas; +using SGame; +using DG.Tweening; + +namespace ScrewsMaster +{ + public class PropUI : BaseUI + { + private PropUICtrl ctrl; + private PropModel model; + private FGUI.G003_play.com_prop ui; + private int type; + private int num; + + private PropViewData _data; + + private int _payBoxPrice; + private bool _needWatchAds; + + public PropUI(PropUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PropUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G003_play"; + uiInfo.assetName = "com_prop"; + uiInfo.layerType = UILayerType.Normal; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PropModel) as PropModel; + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= UpdateButtonState; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G003_play.com_prop; + } + + protected override void OnOpenBefore(object args) + { + _data = args as PropViewData; + if (_data != null) + { + type = _data.type; + num = _data.index; + } + + // args.GetType().GetProperty("type").GetValue(args); + // num = (int)args.GetType().GetProperty("index").GetValue(args); + ui.cont_prop.selectedIndex = type; + ui.pay_type.selectedIndex = GameHelper.IsAdModelOfPay() ? 0 : 1; + if (type == 3) + { + Debug.Log(BuriedPointEvent.AddBoxShow + "_" + num); + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxShow + "_" + num, 1); + HallManager.Instance.UpdateSecondEvent += UpdateButtonState; + + } + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + GameDispatcher.Instance.AddListener(GameMsg.AdRewardClaimed, OnUpdateAdReward); + GameDispatcher.Instance.AddListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward); + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + } + protected override void RemoveListener() + { + + GameDispatcher.Instance.RemoveListener(GameMsg.AdRewardClaimed, OnUpdateAdReward); + GameDispatcher.Instance.RemoveListener(GameMsg.AdWatchCountUpdated, OnUpdateAdReward); + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + } + + private void OnUpdateAdReward(object data) + { + UpdateWatchAdsText(); + UpdateButtonState(); + } + #endregion + void pay_success(object str) + { + string type = (string)str; + if (type == MaxPayManager.buy_one) + { + ShowScrews.Instance.OnSuccessPayBox1(num); + SetButtonsTouchable(false); + DOVirtual.DelayedCall(0.1f, () => + { + CtrlCloseUI(); + }); + } + } + //初始化页面逻辑 + private void InitView() + { + var addPrice = ConfigSystem.GetConfig().Purchaseprops; + var mergePrice = ConfigSystem.GetConfig().Purchaseprops; + var cleanPrice = ConfigSystem.GetConfig().Purchaseprops; + _payBoxPrice = (int)ConfigSystem.GetConfig().addspace; + + if (ui.btn_add is btn_revive btnAdd) btnAdd.txt_coin.text = addPrice.ToString(); + ui.btn_add.onClick.Add(() => + { + if (!GameHelper.CheckGoldNumber(addPrice)) + { + GameHelper.ShowTips("Not Enough Coins"); + return; + } + GameHelper.AddGoldNumber(-addPrice); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + + GameHelper.AddItemNumber(ItemEnum.AddHole, 1); + SetButtonsTouchable(false); + CtrlCloseUI(); + ShowScrews.Instance.ShowToast("Successful purchase"); + }); + + if (ui.btn_merge is btn_revive btnMerge) btnMerge.txt_coin.text = mergePrice.ToString(); + ui.btn_merge.onClick.Add(() => + { + if (!GameHelper.CheckGoldNumber(mergePrice)) + { + GameHelper.ShowTips("Not Enough Coins"); + return; + } + GameHelper.AddGoldNumber(-mergePrice); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + + GameHelper.AddItemNumber(ItemEnum.MergeBox, 1); + + SetButtonsTouchable(false); + CtrlCloseUI(); + ShowScrews.Instance.ShowToast("Successful purchase"); + }); + + if (ui.btn_clean is btn_revive btnClean) btnClean.txt_coin.text = cleanPrice.ToString(); + ui.btn_clean.onClick.Add(() => + { + if (!GameHelper.CheckGoldNumber(cleanPrice)) + { + GameHelper.ShowTips("Not Enough Coins"); + return; + } + GameHelper.AddGoldNumber(-cleanPrice); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + + GameHelper.AddItemNumber(ItemEnum.ClearHole, 1); + SetButtonsTouchable(false); + CtrlCloseUI(); + ShowScrews.Instance.ShowToast("Successful purchase"); + }); + + // if (ui.btn_PayBox is btn_revive btnPayBox) btnPayBox.txt_coin.text = payBoxPrice.ToString(); + ui.btn_PayBox.onClick.Add(() => + { + if (_needWatchAds) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxClick + "_" + num, 1); + GameHelper.ShowVideoAd($"PayBox", success => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + return; + } + + if (GameHelper.CheckAdWatchCount(_payBoxPrice)) + { + GameHelper.AddAdWatchCount(-_payBoxPrice); + ShowScrews.Instance.OnSuccessPayBox1(num); + SetButtonsTouchable(false); + CtrlCloseUI(); + ShowScrews.Instance.ShowToast("Successful purchase"); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + } + }); + + + ui.btn_close.onClick.Add(() => + { + this.ctrl.CloseUI(); + }); + UpdateButtonState(); + UpdateWatchAdsText(); + if (!GameHelper.IsAdModelOfPay()) + { + ui.pay_type.selectedIndex = 1; + decimal price = (decimal)GameHelper.GetCommonModel().addspace2; + ui.btn_max_pay.title = "$ "+price; + + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = true; + + ui.btn_max_pay.SetClick(() => + { + Debug.Log(BuriedPointEvent.AddBoxClick + "_" + num); + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.AddBoxClick + "_" + num, 1); + ApplePayClass maxPayData = new ApplePayClass + { + amount = (int)Math.Round(price * 100), + sku = MaxPayManager.buy_one, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + } + } + + private void UpdateWatchAdsText() + { + ui.text_hasADsCount.text = $"Owner ADs:{GameHelper.GetAdWatchCount()}"; + ui.text_NeedAds.text = $"Need {(int)ConfigSystem.GetConfig().addspace} ADs"; + } + + private void UpdateButtonState() + { + (ui.btn_PayBox.GetChild("img_saveingpot") as GImage).visible = false; + + _needWatchAds = false; + ui.btn_PayBox.touchable = true; + ui.btn_PayBox.grayed = false; + if (GameHelper.CheckAdWatchCount(_payBoxPrice)) + { + ui.btn_PayBox.text = "Claim"; + } + else if (GameHelper.InAdRewardCooldown()) + { + ui.btn_PayBox.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + ui.btn_PayBox.touchable = false; + ui.btn_PayBox.grayed = true; + } + else + { + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_PayBox.GetChild("img_saveingpot") as GImage).visible = true; + + _needWatchAds = true; + ui.btn_PayBox.text = $"Watch Ad"; + } + } + + private void SetButtonsTouchable(bool b) + { + ui.btn_add.touchable = b; + ui.btn_merge.touchable = b; + ui.btn_clean.touchable = b; + ui.btn_PayBox.touchable = b; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs.meta new file mode 100644 index 0000000..ec2e389 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28a207608f184e341b0527b63006d23f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs new file mode 100644 index 0000000..fcd6362 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs @@ -0,0 +1,73 @@ + + +namespace ScrewsMaster +{ + public class PropUICtrl : BaseUICtrl + { + private PropUI ui; + private PropModel model; + + private uint openUIMsg = UICtrlMsg.PropUI_Open; + private uint closeUIMsg = UICtrlMsg.PropUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.PropModel) as PropModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new PropUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs.meta new file mode 100644 index 0000000..3deb823 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Prop/PropUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4589d02132cd17149b166619e0d928c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank.meta new file mode 100644 index 0000000..1374c3e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28a739131d6ef4540a707321873188a4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs new file mode 100644 index 0000000..23f17fa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs @@ -0,0 +1,25 @@ + + +namespace ScrewsMaster +{ + public class RankCtrl : BaseCtrl + { + public static RankCtrl Instance { get; private set; } + + private RankModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.RankModel) as RankModel; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs.meta new file mode 100644 index 0000000..0899434 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 347516c5bfac0ab40bf56ec1e6116365 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs new file mode 100644 index 0000000..7184ed3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class RankModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs.meta new file mode 100644 index 0000000..423719e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4630b3230bd34c1408b9ba41ac2d1c37 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs new file mode 100644 index 0000000..a8a9fdb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs @@ -0,0 +1,89 @@ + +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; + +namespace ScrewsMaster +{ + public class RankUI : BaseUI + { + private RankUICtrl ctrl; + private RankModel model; + private FGUI.G019_Rank.RankPanel ui; + + public RankUI(RankUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.RankUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G019_Rank"; + uiInfo.assetName = "RankPanel"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RankModel) as RankModel; + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G019_Rank.RankPanel; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + ui.CloseBtn.SetClick(()=> + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RankUI_Close); + }); + + ui.PlayName.text = PreferencesMgr.Instance.PlayerName; + ui.PlayLevel.text = GameHelper.GetLevel().ToString(); + GameHelper.SetSelfAvatar((ui.PlayIcon.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader); + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs.meta new file mode 100644 index 0000000..a26ff30 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2dea71d3bad103f479a6df56ef97d0dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs new file mode 100644 index 0000000..8a4b2af --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs @@ -0,0 +1,73 @@ + + +namespace ScrewsMaster +{ + public class RankUICtrl : BaseUICtrl + { + private RankUI ui; + private RankModel model; + + private uint openUIMsg = UICtrlMsg.RankUI_Open; + private uint closeUIMsg = UICtrlMsg.RankUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RankModel) as RankModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RankUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs.meta new file mode 100644 index 0000000..5614cd8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rank/RankUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9eca9720d4ce7704ca25e043c247e949 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView.meta new file mode 100644 index 0000000..050e3db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 105ffe75e522642359b9f7d82ff47c4f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs new file mode 100644 index 0000000..d459c05 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class RecordViewCtrl : BaseCtrl + { + public static RecordViewCtrl Instance { get; private set; } + + private RecordViewModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs.meta new file mode 100644 index 0000000..d86ccd3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c219c03fd1474d73bd17b07c7df43c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs new file mode 100644 index 0000000..98d47e3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class RecordViewModel : BaseModel + { + public List recordList = new List(); + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs.meta new file mode 100644 index 0000000..04b009d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8267bf1de4e9949828f446ca83bcacfa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs new file mode 100644 index 0000000..3d7fd2a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs @@ -0,0 +1,183 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.A000_common; +using System; +using DG.Tweening; +using FGUI.bkg_jilu; +using Unity.VisualScripting; + +namespace ScrewsMaster +{ + public class RecordViewUI : BaseUI + { + private RecordViewUICtrl ctrl; + private RecordViewModel model; + private FGUI.bkg_jilu.com_jilu ui; + + public RecordViewUI(RecordViewUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.RecordViewUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "bkg_jilu"; + uiInfo.assetName = "com_jilu"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + if (coroutine != null) + { + CrazyAsyKit.StopCoroutine(coroutine); + } + } + + protected override void OnBind() + { + ui = baseUI as FGUI.bkg_jilu.com_jilu; + } + + protected override void OnOpenBefore(object args) + { + InitView(); + + ui.btn_close.onClick.Add(() => + { + CtrlCloseUI(); + }); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + private bool isroll = false; + + private List list_panel = new List(); + + // 初始化页面逻辑 + private void InitView() + { + for (int i = 0; i < 9; i++) + { + GObject item = ui.panel.GetChild("item" + i); + list_panel.Add(item); + } + + UpdateRecord(); + } + + private Coroutine coroutine = null; + public void UpdateRecord() + { + if (ctrl.model == null || ctrl.model.recordList.Count == 0) return; + + for (int i = 0; i < ctrl.model.recordList.Count; i++) + { + if (i < list_panel.Count) + { + setRecord(i, list_panel[i]); + list_panel[i].visible = true; + } + } + + if (ctrl.model.recordList.Count >= 9 && !isroll) // 注意这里应该是 9,因为 list_panel 只有 9 个元素 + { + isroll = true; + coroutine = CrazyAsyKit.StartCoroutine(ScrollRoutine()); + } + } + + private void setRecord(int index, GObject obj) + { + com_record_item item = (com_record_item)obj; + string[] values = ctrl.model.recordList[index].Split('-'); + + item.name.text = values[0]; + item.num.text = "$" + values[1]; // 假设 money 是显示金额的字段 + + string[] parts = values[2].Split(" "); + item.time.text = parts[0]; + } + + private IEnumerator ScrollRoutine() + { + while (true) + { + int panelCount = list_panel.Count; // 缓存 list_panel 的长度 + for (int i = 0; i < panelCount; i++) + { + if (i < list_panel.Count) // 再次检查索引是否有效 + { + float targetY = list_panel[i].y - 129; + GObjectMoveFunc.MoveTween(list_panel[i], targetY); + } + } + + yield return new WaitForSeconds(1f); // 每隔1秒滚动一次 + } + } + + private void hideEvent(object sender = null) + { + + } + + private void showEvent(object sender = null) + { + + } + } + + // 定义一个非泛型静态类来包含扩展方法 + public static class GObjectMoveFunc + { + public static void MoveTween(this GObject obj, float targetY, Action action = null) + { + obj.TweenMove(new Vector2(obj.x, targetY), 0.5f) + .SetEase((EaseType)Ease.Linear) + .OnComplete(()=>{ + if (targetY <= -16) + { + // 第一个 item 放到最后一个位置 + obj.y = 1048; + } + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs.meta new file mode 100644 index 0000000..6a6e936 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1ead525ed41bd47bb87703021c40c757 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs new file mode 100644 index 0000000..96f01ac --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs @@ -0,0 +1,97 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + + +namespace ScrewsMaster + +{ + public class RecordViewUICtrl : BaseUICtrl + { + private RecordViewUI ui; + public RecordViewModel model; + + private uint openUIMsg = UICtrlMsg.RecordViewUI_Open; + private uint closeUIMsg = UICtrlMsg.RecordViewUI_Close; + + #region 生命周期 + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.RecordViewModel) as RecordViewModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RecordViewUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.AddListener(GameMsg.updateRecordList, RefreshList); + + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.RemoveListener(GameMsg.updateRecordList, RefreshList); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + + void RefreshList(object args = null) + { + if (args == null || model.recordList == null) return; + + // Debug.Log($" barry refresh args == {args}"); + // Debug.Log($" barry refresh list == {model.recordList.Count}"); + if (model.recordList.Count >= 9) + { + model.recordList.RemoveAt(0); + + } + model.recordList.Add(args.ToString()); + + ui?.UpdateRecord(); + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs.meta new file mode 100644 index 0000000..5f17d24 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RecordView/RecordViewUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f4b262c4e5a954831be8cf5baf8aff72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence.meta new file mode 100644 index 0000000..31db607 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9d69501a9c6884394bbad5449f537ea5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs new file mode 100644 index 0000000..08b0ee8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class ResurgenceCtrl : BaseCtrl + { + public static ResurgenceCtrl Instance { get; private set; } + + private ResurgenceModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs.meta new file mode 100644 index 0000000..6f01cf3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d56a2d552aac4144bd57d8ba295b6fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs new file mode 100644 index 0000000..d21dc7c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs @@ -0,0 +1,13 @@ +namespace ScrewsMaster +{ + public class ResurgenceModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs.meta new file mode 100644 index 0000000..5eb8977 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a39a114043b6494f946e195cd413673 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs new file mode 100644 index 0000000..0628b35 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs @@ -0,0 +1,302 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.failpack; +using System; +using FGUI.A000_common; +using DG.Tweening; + +namespace ScrewsMaster +{ + public class ResurgenceUI : BaseUI + { + private ResurgenceUICtrl ctrl; + private ResurgenceModel model; + private FGUI.failpack.com_resurgence ui; + + public ResurgenceUI(ResurgenceUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.ResurgenceUI; + this.ctrl = ctrl; + } + private float progress_value; + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "failpack"; + uiInfo.assetName = "com_resurgence"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.failpack.com_resurgence; + } + + protected override void OnOpenBefore(object args) + { + + Debug.Log(args); + progress_value = GameObject.Find("GameStage").GetComponent().LevelProgress * 100; + + InitView(); + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_show, 1); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + if (GameHelper.IsAdModelOfPay()) + { + HallManager.Instance.UpdateSecondEvent += InitView; + } + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + HallManager.Instance.UpdateSecondEvent += updatEevent; + updatEevent(); + } + protected override void RemoveListener() + { + if (GameHelper.IsAdModelOfPay()) + { + HallManager.Instance.UpdateSecondEvent -= InitView; + } + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + HallManager.Instance.UpdateSecondEvent -= updatEevent; + } + #endregion + private void updatEevent() + { + bool _inAdRewardCooldown = GameHelper.InAdRewardCooldown(); + ui.btn_buy.GetChild("title").visible = !_inAdRewardCooldown; + ui.btn_buy.GetChild("icon").visible = !_inAdRewardCooldown; + ui.btn_buy.GetChild("text_cooldown").visible = _inAdRewardCooldown; + ui.btn_buy.grayed = _inAdRewardCooldown; + + ui.btn_buy.GetChild("text_cooldown").text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1 && !ui.btn_buy.grayed) (ui.btn_buy.GetChild("img_saveingpot") as GImage).visible = true; + + + // ui.text_remain.text=CommonHelper.TimeFormat((int)(SaveData.GetSaveobject().failed_pack_time - Convert.ToInt32(GameHelper.GetNowTime())), CountDownType.Hour); + + } + void pay_success(object str) + { + string type = (string)str; + Debug.Log("77777777777777777777777777" + type); + if (type == MaxPayManager.fail_pack) + { + var start = GameHelper.GetUICenterPosition(ui.bg); + var rewardData = new RewardData(); + var end = GameHelper.GetUICenterPosition(ui.end_point); + int back_num = list[2].props_quantity[1]; + int out_num = list[2].props_quantity[0]; + int refresh_num = list[2].props_quantity[2]; + var rewardSingleData = new RewardSingleData(101, list[2].coins_quantity, RewardOrigin.AdTask) + { + startPosition = start, + endPosition = end + }; + + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + rewardData.AddCompleted(success => + { + // if (success) + // { + // RefreshGold(awardNum); + // } + }); + // GameHelper.AddGoldNumber(list[2].coins_quantity); + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity; + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + // GameObject.Find("GameStage").GetComponent().ClearHoleBtnClick(); + if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + // ShowScrews.Instance._isLevelOver = false; + ShowScrews.Instance.OnResurrect(); + } + DOVirtual.DelayedCall(0.1f, () => + { + CtrlCloseUI(); + }); + } + + } + private List list; + //初始化页面逻辑 + private void InitView() + { + if (SaveData.GetSaveobject().failed_pack_time < GameHelper.GetNowTime()) + { + SaveData.GetSaveobject().failed_pack_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().FailedGiftCD; + } + ui.btn_back.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close); + if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + ShowScrews.Instance._isLevelOver = false; + if (ShowScrews.Instance.GetIdleHoleCount() <= 0) ShowScrews.Instance.OnGameFailed(); + } + + }); + list = ConfigSystem.GetConfig().dataList; + int gold_num = list[2].coins_quantity; + int back_num = list[2].props_quantity[1]; + int out_num = list[2].props_quantity[0]; + int refresh_num = list[2].props_quantity[2]; + ui.text_outnum.text = "x" + out_num; + ui.text_backnum.text = "x" + back_num; + ui.text_refreshnum.text = "x" + refresh_num; + ui.text_goldnum.text = "x" + gold_num; + ui.text_progress.text = "Completion:" + Math.Round(progress_value) + "%"; + ui.progress_1.value = progress_value; + if (!GameHelper.IsAdModelOfPay()) + { + ui.pay_type.selectedIndex = 1; + + decimal price = (decimal)list[2].Paid_price2; + ui.btn_max_pay.title = "$ " + price; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_max_pay.GetChild("img_saveingpot") as GImage).visible = true; + ui.btn_max_pay.SetClick(() => + { + ApplePayClass maxPayData = new() + { + amount = (int)Math.Round(price * 100), + sku = MaxPayManager.fail_pack, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + + + return; + } + + + + + + ui.text_have.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}"; + ui.need_text.text = $"Need ADs:{list[2].Paid_price}"; + ui.btn_buy.GetChild("img_saveingpot").visible = false; + + updatEevent(); + + if (GameHelper.CheckAdWatchCount((int)list[2].Paid_price)) + { + ui.btn_buyPackClaim.visible = true; + ui.btn_buy.visible = false; + } + else + { + ui.btn_buyPackClaim.visible = false; + ui.btn_buy.visible = true; + } + ui.btn_buy.SetClick(() => + { + if (ui.btn_buy.grayed) return; + OnClickBuyPackWatchAdsBtn(); + }); + + ui.btn_buyPackClaim.SetClick(() => + { + if (GameHelper.CheckAdWatchCount((int)list[2].Paid_price)) + { + GameHelper.AddAdWatchCount(-(int)list[2].Paid_price); + + var start = GameHelper.GetUICenterPosition(ui.bg); + var rewardData = new RewardData(); + var end = GameHelper.GetUICenterPosition(ui.end_point); + + var rewardSingleData = new RewardSingleData(101, list[2].coins_quantity, RewardOrigin.AdTask) + { + startPosition = start, + endPosition = end + }; + + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + rewardData.AddCompleted(success => + { + // if (success) + // { + // RefreshGold(awardNum); + // } + }); + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity; + // GameHelper.AddGoldNumber(list[2].coins_quantity); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Close); + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + // GameObject.Find("GameStage").GetComponent().ClearHoleBtnClick(); + if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + // ShowScrews.Instance._isLevelOver = false; + ShowScrews.Instance.OnResurrect(); + } + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_buy_success, 1); + } + else + { + GameHelper.ShowTips("Insufficient AdWatchCount"); + return; + } + Debug.Log("goumaichenggong"); + + + }); + + } + + + private void OnClickBuyPackWatchAdsBtn() + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.fail_click, 1); + GameHelper.ShowVideoAd("buy_failpack", success => + { + updatEevent(); + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs.meta new file mode 100644 index 0000000..1c25402 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb8f89f92a98b4317be64d4c14d8f602 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs new file mode 100644 index 0000000..8a28e27 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs @@ -0,0 +1,76 @@ +using System.Collections; +using System.Collections.Generic; + + +namespace ScrewsMaster + +{ + public class ResurgenceUICtrl : BaseUICtrl + { + private ResurgenceUI ui; + private ResurgenceModel model; + + private uint openUIMsg = UICtrlMsg.ResurgenceUI_Open; + private uint closeUIMsg = UICtrlMsg.ResurgenceUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.ResurgenceModel) as ResurgenceModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new ResurgenceUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs.meta new file mode 100644 index 0000000..9dd7412 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Resurgence/ResurgenceUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad517c5a5d56648249afb6f3adb0582d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive.meta new file mode 100644 index 0000000..8462d4f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b215b00ca74232d46a3e958514a2068b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs new file mode 100644 index 0000000..083ce98 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs @@ -0,0 +1,25 @@ + + +namespace ScrewsMaster +{ + public class ReviveCtrl : BaseCtrl + { + public static ReviveCtrl Instance { get; private set; } + + private ReviveModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.ReviveModel) as ReviveModel; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs.meta new file mode 100644 index 0000000..1dc0a75 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 53a0e00701127434680a1c04854804f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs new file mode 100644 index 0000000..f736fb3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class ReviveModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs.meta new file mode 100644 index 0000000..33b9e67 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 715570fb13192e143aea595fafb8362b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs new file mode 100644 index 0000000..7d224d7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs @@ -0,0 +1,171 @@ + +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; +using DG.Tweening; +using Roy.Datas; +using SGame; + +namespace ScrewsMaster +{ + public class ReviveUI : BaseUI + { + private ReviveUICtrl ctrl; + private ReviveModel model; + private FGUI.G008_reward.com_revive ui; + + private bool isRevive; + + public ReviveUI(ReviveUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.ReviveUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_revive"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + model = ModuleManager.Instance.GetModel(ModelConst.ReviveModel) as ReviveModel; + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_revive; + } + + protected override void OnOpenBefore(object args) + { + isRevive = false; + ui.cont_iswacth.selectedIndex = GameHelper.GetIsWacthAd(); + + InitView(); + } + + protected override void OnOpen(object args) + { + + } + + protected override void OnHide() + { + + } + + protected override void OnDisplay(object args) + { + + } + + protected override void OnCloseUIAnimEnd() + { + base.OnCloseUIAnimEnd(); + if (isRevive) + { + ShowScrews.Instance.OnResurrect(); + } + + } + + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + ui.cont_iswacth.selectedIndex = GameHelper.GetIsWacthAd(); + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_AdRevive.GetChild("img_saveingpot") as GImage).visible = true; + + ui.btn_AdRevive.onClick.Add(() => + { + //观看广告复活 + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + ui.btn_back.SetClick(() => { }); + ui.btn_close.SetClick(() => { }); + ui.btn_revive.SetClick(() => { }); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameHelper.SetIsWatchAd(1); + GameHelper.SetReviveCount(); + isRevive = true; + ctrl.CloseUI(); + } + }); + }); + + var revivalCoins = ConfigSystem.GetConfig().RevivalCoins; + if (ui.btn_revive is btn_revive btnRevive) btnRevive.txt_coin.text = revivalCoins.ToString(); + ui.btn_revive.onClick.Add(() => + { + if (!GameHelper.CheckGoldNumber(revivalCoins)) + { + GameHelper.ShowTips("Not Enough Coins"); + return; + } + //消耗金币复活 + GameHelper.AddGoldNumber(-revivalCoins); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + //CtrlCloseUI(); + GameHelper.SetIsWatchAd(2); + GameHelper.SetReviveCount(); + isRevive = true; + ctrl.CloseUI(); + }); + + ui.btn_close.onClick.Add(() => + { + ctrl.CloseUI(); + float[] cash_array = GameHelper.GetRewardValue(2); + + var temp = new SettlementData + { is_success = false, cash_number = cash_array[0], is_level_success = true, is_h5_reward = false }; + + DOVirtual.DelayedCall(0.5f, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp); + }); + }); + + ui.btn_back.onClick.Add(() => + { + ctrl.CloseUI(); + float[] cash_array = GameHelper.GetRewardValue(2); + + var temp = new SettlementData + { is_success = false, cash_number = cash_array[0], is_level_success = true, is_h5_reward = false }; + + DOVirtual.DelayedCall(0.5f, () => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LevelSuccessUI_Open, temp); + }); + }); + + } + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs.meta new file mode 100644 index 0000000..0949e76 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 976df284e6e1b174fa1ecc9b6897b44c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs new file mode 100644 index 0000000..aa9a8ba --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs @@ -0,0 +1,73 @@ + + +namespace ScrewsMaster +{ + public class ReviveUICtrl : BaseUICtrl + { + private ReviveUI ui; + private ReviveModel model; + + private uint openUIMsg = UICtrlMsg.ReviveUI_Open; + private uint closeUIMsg = UICtrlMsg.ReviveUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.ReviveModel) as ReviveModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new ReviveUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs.meta new file mode 100644 index 0000000..6d0d26b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Revive/ReviveUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fbc37ced5acf9bf498bd7fc434f091b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward.meta new file mode 100644 index 0000000..41a7e75 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8015cd6a16829b84ba5fb2e69639b50e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs new file mode 100644 index 0000000..c7086a0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs @@ -0,0 +1,20 @@ +namespace ScrewsMaster +{ + public class RewardCtrl : BaseCtrl + { + public static RewardCtrl Instance { get; private set; } + + private RewardModel model; + + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs.meta new file mode 100644 index 0000000..3909cf0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 023b95f4724e6cf42bb2d4120727a19e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs new file mode 100644 index 0000000..532d954 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs @@ -0,0 +1,17 @@ +namespace ScrewsMaster +{ + public class RewardModel : BaseModel + { + public RewardData rewardInfo; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs.meta new file mode 100644 index 0000000..d7e01fa --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb3dd4b7d103a7a448334bc32eecf18e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs new file mode 100644 index 0000000..e1544ba --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs @@ -0,0 +1,166 @@ +using Spine.Unity; + +namespace ScrewsMaster +{ + using System; + using System.Linq; + using DG.Tweening; + using FairyGUI; + + public class RewardUI : BaseUI + { + private RewardUICtrl ctrl; + private RewardModel model; + private FGUI.G008_reward.com_reward ui; + + private bool isMultiple = false; + private Action closeCallback; + + public RewardUI(RewardUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.RewardUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_reward"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + protected override void OnInit() + { + model = moduleManager.GetModel(ModelConst.RewardModel) as RewardModel; + } + + protected override void OnClose() + { + tween?.Kill(); + CommonHelper.FadeOut(ui); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_reward; + } + + protected override void OnOpenBefore(object args) + { + if (args != null) + { + model.rewardInfo = (RewardData)args; + } + + InitData(); + InitView(); + } + + protected override void OnOpen(object args) + { + CommonHelper.FadeIn(ui); + if (GetRewardOrigin() == RewardOrigin.H5Icon) + { + uiMask.touchable = false; + } + } + + private void InitData() + { + foreach (var rewardSingleData in model.rewardInfo.GetRewardDataList() + .Where(rewardSingleData => rewardSingleData.multiRate == 1)) + { + rewardSingleData.multiRate = rewardSingleData.origin == RewardOrigin.Play + ? GameHelper.GetQuizRate() + : GameHelper.GetVideoRate(); + } + } + + private void InitView() + { + AudioManager.Instance.PlayDynamicEffect("reward_show"); + if (GetRewardOrigin() == RewardOrigin.H5Icon) + { + uiMask.touchable = false; + } + + var value = GetRewardValue(); + ui.text_num.text = GameHelper.Get102Str(value); + + DOVirtual.DelayedCall(0.2f, () => + { + var gamwin = + FXManager.Instance.SetFx(ui.fx_place, Fx_Type.gamwin, ref closeCallback); + gamwin.state.SetAnimation(0, "out", true); + }); + + ui.btn_nor.SetClick(OnClickCollect); + ui.btn_collect.SetClick(OnClickCollect); + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_multi.GetChild("img_saveingpot") as GImage).visible = true; + SetName(); + SetAvatar(); + Set101(); + } + + private Tween tween; + + public void Set101(decimal cash = -1) + { + if (cash < 0) + { + cash = GameHelper.Get102(); + } + + // ui.text_num1.text = $"{GameHelper.Get101Str(cash)}"; + } + + private void SetAvatar() + { + // GameHelper.SetSelfAvatar(((btn_avatar)ui.btn_av).loader_avatar); + } + + private void SetName() + { + // GameHelper.SetName(ui.text_name); + } + + private RewardSingleData GetRewardData(int index = 0) + { + return model.rewardInfo.GetRewardDataList()[index]; + } + + private decimal GetRewardValue(int index = 0) + { + return GetRewardData(index).value; + } + + private RewardOrigin GetRewardOrigin(int index = 0) + { + return GetRewardData(index).origin; + } + + private void OnClickCollect() + { + isMultiple = false; + GetReward(); + CtrlCloseUI(); + GameHelper.ShowInterstitial("interstitial_skip"); + } + + public void GetReward() + { + if (isMultiple) + { + foreach (var rewardSingleData in model.rewardInfo.GetRewardDataList()) + { + rewardSingleData.rate = rewardSingleData.multiRate; + } + } + + RewardSystem.GetReward(model.rewardInfo); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs.meta new file mode 100644 index 0000000..93b2141 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e19f0dc1937b2c4ca00f87b9a5674b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs new file mode 100644 index 0000000..d764747 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs @@ -0,0 +1,60 @@ +namespace ScrewsMaster +{ + public class RewardUICtrl : BaseUICtrl + { + private RewardUI ui; + private RewardModel model; + + private uint openUIMsg = UICtrlMsg.RewardUI_Open; + private uint closeUIMsg = UICtrlMsg.RewardUI_Close; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RewardUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui is { isClose: false }) + { + ui.Close(); + } + + ui = null; + } + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs.meta new file mode 100644 index 0000000..e420160 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Reward/RewardUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 693c512ebd1e2b94cbbd530eedf38c07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew.meta new file mode 100644 index 0000000..5ca02d9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d3e53dbb0bd4945fcb8b09c25ee8debb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs new file mode 100644 index 0000000..88d4dd9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class RewardMulNewCtrl : BaseCtrl + { + public static RewardMulNewCtrl Instance { get; private set; } + + private RewardMulNewModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs.meta new file mode 100644 index 0000000..73199e3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad6b6ad714766497bab936fd94a74d9e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs new file mode 100644 index 0000000..705e4a2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs @@ -0,0 +1,13 @@ +namespace ScrewsMaster +{ + public class RewardMulNewModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs.meta new file mode 100644 index 0000000..2f9079d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de45ca22a6e504abca9a1fc7b66af5f1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs new file mode 100644 index 0000000..76bbcbc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs @@ -0,0 +1,206 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.bkg_reward_new; +using System; +using DG.Tweening; + +namespace ScrewsMaster +{ + public class RewardMulNewUI : BaseUI + { + private RewardMulNewUICtrl ctrl; + private RewardMulNewModel model; + private FGUI.bkg_reward_new.com_reward_mul ui; + private Action closeCallback; + private GiftData rewardInfo; + bool hasCoin = false; + decimal m_coinReward = 0; + public RewardMulNewUI(RewardMulNewUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.RewardMulNewUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "bkg_reward_new"; + uiInfo.assetName = "com_reward_mul"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + + protected override void OnInit() + { + + } + + protected override void OnClose() + { + + } + + protected override void OnBind() + { + ui = baseUI as FGUI.bkg_reward_new.com_reward_mul; + + } + + protected override void OnOpenBefore(object args) + { + rewardInfo = (GiftData)args; + InitView(); + } + + protected override void OnOpen(object args) + { + + } + + + + private void InitView() + { + // AudioManager.Instance.PlayDynamicEffect(AudioConst.reward_show); + ui.node_coin.visible = false; + ui.node_undo.visible = false; + ui.node_move_out.visible = false; + ui.node_refresh.visible = false; + ui.add_undo.visible = false; + ui.add_move_out.visible = false; + ui.add_refresh.visible = false; + + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) { + (ui.btn_mul.GetChild("img_saveingpot") as GImage).visible = true; + } else { + (ui.btn_mul.GetChild("img_saveingpot") as GImage).visible = false; + } + + + for (int i = 0; i < rewardInfo.type.Count; i++) { + if (rewardInfo.type[i] == (int)GiftType.coin) { + hasCoin = true; + ui.node_coin.visible = true; + ui.node_coin.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + } else if (rewardInfo.type[i] == (int)GiftType.undo) { + ui.node_undo.visible = true; + ui.node_undo.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + ui.add_undo.visible = true; + ui.add_undo.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + } else if (rewardInfo.type[i] == (int)GiftType.move_out) { + ui.node_move_out.visible = true; + ui.node_move_out.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + ui.add_move_out.visible = true; + ui.add_move_out.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + } else if (rewardInfo.type[i] == (int)GiftType.refresh) { + ui.node_refresh.visible = true; + ui.node_refresh.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + ui.add_refresh.visible = true; + ui.add_refresh.GetChild("lab_num").text = "x" + rewardInfo.reward[i]; + } + } + + ui.btn_mul.SetClick(() => { + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + GameHelper.ShowTips("Successfully claimed"); + + getReward(2); + playCoinAni(); + + ui.ani_group.visible = true; + ui.t0.Play(() => { + ui.ani_group.visible = false; + }); + } + }); + }); + + ui.btn_claim.SetClick(() => + { + ui.btn_claim.SetClick(() => { }); + ui.btn_mul.SetClick(() => { }); + getReward(1); + playCoinAni(); + DOVirtual.DelayedCall(2f, () => + { + GameHelper.AddAdWatchCount(1); + }); + + ui.ani_group.visible = true; + ui.t0.Play(() => { + ui.ani_group.visible = false; + }); + }); + } + + private void getReward(int rate = 1) { + for (int i = 0; i < rewardInfo.type.Count; i++) { + if (rewardInfo.type[i] == (int)GiftType.coin || rewardInfo.type[i] == 101) { + m_coinReward = rewardInfo.reward[i] * rate; + } else if (rewardInfo.type[i] == (int)GiftType.undo) { + int num = GameHelper.GetItemNumber(ItemEnum.MergeBox) + rewardInfo.reward[i] * rate; + GameHelper.SetItemNumber(ItemEnum.MergeBox, num); + ui.add_undo.GetChild("lab_num").text = "x" + rewardInfo.reward[i] * rate; + } else if (rewardInfo.type[i] == (int)GiftType.move_out) { + int num = GameHelper.GetItemNumber(ItemEnum.AddHole) + rewardInfo.reward[i] * rate; + GameHelper.SetItemNumber(ItemEnum.AddHole, num); + ui.add_move_out.GetChild("lab_num").text = "x" + rewardInfo.reward[i] * rate; + } else if (rewardInfo.type[i] == (int)GiftType.refresh) { + int num = GameHelper.GetItemNumber(ItemEnum.ClearHole) + rewardInfo.reward[i] * rate; + GameHelper.SetItemNumber(ItemEnum.ClearHole, num); + ui.add_refresh.GetChild("lab_num").text = "x" + rewardInfo.reward[i] * rate; + } + } + } + + private bool isget=false; + private void playCoinAni() + { + if (!hasCoin) { + GameDispatcher.Instance.Dispatch(GameMsg.rewardMul_close); + CtrlCloseUI(); + return; + } + + if(isget) return; + isget=true; + var rewardData = new RewardData(); + + int curr_type = 101; + Vector2 end_ = GameHelper.GetUICenterPosition(ui.node_end, true); + + + var rewardSingleData = new RewardSingleData(curr_type, m_coinReward, RewardOrigin.Play) + { + startPosition = GameHelper.GetUICenterPosition(ui.btn_mul, true), + endPosition = new Vector2(end_.x + 30, end_.y + 30), + }; + + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + rewardData.AddCompleted(success => + { + if (success) + { + DOVirtual.DelayedCall(0.7f, () => + { + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.rewardMul_close); + CtrlCloseUI(); + }); + } + }); + + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs.meta new file mode 100644 index 0000000..5fbbd21 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4490553e4e1f94f1bba8ad923fbb61c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs new file mode 100644 index 0000000..64697f4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs @@ -0,0 +1,76 @@ +using System.Collections; +using System.Collections.Generic; + + +namespace ScrewsMaster + +{ + public class RewardMulNewUICtrl : BaseUICtrl + { + private RewardMulNewUI ui; + private RewardMulNewModel model; + + private uint openUIMsg = UICtrlMsg.RewardMulNewUI_Open; + private uint closeUIMsg = UICtrlMsg.RewardMulNewUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RewardMulNewModel) as RewardMulNewModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RewardMulNewUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs.meta new file mode 100644 index 0000000..9ada3eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/RewardMulNew/RewardMulNewUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0c90cdcc991c64c09a5c46a37c7ea15d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox.meta new file mode 100644 index 0000000..c7d5e9b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b666ed4a77d633844983f9959f96256d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs new file mode 100644 index 0000000..10d65f7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class RewardboxCtrl : BaseCtrl + { + public static RewardboxCtrl Instance { get; private set; } + + private RewardboxModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.RewardboxModel) as RewardboxModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs.meta new file mode 100644 index 0000000..ef23779 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 475737b2327d44d4ea721739dc354479 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs new file mode 100644 index 0000000..d3fa8f5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs @@ -0,0 +1,43 @@ +namespace ScrewsMaster +{ + public class RewardboxModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs.meta new file mode 100644 index 0000000..897a33c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 94870495d6abb40eaaca680d24852477 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs new file mode 100644 index 0000000..290e9a7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs @@ -0,0 +1,103 @@ +using FairyGUI; +using FGUI.A000_common; + +namespace ScrewsMaster +{ + public class RewardboxUI : BaseUI + { + private RewardboxUICtrl ctrl; + private RewardboxModel model; + private FGUI.G008_reward.com_rewardbox ui; + + public RewardboxUI(RewardboxUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.RewardboxUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G008_reward"; + uiInfo.assetName = "com_rewardbox"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RewardboxModel) as RewardboxModel; + } + + protected override void OnClose() + { + GameHelper.showGameUI = true; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G008_reward.com_rewardbox; + } + + protected override void OnOpenBefore(object args) + { + + if (GameHelper.IsGiftSwitch()) ui.switchgift.selectedIndex = 1; + else ui.switchgift.selectedIndex = 0; + // (ui.btn_lookad as btn_tabad).color.selectedIndex = btn_tabad.Color_green; + float[] cash_array = GameHelper.GetRewardValue(2); + ui.btn_lookad.SetClick(() => + { + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + GameDispatcher.Instance.Dispatch(GameMsg.Ad_success, cash_array[0]); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Close); + } + }); + + }); + ui.btn_close.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Close); + GameHelper.AddInterAdNumber(); + }); + ui.gold_text.text = string.Format(ui.gold_text.text, cash_array[0]); + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) (ui.btn_lookad.GetChild("img_saveingpot") as GImage).visible = true; + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs.meta new file mode 100644 index 0000000..87f53ba --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 107c313d002eb42708a62beb702590ed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs new file mode 100644 index 0000000..1828406 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs @@ -0,0 +1,71 @@ +namespace ScrewsMaster +{ + public class RewardboxUICtrl : BaseUICtrl + { + private RewardboxUI ui; + private RewardboxModel model; + + private uint openUIMsg = UICtrlMsg.RewardboxUI_Open; + private uint closeUIMsg = UICtrlMsg.RewardboxUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RewardboxModel) as RewardboxModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RewardboxUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs.meta new file mode 100644 index 0000000..86c52d9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Rewardbox/RewardboxUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 694209ebe845a485f81ac656bf536fb7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot.meta new file mode 100644 index 0000000..ec86d02 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cf6626ab657fa49eb95157b5a2f5475c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs new file mode 100644 index 0000000..a109016 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class SaveingPotCtrl : BaseCtrl + { + public static SaveingPotCtrl Instance { get; private set; } + + private SaveingPotModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs.meta new file mode 100644 index 0000000..b4367e4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9e59681e9218143e58eea10a87070d4a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs new file mode 100644 index 0000000..7005777 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs @@ -0,0 +1,13 @@ +namespace ScrewsMaster +{ + public class SaveingPotModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs.meta new file mode 100644 index 0000000..6622e3d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ffa8bfa81fde34182899a4958a8aa4c1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs new file mode 100644 index 0000000..70ef065 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs @@ -0,0 +1,772 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.SaveingPot; +using System; +using System.Linq; +using UnityEngine.PlayerLoop; +using Spine.Unity; +using DG.Tweening; +using FGUI.G018_GameHome; + +namespace ScrewsMaster +{ + public class SaveingPotUI : BaseUI + { + private SaveingPotUICtrl ctrl; + private SaveingPotModel model; + private FGUI.SaveingPot.com_saveingpot ui; + + private SaveingPotClass makeupTaskData; + public int ad_cool_down = 120; + private int broadtime = 1; + + public SaveingPotUI(SaveingPotUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.SaveingPotUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "SaveingPot"; + uiInfo.assetName = "com_saveingpot"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= updateSpeedCD; + closeCallback?.Invoke(); + WebviewManager.Instance.SetDarkThough(true); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot); + } + private SkeletonAnimation ske_pot; + protected override void OnBind() + { + ui = baseUI as FGUI.SaveingPot.com_saveingpot; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + {//刘海屏 + ui.group_.y += Screen.safeArea.y; + } + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Close); + ske_pot = FXManager.Instance.SetFx(ui.ani_potparent, Fx_Type.fx_savepot, ref closeCallback); + ske_pot.state.SetAnimation(0, "edie", true); + WebviewManager.Instance.SetDarkThough(false); + SaveingPotHelper.TestingClearTime(); + makeupTaskData = SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1]; + // makeupTaskData.H5Time = 99999999999999; + ui.btn_close.SetClick(() => + { + CtrlCloseUI(); + }); + ui.btn_close1.SetClick(() => + { + CtrlCloseUI(); + }); + InitView(); + ui.btn_watch.SetClick(WatchBtnClick); + ad_cool_down = ConfigSystem.GetConfig().WithdrawalaccelerationCD; + HallManager.Instance.UpdateSecondEvent += updateSpeedCD; + updateSpeedCD(); + InitBroadCast(); + + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + private Action closeCallback; + //初始化页面逻辑 + private void InitView() + { + Debug.Log(PreferencesMgr.Instance.ExchangeAccount); + Makeup_2 makeupVo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + ui.text_ad.text = "1. Earn " + makeupVo.ADIncrease + " USD for each ad you watch "; + ui.text_pay.text = "2. Pay USD for " + makeupVo.PayIncrease + " times cashback."; + initTop(); + + ui.text_lose.text = string.Format(ui.text_lose.text, SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash)); + ske_pot.SetActive(false); + if (makeupTaskData.needShowAni) + { + Debug.Log("showani"); + ui.type.selectedIndex = 0; + + ui.text_cashprogress.text = SaveingPotHelper.getCashNumber(SaveData.GetSaveobject().saveingpot_cash) + "/" + SaveingPotHelper.getCashNumber(makeupTaskData.amount); + ui.progress_cash.value = (SaveData.GetSaveobject().saveingpot_cash / makeupTaskData.amount) * 100; + + ske_pot.SetActive(true); + if (SaveData.GetSaveobject().saveingpot_cash < makeupTaskData.amount) + { + ui.btn_cash.title = "Go"; + ui.btn_cash.SetClick(() => + { + CtrlCloseUI(); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open, false); + }); + + } + + else + { + ui.btn_cash.SetClick(() => + { + makeupTaskData.needShowAni = false; + SaveData.saveDataFunc(); + InitView(); + }); + } + if (SaveData.GetSaveobject().saveingpot_cash > SaveData.GetSaveobject().last_saveingpot_cash) + { + DOVirtual.Float(SaveData.GetSaveobject().last_saveingpot_cash, SaveData.GetSaveobject().saveingpot_cash, 1, + value => { ui.text_nowcash.text = SaveingPotHelper.getCashString(value); }); + ske_pot.state.SetAnimation(0, "getcash", false); + ske_pot.state.Complete += (a) => + { + ske_pot.state.SetAnimation(0, "edie", true); + }; + + } + else ui.text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash); + SaveData.GetSaveobject().last_saveingpot_cash = SaveData.GetSaveobject().saveingpot_cash; + SaveData.saveDataFunc(); + } + else if (makeupTaskData.status == SaveingPotTaskStatus.None) + { + if (PreferencesMgr.Instance.ExchangeAccount == null) + { + Debug.Log("enter"); + OnEnter(); + } + else + { + OnConfirm(); + } + } + else if (makeupTaskData.status == SaveingPotTaskStatus.Task) + { + OnTask(); + } + else if (makeupTaskData.status == SaveingPotTaskStatus.Inline) + { + OnInline(); + Debug.Log("inline"); + } + + } + void WatchBtnClick() + { + + if (GameHelper.GetNowTime() <= PlayerPrefs.GetInt($"speed_ad_cool_times_pot", 0) + ad_cool_down) + { + Debug.Log("not click"); + return; + } + + GameHelper.ShowVideoAd("reward_OpeningDollarBills", isSuccess => + { + if (isSuccess) + { + ui.btn_watch.enabled = false; + // TimerHelper.mEasy.AddTimer(1.5f, () => + // { + var ad_times = Convert.ToInt32(GameHelper.GetNowTime()); + PlayerPrefs.SetInt($"speed_ad_cool_times_pot", ad_times); + InitView(); + // }); + } + }); + + // var adNum = PreferencesMgr.Instance.RealWatchVideo; + // Debug.Log($"adNum========: {adNum}"); + + } + void updateSpeedCD() + { + broadtime++; + BroadCast(); + if (makeupTaskData.needShowAni) + { + ui.text_remaintime.text = CommonHelper.TimeFormat((int)makeupTaskData.clear_time - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + + } + if (SaveingPotHelper.TestingClearTime()) + { + InitView(); + } + var lastTimes = PlayerPrefs.GetInt($"speed_ad_cool_times_pot", 0); + if (GameHelper.GetNowTime() < lastTimes + ad_cool_down) + { + ui.btn_watch.enabled = false; + ui.btn_watch.show_cd.selectedIndex = 1; + ui.btn_watch.text_cd.text = CommonHelper.TimeFormat( + lastTimes + ad_cool_down - Convert.ToInt32(GameHelper.GetNowTime()), + CountDownType.Hour); + } + else + { + + ui.btn_watch.enabled = true; + ui.btn_watch.show_cd.selectedIndex = 0; + } + + } + + private void OnInline() + { + CheckBtnWatchStatus(); + + ui.type.selectedIndex = 5; + + + CheckActive(makeupTaskData.tableId); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + + + RefreshRecordData(); + } + + private void RefreshRecordData() + { + var data = makeupTaskData; + if (data.inlineNum <= 1) + { + ui.type.selectedIndex = 6; + ui.text_payhint.text = "You will get the " + makeupTaskData.amountStr + " for 90 days"; + ui.text_query.text = PreferencesMgr.Instance.ExchangeAccount; + ui.btn_confirm.SetClick(() => + { + CtrlCloseUI(); + }); + return; + + } + var com_rank = ui.com_newRecord.com_rank; + var com_cord = ui.com_newRecord.com_cord; + + com_cord.email_text.text = PreferencesMgr.Instance.ExchangeAccount; + + + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == data.tableId); + if (redeemVOModel == null) return; + + if (redeemVOModel.AD_Limit_times <= data.WatchVideoSpeedNum) + { + ui.btn_watch.enabled = false; + ui.btn_watch.visible = false; + com_rank.content1.selectedIndex = 1; + com_rank.text_rank1.SetVar("rank", data.WatchVideoSpeedNum.ToString()).FlushVars(); + } + else + { + ui.btn_watch.enabled = true; + ui.btn_watch.visible = true; + com_rank.content1.selectedIndex = 0; + com_rank.text_rank1.SetVar("rank", redeemVOModel.AD_Down.ToString()).FlushVars(); + } + + if (redeemVOModel.Login_Limit_times <= data.loginSpeedNum) + { + com_rank.content2.selectedIndex = 1; + com_rank.text_rank2.SetVar("rank", redeemVOModel.Login_Limit_times.ToString()).FlushVars(); + } + else + { + com_rank.content2.selectedIndex = 0; + var loginRans = GameHelper.GetCommonModel().inlineLoginDown[0] + "-" + GameHelper.GetCommonModel().inlineLoginDown[1]; + com_rank.text_rank2.SetVar("rank", loginRans).FlushVars(); + } + + if (redeemVOModel.Active_Limit_times <= data.activeSpeedNum) + { + com_rank.content3.selectedIndex = 1; + com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_Limit_times.ToString()).FlushVars(); + } + else + { + com_rank.content3.selectedIndex = 0; + + com_rank.text_rank3.SetVar("time", redeemVOModel.Active_time.ToString()).FlushVars(); + com_rank.text_rank3.SetVar("rank", redeemVOModel.Active_time_Down.ToString()).FlushVars(); + + if (CommonHelper.activeTimes_saveingpot.TryGetValue(data.tableId, out int openTimes)) + { + //Debug.Log($"openTimes ===== {openTimes}, data.tableId=== activeTimes_saveingpot_{data.tableId}"); + if (openTimes > 1) + { + //活跃的分钟数 + int min_num = ((int)Time.time - data.activeMinute) / 60; + + //是配置的活跃时间的多少倍 + int active_times = min_num / redeemVOModel.Active_time; + + //Debug.Log($"min_num=== {min_num} {active_times} "); + if (active_times > 0) + { + data.activeMinute = (int)Time.time; + // 可以加速多少排名 + int rank_num = active_times * redeemVOModel.Active_time_Down; + var last = data.activeSpeedNum; + data.activeSpeedNum += rank_num; + //Debug.Log($"rank_num=== {rank_num} {last} {data.activeSpeedNum} {redeemVOModel.Active_Limit_times}"); + if (data.activeSpeedNum > redeemVOModel.Active_Limit_times) + { + rank_num = redeemVOModel.Active_Limit_times - last; + data.activeSpeedNum = redeemVOModel.Active_Limit_times; + } + data.inlineNum -= rank_num; + + //Debug.Log($"订单为: {data.tableId} 通过活跃时间减少的排名为:{rank_num}"); + + if (data.inlineNum < GameHelper.GetCommonModel().inlineMin) + { + data.inlineNum = GameHelper.GetCommonModel().inlineMin; + } + } + } + else + { + data.activeMinute = (int)Time.time; + } + } + } + + com_cord.text_amt.text = $"+{data.amountStr}"; + if (data.order_time != 0) + { + com_cord.time_text.text = DateTimeManager.Instance.TimestampToString(data.order_time); + } + + com_rank.text_ranks.text = data.inlineNum.ToString(); + com_cord.number_text.text = data.inlineNum + "/" + data.inlineInitNum; + + } + private void CheckActive(int index) + { + if (CommonHelper.activeTimes_saveingpot.TryGetValue(index, out int value)) + { + value++; + // Debug.Log($"CheckActive2: {index} {value}"); + CommonHelper.activeTimes_saveingpot[index] = value; + + } + else + { + CommonHelper.activeTimes_saveingpot.Add(index, 1); + } + + } + void CheckBtnWatchStatus() + { + var data = makeupTaskData; + + if (data == null) + { + return; + } + var CardRedeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == data.tableId); + if (CardRedeemVOModel == null) return; + + bool isShow = CardRedeemVOModel.AD_Limit_times > data.WatchVideoSpeedNum && data.inlineNum > GameHelper.GetCommonModel().inlineMin; + + ui.btn_watch.enabled = isShow; + + } + private void OnConfirm() + { + ui.type.selectedIndex = 3; + + Makeup_2 vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + if (vo == null) + { + return; + } + + // ui.text_condi1.SetVar("cash", GameHelper.Get102Str(vo.item_need)).FlushVars(); + // ui.pb_condi1.max = vo.item_need; + // var curValue = Math.Min(PreferencesMgr.Instance.Currency102, vo.item_need); + // ui.pb_condi1.value = (double)curValue; + // ui.pay_text1.text = + // String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios", + // (ConfigSystem.GetConfig().purchase1 + ",00")); + // var textTitle = ui.pb_condi1.GetChild("title"); + // if (textTitle != null) + // { + // textTitle.text = "$" + GameHelper.Get102Str(curValue) + "/" + "$" + GameHelper.Get102Str(vo.item_need); + // } + + + float taskTime = (int)((float)vo.task_need / 60 * 100) * 0.01F; + float completeTaskTime = (int)((float)makeupTaskData.H5Time / 60 * 100) * 0.01F; + float completeTaskValue = Math.Min(completeTaskTime, taskTime); + ui.text_condi2.text = taskTime.ToString(); + ui.pb_condi2.max = taskTime; + ui.pb_condi2.value = completeTaskValue; + ui.pb_condi2.title.text = $"{completeTaskValue}/{taskTime}"; + Debug.Log(taskTime); + Debug.Log(completeTaskTime); + Debug.Log(completeTaskValue); + // if (PreferencesMgr.Instance.MakeupTaskH5Time < vo.task_need && AppConst.isPt()) + // { + // ui.show_pay.selectedIndex = com_confirm.Show_pay_true; + // } + // else ui.show_pay.selectedIndex = com_confirm.Show_pay_false; + + //ui.text_wallet.SetVar("Payer", "$").FlushVars(); + // if (AppConst.isPt()) ui.text_wallet.text = "Pix"; + ui.text_cash.text = makeupTaskData.GetAmountStr(); + ui.text_account.text = PreferencesMgr.Instance.ExchangeAccount; + + if (completeTaskTime >= taskTime) + { + ui.cont_confirm.selectedIndex = 0; + ui.btn_confirm.SetClick(() => + { + AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone); + + makeupTaskData.SetStatus(SaveingPotTaskStatus.Task); + // PreferencesMgr.Instance.SaveMakeupTaskHistory(); + OnTask(); + }); + } + else + { + // ui.cont_confirm.selectedIndex = 1; + ui.btn_confirm.SetClick(() => + { + // AudioManager.Instance.PlayDynamicEffect(AudioConst.MakeupDone); + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open); + //GameDispatcher.Instance.Dispatch(GameMsg.MainTab, 1); + if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close); + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + } + CtrlCloseUI(); + }); + } + } + private void OnTask() + { + var vo = ConfigSystem.GetConfig().GetData(makeupTaskData.tableId); + if (vo == null) + { + return; + } + ui.type.selectedIndex = 4; + ui.com_task.text_orderid.text = makeupTaskData.orderID; + ui.com_task.text_task_title.SetVar("ad", vo.ad_need.ToString()).FlushVars(); + ui.com_task.text_ads.text = $"{makeupTaskData.videoCount}/{vo.ad_need}"; + //if (AppConst.isPt() && makeupTaskData.videoCount < vo.ad_need) ui.com_task.lang.selectedIndex = com_task.Lang_pt; + //else ui.com_task.lang.selectedIndex = com_task.Lang_en; + // ui.com_task.pay_text1.text = String.Format("Pague [color=#18a218][size=44]R${0}[/size][/color] para pular anúncios", + // (ConfigSystem.GetConfig().purchase2 + ",00")); + ui.com_task.text_payer.SetVar("amt", makeupTaskData.GetAmountStr()).FlushVars(); + if (makeupTaskData.videoCount >= vo.ad_need) + { + ui.com_task.cont_process.selectedIndex = 1; + } + else ui.com_task.cont_process.selectedIndex = 0; + ui.btn_confirm.SetClick(() => + { + if (makeupTaskData.videoCount >= vo.ad_need) + { + GameHelper.ShowLoading(1, 2, () => + { + ConsumeSystem.Consume(vo.item, vo.item_need, isSuccess => + { + makeupTaskData.SetStatus(SaveingPotTaskStatus.Inline); + makeupTaskData.inlineInitNum = + CommonHelper.RandomRange(ConfigSystem.GetConfig().inlineInitNum[0], + ConfigSystem.GetConfig().inlineInitNum[1]); + makeupTaskData.inlineNum = CommonHelper.RandomRange( + ConfigSystem.GetConfig().inlineInitNum[0], + makeupTaskData.inlineInitNum); + makeupTaskData.order_time = GameHelper.GetNowTime(); + // PreferencesMgr.Instance.SaveMakeupTaskHistory(); + //OnInline(); + SaveData.GetSaveobject().saveingpot_cash -= vo.item_need; + SaveingPotHelper.CreatSaveingPotItem(); + // Debug.Log(JsonConvert.SerializeObject(vo)); + if (vo.id == 1) + { + NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash1, 1); + } + else if (vo.id == 2) + { + NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash2, 1); + } + else if (vo.id == 3) + { + NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_cash3, 1); + } + if (vo.id != 3) + { + // cash_index++; + } + InitView(); + + if (vo.id == 3) + { + // PlayerPrefs.SetInt("cash_lv", 2); + makeupTaskData = SaveData.GetSaveobject().saveingpot_history.Last(); + } + + }); + }); + + } + else + { + if (UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.GameHomeUI_Close); + var level = ShowScrews.Instance.gameMode == GameHome.Mode_difficult ? 1 : GameHelper.GetLevel(); ; + ShowScrews.Instance.InitLogic(level); + AudioManager.Instance.PlayBGM(AudioConst.PlayingBg); + } + CtrlCloseUI(); + + //UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.H5UI_Open); + // MainTabUI.getIns().OnGameTab(1); + } + }); + } + private void OnEnter() + { + GTextInput enter_input = null; + + enter_input = ui.com_info.enter_email; + + + ui.type.selectedIndex = 1; + ui.btn_confirm.SetClick(() => + { + var account = enter_input.text.Replace(" ", ""); + if (account == null || account == "") + { + GameHelper.ShowTips("Please enter the correct account information1", true); + return; + } + + if (!GameHelper.CheckAccountValidly(account)) + { + GameHelper.ShowTips("Please enter the correct account information2", true); + return; + } + + var fname = ui.com_fname.enter_fname.text.Replace(" ", ""); + if (!GameHelper.CheckNameValidly(fname)) + { + GameHelper.ShowTips("Please enter the correct account information3", true); + return; + } + + var lname = ui.com_lname.enter_fname_1.text.Replace(" ", ""); + if (!GameHelper.CheckNameValidly(lname) && !AppConst.isPt()) + { + GameHelper.ShowTips("Please enter the correct account information4", true); + return; + } + PreferencesMgr.Instance.ExchangeAccount = account; + PreferencesMgr.Instance.ExchangeName = $"{fname} {lname}"; + PreferencesMgr.Instance.short_name = fname; + PreferencesMgr.Instance.long_name = lname; + showPaypal(); + //uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupStepUI_Open, makeupTaskData); + //CtrlCloseUI(); + }); + + } + void showPaypal() + { + ui.type.selectedIndex = 2; + + if (makeupTaskData == null) + { + return; + } + + + ui.com_pay.text_name.text = PreferencesMgr.Instance.ExchangeName; + ui.com_pay.text_email.text = PreferencesMgr.Instance.ExchangeAccount; + + ui.com_pay.btn_change.SetClick(() => + { + PreferencesMgr.Instance.ExchangeName = null; + PreferencesMgr.Instance.ExchangeAccount = null; + OnEnter(); + + }); + GameHelper.SetSelfAvatar(ui.com_pay.load_avatar); + ui.btn_confirm.SetClick(() => + { + var info = new + { + email = PreferencesMgr.Instance.ExchangeAccount, + first_name = PreferencesMgr.Instance.short_name, + last_name = PreferencesMgr.Instance.long_name + }; + NetworkKit.PostWithHeader("shop/payOutUserInfo", info, (isSuccess, obj) => + { + if (isSuccess) + { + } + }); + NetworkKit.BuriedPoint(BuriedPointEvent.withdraw_behavior, BuriedPointEvent.withdraw_message, 1); + InitView(); + }); + } + public int now_selectindex; + void initTop() + { + // Debug.Log(JsonConvert.SerializeObject(PreferencesMgr.Instance.MakeupTaskHistory)); + + List btn_list = new List() { ui.btn_level0, ui.btn_level1, ui.btn_level2 }; + + List makeup_list = ConfigSystem.GetConfig().dataList; + now_selectindex = makeupTaskData.tableId - 1; + List saveingpot_history = SaveData.GetSaveobject().saveingpot_history; + + for (int i = 0; i < btn_list.Count; i++) + { + btn_list[i].text_cash.text = "$" + makeup_list[i].item_need; + Debug.Log(makeup_list[i].item_need); + btn_list[i].index.selectedIndex = i; + if (i >= saveingpot_history.Count) + { + btn_list[i].btn_state.selectedIndex = 2; + btn_list[i].text_type.grayed = true; + btn_list[i].text_cash.grayed = true; + } + else if (saveingpot_history.Count > i + 1 || ((saveingpot_history.Count == 3) && (saveingpot_history[2].status == SaveingPotTaskStatus.Inline))) + { + btn_list[i].btn_state.selectedIndex = 0; + } + else + { + btn_list[i].btn_state.selectedIndex = 1; + } + + + if (i == now_selectindex) + { + btn_list[i].img_outline.visible = true; + } + else if (i >= saveingpot_history.Count) + { + btn_list[i].img_outline.visible = false; + btn_list[i].SetClick(() => + { + GameHelper.ShowTips("To be unlocked"); + }); + } + else + { + btn_list[i].img_outline.visible = false; + int index = i; + btn_list[i].SetClick(() => + { + + for (int j = saveingpot_history.Count - 1; j >= 0; j--) + { + Debug.Log(saveingpot_history[j].tableId); + Debug.Log(index + 1); + Debug.Log(saveingpot_history[j].tableId == index + 1); + if (saveingpot_history[j].tableId == index + 1) + { + makeupTaskData = saveingpot_history[j]; + now_selectindex = index; + + break; + } + } + + InitView(); + }); + } + } + + } + private List config_name_list = ConfigSystem.GetConfig().config_name_list; + private List config_money_list = ConfigSystem.GetConfig().config_money_list; + private List broad_list = new List(); + private void BroadCast() + { + if (broadtime % 3 == 0) + { + ui.broad.t1.Play(() => + { + broad_list.RemoveAt(0); + int name_index = UnityEngine.Random.Range(0, config_name_list.Count); + int money_index = UnityEngine.Random.Range(0, config_money_list.Count); + broad_list.Add(new string[2] { config_name_list[name_index], config_money_list[money_index] }); + for (int i = 0; i < 4; i++) + { + text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]$" + broad_list[i][1] + "[/color]"; + } + }); + + + } + + } + private List text_list = new List(); + private void InitBroadCast() + { + text_list.Add(ui.broad.text_0); + text_list.Add(ui.broad.text_1); + text_list.Add(ui.broad.text_2); + text_list.Add(ui.broad.text_3); + for (int i = 0; i < 4; i++) + { + + int name_index = UnityEngine.Random.Range(0, config_name_list.Count); + int money_index = UnityEngine.Random.Range(0, config_money_list.Count); + broad_list.Add(new string[2] { config_name_list[name_index], config_money_list[money_index] }); + text_list[i].text = "congratulations,[color=#ad4800][size=36] " + broad_list[i][0] + " [/size][/color]Successful exchange[color=#ad4800]$" + broad_list[i][1] + "[/color]"; + + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs.meta new file mode 100644 index 0000000..38c4ffe --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f92e47328a7945b6a75b1bead2ad203 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs new file mode 100644 index 0000000..49e85db --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs @@ -0,0 +1,76 @@ +using System.Collections; +using System.Collections.Generic; + + +namespace ScrewsMaster + +{ + public class SaveingPotUICtrl : BaseUICtrl + { + private SaveingPotUI ui; + private SaveingPotModel model; + + private uint openUIMsg = UICtrlMsg.SaveingPotUI_Open; + private uint closeUIMsg = UICtrlMsg.SaveingPotUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.SaveingPotModel) as SaveingPotModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new SaveingPotUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs.meta new file mode 100644 index 0000000..aeb539f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SaveingPot/SaveingPotUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd17eb44157da4774b1a9293490c2550 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay.meta new file mode 100644 index 0000000..9424d0e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 74b14dc12a002f64b812f52d5eeca13c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs new file mode 100644 index 0000000..e817149 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs @@ -0,0 +1,42 @@ +namespace ScrewsMaster +{ + public class SheepPlayCtrl : BaseCtrl + { + public static SheepPlayCtrl Instance { get; private set; } + + private SheepPlayModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + //model = ModuleManager.Instance..GetModel(ModelConst.SheepPlayModel) as SheepPlayModel; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs.meta new file mode 100644 index 0000000..3e7a5d9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dccdf152f07be452bbd8727e8a8aa708 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs new file mode 100644 index 0000000..941c431 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs @@ -0,0 +1,46 @@ +namespace ScrewsMaster +{ + public class SheepPlayModel : BaseModel + { + #region 生命周期 + + public decimal showDollar; + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + // protected override void OnReset() + // { + // } + // #endregion + + // #region 读取数据 + // protected override void OnReadData() + // { + // } + // #endregion + + // #region 本地存储 + // protected override void WriteLocalStorage() + // { + + // } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs.meta new file mode 100644 index 0000000..f48eb8d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb3e7a6ac36b945dcb2b6b04634732d7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs new file mode 100644 index 0000000..32c795d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs @@ -0,0 +1,660 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI; +using FGUI.G003_play; +using Random = UnityEngine.Random; +using DG.Tweening; +using System.Linq; +using FGUI.A000_common; +using Spine.Unity; +using btn_noads = FGUI.A000_common.btn_noads; + +namespace ScrewsMaster +{ + public class SheepPlayUI : BaseUI + { + private SheepPlayUICtrl _ctrl; + private SheepPlayModel _model; + private sheep_play ui; + + private MakeupTaskData _makeupTaskData; + private Makeup _makeup; + + private btn_noads _btnNoAds; + + private Action closeCallback; + + private int _adCoolDown = 20; + private int _adNumbers = 0; + private int _adTimes = 0; + + public SheepPlayUI(SheepPlayUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.SheepPlayUI; + _ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G003_play"; + uiInfo.assetName = "sheep_play"; + uiInfo.layerType = UILayerType.Normal; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = false; + } + + private bool is_first_login_go_to_h5; + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + // HallManager.Instance.UpdateSecondEvent -= GameHelper.addGameTime; + HallManager.Instance.UpdateSecondEvent -= TimeEvent; + HallManager.Instance.UpdateSecondEvent -= UpData; + HallManager.Instance.UpdateEvent -= UpdateEvent; + closeCallback?.Invoke(); + } + + protected override void OnBind() + { + ui = baseUI as sheep_play; + } + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + { + ui.TopBox.y += Screen.safeArea.y; + } + + var showH5Btn = false; + if (GameHelper.IsGiftSwitch()) + { + showH5Btn = true; + } + else + { + showH5Btn = GameHelper.GetCommonModel().WVswitch != 0; + // if (showH5Btn) + // { + // ui.btn_h5.t0.Stop(); + // } + } + // ui.btn_h5.visible = showH5Btn; + + + ui.money.visible = ui.gold.red.visible = ui.btn_look_ad.visible = GameHelper.IsGiftSwitch(); + + ui.btn_menu.touchable = false; + SetAvatar(); + + // HallManager.Instance.UpdateSecondEvent += GameHelper.addGameTime; + HallManager.Instance.UpdateSecondEvent += TimeEvent; + HallManager.Instance.UpdateSecondEvent += UpData; + HallManager.Instance.UpdateEvent += UpdateEvent; + + + InitView(); + + if (GameHelper.getGameday() != DateTime.Now.Day) + { + PlayerPrefs.SetInt("_time", 0); + SaveData.GetSaveobject().time_task_record = new List(); + GameHelper.setGameday(); + } + } + + + protected override void OnOpen(object args) + { + + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + GameDispatcher.Instance.AddListener(GameMsg.BattleLevelUp, OnBattleLevelUp); + GameDispatcher.Instance.AddListener(GameMsg.Gold_refresh, SetTopCurr); + GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, SetMakeup); + GameDispatcher.Instance.AddListener(GameMsg.Ad_success, ad_success); + GameDispatcher.Instance.AddListener(GameMsg.GotoH5, GotoH5); + GameDispatcher.Instance.AddListener(GameMsg.FlyGold, OnChangeGold); + GameDispatcher.Instance.AddListener(GameMsg.RefreshLookAd, OnChangeLookAd); + GameDispatcher.Instance.AddListener(GameMsg.BuyPack, OnBuyPack); + GameDispatcher.Instance.AddListener(GameMsg.BuyRemoveAdPack, OnBuyPack); + GameDispatcher.Instance.AddListener(GameMsg.ThreeDaysGiftUIClose, checkThreeGift); + // MainThreadDispatcher.Instance.AddListener(MainThreadMsg.App_Focus_True, backGame); + + } + protected override void RemoveListener() + { + PreferencesDispatcher.Instance.RemoveListener(PreferencesMsg.playerAvatarId, OnChangeAvatar); + GameDispatcher.Instance.RemoveListener(GameMsg.Gold_refresh, SetTopCurr); + GameDispatcher.Instance.RemoveListener(GameMsg.RefreshMakeupData, SetMakeup); + GameDispatcher.Instance.RemoveListener(GameMsg.GotoH5, GotoH5); + GameDispatcher.Instance.RemoveListener(GameMsg.FlyGold, OnChangeGold); + GameDispatcher.Instance.RemoveListener(GameMsg.RefreshLookAd, OnChangeGold); + GameDispatcher.Instance.RemoveListener(GameMsg.BuyPack, OnBuyPack); + GameDispatcher.Instance.RemoveListener(GameMsg.BuyRemoveAdPack, OnBuyPack); + GameDispatcher.Instance.RemoveListener(GameMsg.ThreeDaysGiftUIClose, checkThreeGift); + } + + private void OnBuyPack(object args) + { + SetBtnAds(); + } + #endregion + //初始化页面逻辑 + private void InitView() + { + var reqData = new RespLoginFunnelData + { + type = "enterHall", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + + ui.fairyBatching = true; + int level = GameHelper.GetLevel(); + ui.level_text.text = "Level " + level; + + _adCoolDown = ConfigSystem.GetConfig().lobbyrewrdtime * 60; + _adTimes = PlayerPrefs.GetInt("ad_time", 0); + _adNumbers = PlayerPrefs.GetInt("ad_number", 1); + _btnNoAds = ui.btn_noads as btn_noads; + + ui.broadcast.visible = false; + SetTopCurr(); + SetMakeup(); + SetBtnTask(); + + if (SaveData.GetSaveobject().is_autopack_show_day != DateTime.Now.Day) + { + SaveData.GetSaveobject().is_autopack_show = false; + } + + + if (SaveData.GetSaveobject().start_time == 0) SaveData.GetSaveobject().start_time = GameHelper.GetNowTime(); + SetBtnAds(); + + if ((SaveData.GetSaveobject().battle_pass_time + ConfigSystem.GetConfig().dataList[0].Passportrewards_CD * 24 * 3600) < GameHelper.GetNowTime()) + { + SaveData.GetSaveobject().battle_pass_time = (int)GameHelper.GetNowTime(); + GameHelper.ResetGameExp(); + SaveData.GetSaveobject().battle_pass_freelist.Clear(); + SaveData.GetSaveobject().battle_pass_paylist.Clear(); + SaveData.GetSaveobject().is_get_battlepass = false; + } + + InitLookAdBtn(); + InitButtons(); + ui.btn_failpack.SetClick(() => + { + // float complte_progress = showResurgence(); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ResurgenceUI_Open, 0.5f); + }); + checkThreeGift(); + ui.btn_three_day.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ThreeDaysGiftUI_Open); + }); + } + void UpdateEvent() + { + long t = SaveData.GetSaveobject().failed_pack_time; + if (SaveData.GetSaveobject().failed_pack_time > GameHelper.GetNowTime()) + { + ui.btn_failpack.visible = true; + long time_ = t * 1000 - GameHelper.getNowTimeByMillisecond(); + DateTime oldDate = new DateTime(1970, 1, 1); + oldDate = oldDate.AddMilliseconds(time_); + ui.btn_failpack.GetChild("lab_time").text = DateTimeManager.Instance.DateTimeToFFFString(oldDate); + } + else + { + ui.btn_failpack.visible = false; + } + + + } + private void checkThreeGift(object obj = null) + { + if (SaveData.GetSaveobject().is_get_ThreeDaysGift) + { + var isToday = GameHelper.InToday(SaveData.GetSaveobject().last_got_three_gift_time, 0, true); + int three_gift_got_index = SaveData.GetSaveobject().three_gift_got_index; + if (three_gift_got_index > (int)rewardState.day3) + { + ui.btn_three_day.visible = false; + } + else if (!isToday) + { + ui.btn_three_day.GetChild("red").visible = true; + } + else + { + ui.btn_three_day.GetChild("red").visible = false; + } + } + } + private void InitButtons() + { + ui.btn_menu.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.ProfileUI_Open); + GameHelper.showGameUI = false; + }); + ui.btn_setting.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.MenuUI_Open); + GameHelper.showGameUI = false; + }); + + ui.money.btn_cashout.SetClickDownEffect(0.8f, 1); + ui.money.btn_cashout.SetClick(OnClickMoneyBtn); + + ui.btn_task.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewTaskUI_Open); GameHelper.showGameUI = false; + }); + + ui.gold.btn_buygold.SetClick(() => + { + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); + GameHelper.showGameUI = false; + }); + + ui.Btn_SignIn.SetClick(() => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SignInUI_Open); + GameHelper.showGameUI = false; + }); + + // ui.btn_h5.SetClick(() => + // { + // GotoH5(); + // }); + + ui.btn_noads.SetClick(() => + { + if (!SaveData.GetSaveobject().is_get_packreward && !SaveData.GetSaveobject().is_get_removead) + { + if (_btnNoAds.img_ad.visible) + { + PackRewardData param = new PackRewardData(); + param.isAutoPop = false; + param.isNeedScroll = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open); + } + + } + else if (SaveData.GetSaveobject().is_get_packreward) + { + PackRewardData param = new PackRewardData(); + param.isAutoPop = false; + param.isNeedScroll = true; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open); + } + GameHelper.showGameUI = false; + }); + if (ConfigSystem.GetConfig().PiggyBankSwitch == 0 || !GameHelper.IsGiftSwitch()) + { + ui.btn_saveingpot.visible = false; + } + ui.btn_saveingpot.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.SaveingPotUI_Open); }); + (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash); + var ske_pot = FXManager.Instance.SetFx((ui.btn_saveingpot as btn_saveingpot).ani_parent, Fx_Type.fx_savepot_icon, ref closeCallback); + ske_pot.state.SetAnimation(0, "animation", true); + } + private void SetSaveingPotBtn(object a = null) + { + (ui.btn_saveingpot as btn_saveingpot).text_nowcash.text = SaveingPotHelper.getCashString(SaveData.GetSaveobject().saveingpot_cash); + + } + private void OnClickMoneyBtn() + { + if (_makeupTaskData == null || _makeup == null) + { + return; + } + GameHelper.showGameUI = false; + uiCtrlDispatcher.Dispatch(UICtrlMsg.MakeupConfirmUI_Open, _makeupTaskData); + } + + private void InitLookAdBtn() + { + var sk = FXManager.Instance.SetFx(ui.btn_look_ad.gp, Fx_Type.fx_main_ad, ref closeCallback); + sk.state.SetAnimation(0, "animation", true); + ui.btn_look_ad.SetClick(LookAd); + ui.btn_look_ad.visible = false; + } + + void LookAd() + { + + //PlayerPrefs .SetInt("adCoolDownTime",Convert.ToInt32( GameHelper.GetNowTime())); + if (_adNumbers >= 3 && (GameHelper.GetNowTime() <= PlayerPrefs.GetInt("ad_time") + _adCoolDown)) + { + return; + + } + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardboxUI_Open); + // GameHelper.showGameUI = false; + + GameHelper.ShowVideoAd("reward_lobby", isSuccess => + { + if (isSuccess) + { + float[] cash_array = GameHelper.GetRewardValue(2); + GameDispatcher.Instance.Dispatch(GameMsg.Ad_success, cash_array[0]); + } + }); + ui.btn_look_ad.visible = false; + } + + void GotoH5(object obj = null) + { + //CreatSheepCard.instance.SetCameraVisible(false); + + // CtrlDispatcher.Instance.Dispatch(CtrlMsg.Webview_StateChange, WebUIType.H5); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.H5UI_Open); + GameHelper.showGameUI = false; + + } + public void SetBtnAds() + { + if (!SaveData.GetSaveobject().is_get_removead && !SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Play(-1, 0, null); + } + else if (SaveData.GetSaveobject().is_get_removead && SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Stop(); + _btnNoAds.visible = false; + } + else if (SaveData.GetSaveobject().is_get_packreward) + { + _btnNoAds.t0.Stop(); + _btnNoAds.t1.Play(); + _btnNoAds.img_pack.visible = false; + _btnNoAds.img_ad.visible = true; + + } + else if (SaveData.GetSaveobject().is_get_removead) + { + _btnNoAds.t0.Stop(); + _btnNoAds.t1.Play(); + _btnNoAds.img_pack.visible = true; + _btnNoAds.img_ad.visible = false; + } + + } + + private void OnBattleLevelUp(object obj = null) + { + SetBtnTask(); + } + + void SetBtnTask() + { + ui.btn_task.number_text.text = "Lv." + GameHelper.GetBattleLv(); + if (GameHelper.GetBattleLv() >= ConfigSystem.GetConfig().dataList.Count) + { + ui.btn_task.progress.width = 135; + } + else + { + ui.btn_task.progress.width = + Mathf.Min((float)GameHelper.GetGameExp() / ConfigSystem.GetConfig().dataList[GameHelper.GetBattleLv()].Eliminating_quantity, 1) * 135; + } + + } + + void SetMakeup(object a = null) + { + ui.money.number_text.text = GameHelper.Get102Str(GameHelper.Get102()); + + DOVirtual.Float(0, (float)GameHelper.Get102(), 1, + value => { ui.money.number_text.text = GameHelper.Get102Str((decimal)value); }); + + if (GameHelper.IsGiftSwitch()) + { + if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0) + { + return; + } + + _makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + _makeup = ConfigSystem.GetConfig().GetData(_makeupTaskData.tableId); + } + } + + void SetTopCurr(object a = null) + { + ui.gold.number_text.text = GameHelper.GetGoldNumber().ToString(); + // ui.gold.state.selectedIndex = GameHelper.IsGiftSwitch() ? 1 : 0; + + } + + public void SetMoneyCurr(object a = null) + { + ui.money.number_text.text = GameHelper.Get102Str(GameHelper.Get102()); + } + + + void OnChangeGold(object args) + { + if (!GameHelper.IsGiftSwitch()) return; + + var probability = GameHelper.GetCommonModel().Smallrewardsrate; + var range = Random.Range(0, 101); + if (range > probability) return; + + reward_data temp = args as reward_data; + + var rewardValue = GameHelper.GetRewardValue(0); + var end = GameHelper.GetUICenterPosition(ui.money.GetChild("number_text")); + + if (temp != null) + { + temp.end = end; + temp.change = rewardValue[0]; + temp.type = 111; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + } + + GameHelper.AddMoney(rewardValue[0]); + DOVirtual.DelayedCall(1, () => + { + var startNum = (float)GameHelper.Get102() - rewardValue[0]; + + DOVirtual.Float(startNum, (float)GameHelper.Get102(), 1f, + value => { (ui.money.GetChild("number_text") as GTextField).text = GameHelper.Get102Str((decimal)value); }); + }); + } + + void OnChangeLookAd(object args = null) + { + if (GameHelper.IsGiftSwitch() && (Random.Range(0, 100) < ConfigSystem.GetConfig().roomrewardrate) && !ui.btn_look_ad.visible) + { + ui.btn_look_ad.visible = true; + _btnLookAdShowTime = 0; + + } + } + + private void OnChangeAvatar(ChangeValue obj) + { + SetAvatar(); + } + + + private void SetAvatar() + { + GameHelper.SetSelfAvatar((ui.btn_menu.GetChild("loader_avatar") as GComponent).GetChild("loader_avatar") as GLoader); + } + + void ad_success(object a = null) + { + var start = GameHelper.GetUICenterPosition(ui.btn_look_ad); + var end = GameHelper.GetUICenterPosition(ui.money.number_text); + + if (a != null) + { + float cash = (float)a; + reward_data temp = new reward_data() { start = start, end = end, change = cash, type = 111 }; + if (!GameHelper.IsGiftSwitch()) + { + temp.type = 101; + temp.end = GameHelper.GetUICenterPosition(ui.gold.number_text); + GameHelper.AddGoldNumber(3); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, GameHelper.GetGoldNumber(), 1, + value => { ui.gold.number_text.text = ((int)value).ToString(); }); + }); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.CoinWnd_newUI_Open, temp); + GameHelper.AddMoney(cash); + DOVirtual.DelayedCall(1, () => + { + DOVirtual.Float(0, (float)GameHelper.Get102(), 1, + value => { ui.money.number_text.text = GameHelper.Get102Str((decimal)value); }); + }); + } + } + + ui.btn_look_ad.visible = false; + + } + + private int _timeCount = 11; + private com_broadcast_text1 _textUI; + private int _btnLookAdShowTime = 0; + void TimeEvent() + { + + // _timeCount++; + // if (_timeCount > 10) + // { + // ui.broadcast.visible = false; + // } + // var exBrPoolModel = ConfigSystem.GetConfig(); + // var configNameList = exBrPoolModel.config_name_list; + // var configMoneyList = exBrPoolModel.config_money_list; + // var nameIndex = Random.Range(0, configNameList.Count); + // var moneyIndex = Random.Range(0, configMoneyList.Count); + + // if (_timeCount > 30) + // { + // _timeCount = 0; + // ui.broadcast.visible = true; + + // _textUI ??= ui.broadcast.GetChild("broad_cast_text") as com_broadcast_text1; + // if (_textUI != null) + // { + // _textUI.cast_text.text = String.Format(_textUI.show_text.text, + // configNameList[nameIndex], + // configMoneyList[moneyIndex], + // DateTimeManager.Instance.GetCurrDateTime()); + // _textUI.t0.Play(() => { ui.broadcast.visible = false; }); + // } + // } + if (!UIManager.Instance.IsExistUI(UIConst.GameHomeUI)) + { + GameHelper.addGameTime(); + GameHelper.SetGameTimes(); + //Debug.Log("zengjiashijian"); + makeupTaskData_saveing = SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1]; + if (makeupTaskData_saveing.status == SaveingPotTaskStatus.None) + { + if (PreferencesMgr.Instance.ExchangeAccount != null) + { + makeupTaskData_saveing.H5Time += 1; + } + } + + if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + if (taskData != null) + { + PreferencesMgr.Instance.MakeupTaskH5Time += 1; + } + } + } + + + if (!GameHelper.IsGiftSwitch()) return; + + + _btnLookAdShowTime++; + if (_btnLookAdShowTime > 15) ui.btn_look_ad.visible = false; + SetSaveingPotBtn(); + + + } + private SaveingPotClass makeupTaskData_saveing; + private List _paidcoinsList; + void UpData() + { + _paidcoinsList ??= ConfigSystem.GetConfig().dataList; + + int time = SaveData.GetSaveobject()._goldtime0; + if ( time + _paidcoinsList[0].receive_CD < GameHelper.GetNowTime()) + { + ui.gold.state.selectedIndex = 2; + ui.gold.red.visible = true; + } + else + { + ui.gold.state.selectedIndex = 1; + } + + + ui.btn_task.red.visible = SaveData.getRed(); + if (!GameHelper.IsGiftSwitch()) return; + if ((!SaveData.GetSaveobject().is_get_packreward || !SaveData.GetSaveobject().is_get_removead) && !SaveData.GetSaveobject().is_autopack_show + && GameHelper.showGameUI && (Time.time > (ConfigSystem.GetConfig().Activetimes * 60))) + { + + PackRewardData param = new PackRewardData(); + param.isAutoPop = true; + param.isNeedScroll = false; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PackrewardUI_Open, param); + SaveData.GetSaveobject().is_autopack_show = true; + SaveData.GetSaveobject().is_autopack_show_day = DateTime.Now.Day; + SaveData.saveDataFunc(); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs.meta new file mode 100644 index 0000000..7a545fc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 901f044832e634fd69e12ec14f995ac7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs new file mode 100644 index 0000000..cdf288b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs @@ -0,0 +1,307 @@ + + +using System.Collections.Generic; +using AppsFlyerSDK; +using UnityEngine; + +namespace ScrewsMaster +{ + public class SheepPlayUICtrl : BaseUICtrl + { + private SheepPlayUI ui; + private SheepPlayModel model; + + private uint openUIMsg = UICtrlMsg.SheepPlayUI_Open; + private uint closeUIMsg = UICtrlMsg.SheepPlayUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.SheepPlayModel) as SheepPlayModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new SheepPlayUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.AddListener(GameMsg.Update101, OnUpdateDollar); + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + AppDispatcher.Instance.AddListener(AppMsg.App_Focus_False, (a) => + { + SaveData.saveDataFunc(); + }); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.RemoveListener(GameMsg.Update101, OnUpdateDollar); + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + } + private bool CheckIsOpen(string name) + { + var isOpen = UIManager.Instance.IsExistUI(name); + + return isOpen; + } + void pay_success(object str) + { + string type = (string)str; + string purch_number = ""; + Debug.Log("jiantinggggggggggggggggggggggg"); + if (type.Contains("buy_gold")) + { + if (type.StartsWith("buy_gold")) + { + int startIndex = "buy_gold".Length; + string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 + int suffix_num = int.Parse(suffix); + purch_number = ConfigSystem.GetConfig().dataList[suffix_num].Payment_amount2.ToString(); + + if (!CheckIsOpen(UIConst.BuygoldUI)) + { + switch (suffix_num) + { + case 0: + SaveData.GetSaveobject()._goldtime0 = (int)GameHelper.GetNowTime(); + break; + case 1: + SaveData.GetSaveobject()._goldtime1 = (int)GameHelper.GetNowTime(); + break; + case 2: + SaveData.GetSaveobject()._goldtime2 = (int)GameHelper.GetNowTime(); + break; + case 3: + SaveData.GetSaveobject()._goldtime3 = (int)GameHelper.GetNowTime(); + break; + case 4: + SaveData.GetSaveobject()._goldtime4 = (int)GameHelper.GetNowTime(); + break; + case 5: + SaveData.GetSaveobject()._goldtime5 = (int)GameHelper.GetNowTime(); + break; + case 6: + SaveData.GetSaveobject()._goldtime6 = (int)GameHelper.GetNowTime(); + break; + default: + return; + } + + SaveData.saveDataFunc(); + + var list = ConfigSystem.GetConfig().dataList; + GameHelper.AddGoldNumber(list[suffix_num].Actual_coins); + } + } + + } + else if (type == MaxPayManager.remove_ad) + { + SaveData.GetSaveobject().is_get_removead = true; + SaveData.saveDataFunc(); + purch_number = ConfigSystem.GetConfig().dataList[1].Paid_price2.ToString(); + ui?.SetBtnAds(); + + if (!CheckIsOpen(UIConst.PackrewardUI)) + { + var list = ConfigSystem.GetConfig().dataList; + GameHelper.AddGoldNumber(list[1].coins_quantity); + + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyRemoveAdPack); + } + } + else if (type == MaxPayManager.pack_reward) + { + List list = ConfigSystem.GetConfig().dataList; + + // setBtnAds(); + purch_number = ConfigSystem.GetConfig().dataList[0].Paid_price2.ToString(); + ui?.SetBtnAds(); + + SaveData.GetSaveobject().is_get_packreward = true; + SaveData.saveDataFunc(); + if (!CheckIsOpen(UIConst.PackrewardUI)) + { + int gold_num = list[0].coins_quantity; + int back_num = list[0].props_quantity[1]; + int out_num = list[0].props_quantity[0]; + int refresh_num = list[0].props_quantity[2]; + GameHelper.AddGoldNumber(gold_num); + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.BuyPack); + } + } + else if (type == MaxPayManager.battle_pass) + { + + + purch_number = ConfigSystem.GetConfig().Passportgift2.ToString(); + + if (!CheckIsOpen(UIConst.NewTaskUI)) + { + SaveData.GetSaveobject().is_get_battlepass = true; + int gold = 0; + int out_ = 0; + int back_ = 0; + int refresh_ = 0; + var Passportrewards_list = ConfigSystem.GetConfig().dataList; + var _passLevel = GameHelper.GetBattleLv(); + for (int i = 0; i < Passportrewards_list.Count; i++) + { + if (_passLevel > i) + { + switch (Passportrewards_list[i].Paid_rewards_type) + { + case 0: + gold += Passportrewards_list[i].Paid_rewards_num; + break; + case 1: + out_ += Passportrewards_list[i].Paid_rewards_num; + break; + case 2: + back_ += Passportrewards_list[i].Paid_rewards_num; + break; + case 3: + refresh_ += Passportrewards_list[i].Paid_rewards_num; + break; + } + + SaveData.GetSaveobject().battle_pass_paylist.Add(i + 1); + } + else break; + } + + if (gold > 0) + { + + GameHelper.AddGoldNumber(gold); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + GameHelper.AddItemNumber(ItemEnum.AddHole, out_); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + SaveData.saveDataFunc(); + } + } + else if (type == MaxPayManager.fail_pack) + { + List list = ConfigSystem.GetConfig().dataList; + purch_number = ConfigSystem.GetConfig().dataList[2].Paid_price2.ToString(); + + if (!CheckIsOpen(UIConst.ResurgenceUI)) + { + + int back_num = list[2].props_quantity[1]; + int out_num = list[2].props_quantity[0]; + int refresh_num = list[2].props_quantity[2]; + // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity; + + GameHelper.AddGoldNumber(list[2].coins_quantity); + GameHelper.AddItemNumber(ItemEnum.AddHole, out_num); + GameHelper.AddItemNumber(ItemEnum.MergeBox, back_num); + GameHelper.AddItemNumber(ItemEnum.ClearHole, refresh_num); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameObject.Find("GameStage").GetComponent().ClearHoleBtnClick(); + } + + } + else if (type == MaxPayManager.three_days_gift) + { + SaveData.GetSaveobject().is_get_ThreeDaysGift = true; + SaveData.saveDataFunc(); + purch_number = ConfigSystem.GetConfig().dataList[0].Paid_price2.ToString(); + } + else if (type == MaxPayManager.buy_one) + { + SaveData.GetSaveobject().is_get_ThreeDaysGift = true; + SaveData.saveDataFunc(); + purch_number = GameHelper.GetCommonModel().addspace2.ToString(); + if (!CheckIsOpen(UIConst.PropUI)) + { + ShowScrews.Instance.OnSuccessPayBox1(0); + } + + } + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close); + + //付费收益上报AF,要排除广告兑换 + if (!GameHelper.IsAdModelOfPay() && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue)) + { + // Debug.Log("付费收益上报AF----------- " + revenue.ToString()); + adCallbackInfo.Clear(); + adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId()); + adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().uid.ToString()); + adCallbackInfo.Add("af_currency", "USD"); + adCallbackInfo.Add("af_revenue", revenue.ToString()); + AppsFlyer.sendEvent("af_purchase", adCallbackInfo); + + GameHelper.sendRevenueToServer("af_purchase", "af_revenue", (int)(revenue * 10000)); + } + + } + public static Dictionary adCallbackInfo = new Dictionary(); + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + + + void OnUpdateDollar(object obj) + { + if (obj != null) + { + ui.SetMoneyCurr(); + } + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs.meta new file mode 100644 index 0000000..6adabae --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SheepPlay/SheepPlayUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad90dca2f6a8344fe8ce6cfd224043d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView.meta new file mode 100644 index 0000000..b006d9d --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4abab5c222004e779e892b0a8196e28c +timeCreated: 1726108579 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs new file mode 100644 index 0000000..21ae745 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs @@ -0,0 +1,41 @@ +namespace ScrewsMaster +{ + public class SignInViewCtrl : BaseCtrl + { + public static SignInViewCtrl Instance { get; private set; } + + private SignInViewModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs.meta new file mode 100644 index 0000000..ccce28e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aecb9bbe72cf49240bf4693b31ec6c71 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs new file mode 100644 index 0000000..762014f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs @@ -0,0 +1,26 @@ +namespace ScrewsMaster +{ + public class SignInViewModel : BaseModel + { + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs.meta new file mode 100644 index 0000000..3af10dd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41b78bce70bb5bb4f9dfcf659ebc5d0c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs new file mode 100644 index 0000000..6c319c1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using DG.Tweening; +using FairyGUI; +using FGUI.G014_SignIn; +using Spine.Unity; +using UnityEngine; + +namespace ScrewsMaster +{ + public class SignInViewUI : BaseUI + { + private SignInViewUICtrl ctrl; + private SignInViewModel model; + private SignDailyRewardModel signModel; + + private com_sign_in ui; + + private List signBtnList = new List(); + + private GTextField _goldNumText; + + public SignInViewUI(SignInViewUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.SignInViewUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G014_SignIn"; + uiInfo.assetName = "com_sign_in"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnClose() + { + GameHelper.showGameUI = true; + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G014_SignIn.com_sign_in; + } + + protected override void OnOpenBefore(object args) + { + + if (Screen.safeArea.y != 0) + { + ui.gold.y += Screen.safeArea.y; + } + + _goldNumText = ui.gold.GetChild("number_text") as GTextField; + signBtnList.Add(ui.day1); + signBtnList.Add(ui.day2); + signBtnList.Add(ui.day3); + signBtnList.Add(ui.day4); + signBtnList.Add(ui.day5); + signBtnList.Add(ui.day6); + signBtnList.Add(ui.day7); + + signModel = ConfigSystem.GetConfig(); + + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + var signList = signModel.dataList; + + for (int i = 0; i < signList.Count; i++) + { + if (i < 7) + { + RefreshView(signBtnList[i], signList[i], i); + } + } + + + ui.close.SetClick(CtrlCloseUI); + _goldNumText.text = GameHelper.GetGoldNumber().ToString(); + } + + private void RefreshView(btn_sign btnSign, SignDailyReward reward, int index) + { + btnSign.TitleStyle_1.text = $"Day {index + 1}"; + btnSign.TitleStyle_2.text = $"Day {index + 1}"; + btnSign.reward_num.text = reward.quantity[0] + ""; + + // sk.SetActive(false); + + var signDays = PreferencesMgr.Instance.SignState.Count; + var isToday = true; + if (signDays > 0) + isToday = GameHelper.InToday(PreferencesMgr.Instance.SignState[signDays - 1], 0, true); + + if (index < signDays) + { + btnSign.State.selectedIndex = btn_sign.State_Received; + } + else if (index == signDays) + { + if (signDays > 0 && isToday) + { + btnSign.State.selectedIndex = btn_sign.State_Unreceived; + } + else + { + btnSign.State.selectedIndex = btn_sign.State_Current; + SkeletonAnimation sk = FXManager.Instance.SetFx(btnSign.GetChild("fx_parent") as GGraph, Fx_Type.fx_signin, ref closeCallback); + + sk.state.SetAnimation(0, index >= 6 ? "big" : "small", true); + btnSign.isCloseClickAnim = true; + + btnSign.SetClick(() => + { + var startPos = GameHelper.GetUICenterPosition(btnSign); + btnSign.State.selectedIndex = btn_sign.State_Received; + btnSign.onClick.Clear(); + btnSign.touchable = false; + sk.SetActive(false); + + GetSignInReward(reward, startPos, btnSign); + }); + } + } + else + { + btnSign.State.selectedIndex = btn_sign.State_Unreceived; + } + + btnSign.Style.selectedIndex = index >= 6 ? btn_sign.Style_2 : btn_sign.Style_1; + } + + private Action closeCallback; + + private void GetSignInReward(SignDailyReward vo, Vector2 startPos, GButton btnDay) + { + var curGoldNum = GameHelper.GetGoldNumber(); + var rewardModel = new RewardData(); + for (var i = 0; i < vo.item1.Length; i++) + { + var rewardData = new RewardSingleData(101, vo.quantity[i], RewardOrigin.SignIn) + { + startPosition = startPos, + endPosition = GameHelper.GetUICenterPosition(_goldNumText), + + }; + rewardModel.AddReward(rewardData); + } + + if (vo.is_com_reward) + // rewardModel.displayType = RewardDisplayType.RewardFly | RewardDisplayType.Dialog | + // RewardDisplayType.ValueChange; + rewardModel.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + else + rewardModel.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + + if (vo.is_double) rewardModel.condition = RewardCondition.None; + + rewardModel.AddCompleted(isSuccess => + { + if (isSuccess) + { + PreferencesMgr.Instance.SignState.Add(GameHelper.GetNowTime()); + PreferencesMgr.Instance.SaveSignState(); + + btnDay.onClick.Clear(); + AudioManager.Instance.PlayDynamicEffect(AudioConst.DailyBonusCollect); + + DOVirtual.Float(curGoldNum, GameHelper.GetGoldNumber(), 1f, + value => { _goldNumText.text = ((int)value).ToString(); });//金币变化动画 + + // 用来刷新todo界面的一些信息,如红点等 + // GameDispatcher.Instance.Dispatch(GameMsg.UpdateTodoView); + + + // CtrlCloseUI(); + } + else + { + GameHelper.ShowTips("Not time to check in yet"); + + } + }); + + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardModel); + // ui.visible = false; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs.meta new file mode 100644 index 0000000..4d89111 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2ece96875532004db61ef94dca62b2e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs new file mode 100644 index 0000000..28a1898 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs @@ -0,0 +1,85 @@ + +namespace ScrewsMaster +{ + public class SignInViewUICtrl : BaseUICtrl + { + private readonly uint closeUIMsg = UICtrlMsg.SignInUI_Close; + private SignInViewModel model; + + private readonly uint openUIMsg = UICtrlMsg.SignInUI_Open; + private SignInViewUI ui; + + private void OnSignInUI_Display(object obj) + { + if (obj != null) + { + var isShow = (bool)obj; + if (isShow) + ui?.Display(); + else + ui?.Hide(); + } + } + + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new SignInViewUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) ui.Close(); + ui = null; + } + + #endregion + + #region 消息 + + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + } + + protected override void RemoveServerListener() + { + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs.meta new file mode 100644 index 0000000..b59c2c5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/SignInView/SignInViewUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6dc9cf8d737eb74189bdda1f202d664 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift.meta new file mode 100644 index 0000000..708d8a1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bb683b86a350e4edb91204267dbdf6a5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs new file mode 100644 index 0000000..d474410 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; + + + namespace ScrewsMaster +{ + public class ThreeDaysGiftCtrl : BaseCtrl + { + public static ThreeDaysGiftCtrl Instance { get; private set; } + + private ThreeDaysGiftModel model; + + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs.meta new file mode 100644 index 0000000..71f2b9a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftCtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c26aef375ac148dc9b4bd8090279823 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs new file mode 100644 index 0000000..2642605 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs @@ -0,0 +1,13 @@ +namespace ScrewsMaster +{ + public class ThreeDaysGiftModel : BaseModel + { + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs.meta new file mode 100644 index 0000000..aac17a8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c2702ca6f5c254a3cbaffdc3c9a51550 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs new file mode 100644 index 0000000..a483398 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs @@ -0,0 +1,435 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FutureCore; +using FairyGUI; +using FGUI.threeDaysGift; +using Spine.Unity; +using DG.Tweening; +using FGUI.A000_common; +using System; + +namespace ScrewsMaster +{ + public class ThreeDaysGiftUI : BaseUI + { + private ThreeDaysGiftUICtrl ctrl; + private ThreeDaysGiftModel model; + private FGUI.threeDaysGift.com_three_days ui; + + public ThreeDaysGiftUI(ThreeDaysGiftUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.ThreeDaysGiftUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "threeDaysGift"; + uiInfo.assetName = "com_three_days"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + + } + + protected override void OnClose() + { + HallManager.Instance.UpdateSecondEvent -= InitView; + GameHelper.showGameUI = true; + GameDispatcher.Instance.Dispatch(GameMsg.pack_close); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.threeDaysGift.com_three_days; + } + private Action closeCallback; + protected override void OnOpenBefore(object args) + { + + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, BuriedPointEvent.three_days_gift_show, 1); + + list = ConfigSystem.GetConfig().dataList; + + ui.btn_close.SetClick(() => + { + GameDispatcher.Instance.Dispatch(GameMsg.ThreeDaysGiftUIClose); + CtrlCloseUI(); + }); + + ui.groups.visible = false; + + var ske_bg = FXManager.Instance.SetFx(ui.ani_bg, Fx_Type.fx_three_gift, ref closeCallback); + ske_bg.state.SetAnimation(0, "3_days", false); + ske_bg.state.Complete += (a) => + { + ske_bg.state.SetAnimation(0, "3_days_dj", false); + }; + + DOVirtual.DelayedCall(0.5f, () => + { + ui.groups.visible = true; + }); + + // var ske_btn = FXManager.Instance.SetFx(ui.ani_title, Fx_Type.fx_title_effect, ref closeCallback); + // ske_btn.state.SetAnimation(0, "animation", true); + + InitView(); + HallManager.Instance.UpdateSecondEvent += InitView; + // WebviewManager.Instance.SetDarkThough(false); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.AddListener(GameMsg.rewardMul_close, rewardMul_close); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + GameDispatcher.Instance.RemoveListener(GameMsg.rewardMul_close, rewardMul_close); + } + #endregion + void pay_success(object str) + { + string type = (string)str; + if (type == MaxPayManager.three_days_gift) + { + + // var start = Vector2.zero; + // if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day1) { + // start = GameHelper.GetUICenterPosition(ui.day1.item1.lab_num); + // } else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day2) { + // start = GameHelper.GetUICenterPosition(ui.day2.item1.lab_num); + // } else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day3) { + // start = GameHelper.GetUICenterPosition(ui.day3.item1.lab_num); + // } + // + // var rewardData = new RewardData(); + // var end = GameHelper.GetUICenterPosition(ui.node_end); + // + // var rewardSingleData = new RewardSingleData(101, list[1].coins_quantity, RewardOrigin.AdTask) + // { + // startPosition = start, + // endPosition = end + // }; + // + // rewardData.AddReward(rewardSingleData); + // rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + // rewardData.AddCompleted(success => + // { + // // if (success) + // // { + // // RefreshGold(awardNum); + // // } + // }); + // + // GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + // // PreferencesMgr.Instance.Currency101 -= list[1].coins_quantity; + // + // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.AdcomingUI_Close); + // SaveData.GetSaveobject().is_get_removead = true; + // InitView(); + SaveData.GetSaveobject().is_get_ThreeDaysGift = true; + SaveData.saveDataFunc(); + ui.pay_type.selectedIndex = 2; + } + // GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh); + + } + + void rewardMul_close(object str) + { + if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day1) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day1_success, 1); + } + else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day2) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day2_success, 1); + } + else if (SaveData.GetSaveobject().three_gift_got_index == (int)rewardState.day3) + { + NetworkKit.BuriedPoint(BuriedPointEvent.Three_days_gift_event, BuriedPointEvent.three_day3_success, 1); + } + + SaveData.GetSaveobject().three_gift_got_index++; + SaveData.GetSaveobject().last_got_three_gift_time = GameHelper.GetNowTime(); + + } + + private List list; + + + private void InitView() + { + // ui.text_have.text = "Owner ADs:" + SaveData.GetSaveobject().look_ad_numbers; + // ui.need_text.text = "need " + list[0].Paid_price + " ADs"; + + ui.text_have.text = $"You Have ADs:{GameHelper.GetAdWatchCount()}"; + ui.need_text.text = $"Need ADs:{list[0].Paid_price}"; + + ui.btn_buypack.GetChild("img_saveingpot").visible = false; + ui.btn_max_pack.GetChild("img_saveingpot").visible = false; + + initItem(0); + initItem(1); + initItem(2); + + btn_green btn_buypack = (ui.btn_buypack as btn_green); + GObject pack_title = ui.btn_buypack.GetChild("title"); + + if (SaveData.GetSaveobject().is_get_ThreeDaysGift) + { + ui.pay_type.selectedIndex = 2; + var isToday = GameHelper.InToday(SaveData.GetSaveobject().last_got_three_gift_time, 0, true); + int three_gift_got_index = SaveData.GetSaveobject().three_gift_got_index; + if (isToday || (three_gift_got_index > (int)rewardState.day3)) + { + ui.btn_get.grayed = true; + ui.btn_get.SetClick(() => + { + if (three_gift_got_index < (int)rewardState.day3) + { + GameHelper.ShowTips("Come back and pick it up tomorrow."); + } + }); + } + else + { + ui.btn_get.SetClick(() => + { + getReward(); + ui.btn_get.SetClick(() => { }); + }); + } + + } + else + { + + if (!GameHelper.IsAdModelOfPay()) + { + ui.pay_type.selectedIndex = 1; + decimal price_pack = (decimal)list[0].Paid_price2; + ui.btn_max_pack.title = "$ "+price_pack; + bool is_get = SaveData.GetSaveobject().is_get_ThreeDaysGift; + if (is_get) + { + ui.btn_max_pack.enabled = false; + ui.btn_max_pack.SetClick(() => { }); + } + else + { + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) + { + ui.btn_max_pack.GetChild("img_saveingpot").visible = true; + } + ui.btn_max_pack.SetClick(() => + { + ApplePayClass maxPayData = new ApplePayClass + { + amount = (int)Math.Round(price_pack * 100), + sku = MaxPayManager.three_days_gift, + currency = "USD" + }; + MaxPayManager.Instance.Buy(maxPayData); + }); + } + } + else + { + + + + ui.pay_type.selectedIndex = 0; + bool is_get = SaveData.GetSaveobject().is_get_ThreeDaysGift; + if (is_get) + { + btn_buypack.state.selectedIndex = 0; + btn_buypack.cooldown.selectedIndex = 1; + ui.btn_buypack.grayed = true; + pack_title.text = "Cliamed"; + ui.btn_buypack.SetClick(() => + { + + }); + } + else if (GameHelper.GetAdWatchCount() >= list[0].Paid_price) + { + btn_buypack.state.selectedIndex = 1; + btn_buypack.cooldown.selectedIndex = 0; + btn_buypack.SetClick(() => //购买成功 + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_AD_event, BuriedPointEvent.three_days_gift_buy_success, 1); + // SaveData.GetSaveobject().look_ad_numbers -= (int)list[0].Paid_price; + GameHelper.AddAdWatchCount(-(int)list[0].Paid_price); + + GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, MaxPayManager.three_days_gift); + + // getReward(); + ui.btn_buypack.SetClick(() => { }); + }); + } + else if (GameHelper.GetAdRewardCooldownTime() > GameHelper.GetNowTime()) + { + btn_buypack.state.selectedIndex = 0; + btn_buypack.cooldown.selectedIndex = 1; + pack_title.text = CommonHelper.TimeFormat((int)GameHelper.GetAdRewardCooldownTime() - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour); + btn_buypack.SetClick(() => { }); + } + else + { + btn_buypack.state.selectedIndex = 0; + btn_buypack.cooldown.selectedIndex = 0; + if (GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig().PiggyBankSwitch == 1) + { + ui.btn_buypack.GetChild("img_saveingpot").visible = true; + } + pack_title.text = "Watch AD"; + btn_buypack.SetClick(() => + { + OnClickBuyPackWatchAdsBtn(); + }); + } + } + } + + } + private void OnClickBuyPackWatchAdsBtn() + { + NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, + BuriedPointEvent.three_days_gift_click, 1); + + GameHelper.ShowVideoAd("buy_failpack", success => + { + if (success) + { + GameHelper.UpdateAdRewardExchangeTime(); + } + }); + } + private void initItem(int index) + { + com_item day = null; + if (index == 0) + { + day = ui.day1; + } + else if (index == 1) + { + day = ui.day2; + } + else if (index == 2) + { + day = ui.day3; + } + + if (SaveData.GetSaveobject().three_gift_got_index - 1 > index) + { + day.img_select.visible = true; + if (SaveData.GetSaveobject().three_gift_got_index - 1 > 2) + { + day.img_select2.visible = true; + } + } + + day.state.selectedIndex = list[index].props_quantity.Length; + + setItemUrl(day.item1.loader_, GiftType.coin); + day.item1.lab_num.text = "x" + list[index].coins_quantity; + + for (int i = 0; i < list[index].props_quantity.Length; i++) + { + item_reward item = (day.GetChild("item" + (i + 2)) as item_reward); + setItemUrl(item.loader_, (GiftType)list[index].props_type[i]); + + item.lab_num.text = "x" + list[index].props_quantity[i]; + } + } + + private void setItemUrl(GLoader loader, GiftType urltype) + { + if (urltype == GiftType.coin) loader.url = "ui://threeDaysGift/3DAYS_prs_001"; + else if (urltype == GiftType.move_out) loader.url = "ui://threeDaysGift/3DAYS_prs_002"; + else if (urltype == GiftType.refresh) loader.url = "ui://threeDaysGift/3DAYS_prs_003"; + else if (urltype == GiftType.undo) loader.url = "ui://threeDaysGift/3DAYS_prs_004"; + } + + private void getReward() + { + int index = SaveData.GetSaveobject().three_gift_got_index; + + com_item item = null; + if (index == (int)rewardState.day1) + { + item = ui.day1; + } + else if (index == (int)rewardState.day2) + { + item = ui.day2; + } + else if (index == (int)rewardState.day3) + { + item = ui.day3; + } + item.img_select.visible = true; + + + List types = new List(); + List rewards = new List(); + types.Add((int)GiftType.coin); + rewards.Add(list[index - 1].coins_quantity); + for (int i = 0; i < list[index - 1].props_quantity.Length; i++) + { + types.Add(list[index - 1].props_type[i]); // GiftType 类型 + rewards.Add(list[index - 1].props_quantity[i]); + } + GiftData data = new GiftData(); + data.type = types; + data.reward = rewards; + uiCtrlDispatcher.Dispatch(UICtrlMsg.RewardMulNewUI_Open, data); + } + } +} +enum rewardState +{ + day1 = 1, + day2, + day3 +} +public class GiftData +{ + public List type; + public List reward; + public string uiName; +} + +public enum GiftType : int +{ + coin = 101, + move_out = 0, + undo = 1, + refresh = 2, +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs.meta new file mode 100644 index 0000000..7c5660f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 34e42e54a15e74f5fa6f4738876e5946 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs new file mode 100644 index 0000000..c349ddf --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs @@ -0,0 +1,76 @@ +using System.Collections; +using System.Collections.Generic; + + +namespace ScrewsMaster + +{ + public class ThreeDaysGiftUICtrl : BaseUICtrl + { + private ThreeDaysGiftUI ui; + private ThreeDaysGiftModel model; + + private uint openUIMsg = UICtrlMsg.ThreeDaysGiftUI_Open; + private uint closeUIMsg = UICtrlMsg.ThreeDaysGiftUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.ThreeDaysGiftModel) as ThreeDaysGiftModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new ThreeDaysGiftUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs.meta new file mode 100644 index 0000000..7a3cde0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/ThreeDaysGift/ThreeDaysGiftUICtrl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a66b1a98eeb44e23940d70809964ad8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips.meta new file mode 100644 index 0000000..51f0922 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f0a7659f93c64c70aa1de1b32d872fea +timeCreated: 1727432236 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs new file mode 100644 index 0000000..05f9b37 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs @@ -0,0 +1,24 @@ + + +namespace ScrewsMaster +{ + public class TipsCtrl : BaseCtrl + { + public static TipsCtrl Instance { get; private set; } + + private TipsModel model; + + #region 生命周期 + protected override void OnInit() + { + Instance = this; + } + + protected override void OnDispose() + { + Instance = null; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs.meta new file mode 100644 index 0000000..8d7c534 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6401fa3127124bc1a1b09c999fdd348d +timeCreated: 1727432236 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs new file mode 100644 index 0000000..0769cd0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs @@ -0,0 +1,20 @@ + + +namespace ScrewsMaster +{ + public class TipsModel : BaseModel + { + #region 生命周期 + + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs.meta new file mode 100644 index 0000000..f4f4b7f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: db5e6fdb10824beda4bad651244857f2 +timeCreated: 1727432236 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs new file mode 100644 index 0000000..8c42bdb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs @@ -0,0 +1,94 @@ + +using FGUI.A000_common; +using UnityEngine; +using FairyGUI; +using Roy.Datas; +using SGame; + +namespace ScrewsMaster +{ + public class TipsUI : BaseUI + { + private TipsUICtrl ctrl; + private PropModel model; + private FGUI.G003_play.Com_LoginFailurePopup ui; + private int type; + private int num; + + private PropViewData _data; + + public TipsUI(TipsUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.PropUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "G003_play"; + uiInfo.assetName = "Com_LoginFailurePopup"; + uiInfo.layerType = UILayerType.NetworkError; + uiInfo.isNeedOpenAnim = true; + uiInfo.isNeedCloseAnim = true; + uiInfo.isNeedUIMask = false; + } + + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnClose() + { + } + + protected override void OnBind() + { + ui = baseUI as FGUI.G003_play.Com_LoginFailurePopup; + } + + protected override void OnOpenBefore(object args) + { + + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + + } + protected override void RemoveListener() + { + + } + #endregion + + //初始化页面逻辑 + private void InitView() + { + ui.btn_close.visible = false; + ui.btn_Login.onClick.Add(() => + { + NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login); + ctrl.CloseUI(); + }); + ui.btn_close.onClick.Add(() => { + this.ctrl.CloseUI(); + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs.meta new file mode 100644 index 0000000..d95aefc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUI.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8dd4a8c0542a4477add409b9ab06e0b0 +timeCreated: 1727432236 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs new file mode 100644 index 0000000..1e7d9ed --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs @@ -0,0 +1,72 @@ + + +namespace ScrewsMaster +{ + public class TipsUICtrl : BaseUICtrl + { + private TipsUI ui; + private TipsModel model; + + private uint openUIMsg = UICtrlMsg.TipsUI_Open; + private uint closeUIMsg = UICtrlMsg.TipsUI_Close; + + #region 生命周期 + protected override void OnInit() + { + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new TipsUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + #endregion + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs.meta new file mode 100644 index 0000000..7f24ad9 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ModuleUI/Tips/TipsUICtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: de49ae9fb07346bf871fc2fe460602b3 +timeCreated: 1727432236 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr.meta b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr.meta new file mode 100644 index 0000000..5bf9062 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6191a2197adfc2048b4b66bdc348f28e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs new file mode 100644 index 0000000..26fa766 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class PreferencesDataReadyCtrl : BaseCtrl + { + LoginModel userModel; + private List msgList = new List(); + + #region 生命周期 + + protected override void OnInit() + { + userModel = ModuleManager.Instance.GetModel(ModelConst.LoginModel) as LoginModel; + } + + protected override void OnDispose() + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + ctrlDispatcher.AddListener(CtrlMsg.Preferences_InitComplete, PreferenceDataReady); + ctrlDispatcher.AddListener(CtrlMsg.Game_StartBefore, SendCtrlMsg); + } + + protected override void RemoveListener() + { + ctrlDispatcher.RemoveListener(CtrlMsg.Preferences_InitComplete, PreferenceDataReady); + ctrlDispatcher.RemoveListener(CtrlMsg.Game_StartBefore, SendCtrlMsg); + } + + #endregion + + + public void PreferenceDataReady(object objs = null) + { + InspectionNewDay(); + + + PreferencesMgr.Instance.GameStartCount++; + } + + + public void InspectionNewDay() + { + long login_time = userModel.login_time; + DateTime data = DateTimeManager.Instance.GetDateTime(login_time); + string dateStr = DateTimeManager.Instance.DateTimeToYYYYMMDD(data); + if (!PreferencesMgr.Instance.Date.Equals(dateStr)) + { + PreferencesMgr.Instance.Date = dateStr; + msgList.Add(CtrlMsg.NewDays); + PreferencesMgr.Instance.LoginGameTodayTimes = 1; + } + else + { + PreferencesMgr.Instance.LoginGameTodayTimes++; + } + } + + + public void SendCtrlMsg(object args = null) + { + for (int i = 0; i < msgList.Count; i++) + { + ctrlDispatcher.Dispatch(msgList[i]); + } + + msgList.Clear(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs.meta b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs.meta new file mode 100644 index 0000000..82a0598 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesDataReadyCtrl.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b456e1e40be344dd99c817ba250c2a0e +timeCreated: 1692007381 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs new file mode 100644 index 0000000..a91b65e --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs @@ -0,0 +1,226 @@ +namespace ScrewsMaster +{ + public static class PreferencesField + { + public const string currency102 = "currency101"; + + + public const string maxCurrency102 = "maxCurrency101"; + + + public const string nextNewDayTime = "nextNewDayTime"; + public const string nextOpenWheelStampTime = "nextOpenWheelStampTime"; + public const string thisDayWatchSlyderVideoNum = "thisDayWatchSlyderVideoNum"; + + + public const string playerName = "playerName"; + + + public const string playerAvatarId = "playerAvatarId"; + + + public const string signState = "signState"; + + + public const string completeGuideList = "completeGuideList"; + + public const string isResetGuide = "isResetGuide"; + + + public const string gameOfCount = "gameOfCount"; + + + public const string winOfGame = "winOfGame"; + + + public const string onceStatistcList = "onceStatistcList"; + + + public const string watchVideoBeginSum = "watchVideoBeginSum"; + + + public const string isGod = "isGod"; + + + public const string facebookId = "facebookId"; + + + public const string facebookName = "facebookName"; + + + public const string facebookAvatarUrl = "facebookAvatarUrl"; + + + public const string updataFBLogin_Data = "updataFBLogin_Data"; + + + public const string isFaceBookLogin = "isFaceBookLogin"; + + + public const string isGuideFinish = "isGuideFinish"; + + + public const string currentQuestionIndex = "currentQuestionIndex"; + + public const string GameLevel = "GameLevel"; + public const string BattleExp = "BattleExp"; + public const string PrizeWheelCount = "PrizeWheelCount"; + public const string PrizeWheelTime = "PrizeWheelTime"; + public const string TotalCoins = "TotalCoins"; + public const string PayBox1 = "PayBox1"; + public const string PayBox2 = "PayBox2"; + public const string Items = "Items"; + public const string AdWatchCount = "AdWatchCount"; + + + public const string exchangeBindGuide = "exchangeBindGuide"; + + + public const string exchangeAccount = "exchangeAccount"; + + + public const string exchangeName = "exchangeName"; + + + public const string haveRedeemedSkin = "haveRedeemedSkin"; + + + public const string inUseSkin = "inUseSkin"; + + + public const string paypalAccount = "paypalAccount"; + + + public const string isSuccessRedeem = "isSuccessRedeem"; + + public const string inviteDataList = "inviteDataList"; + + + public const string inviteRecordList = "inviteRecordList"; + + + public const string inviteMakeUpHistoryList = "inviteMakeUpHistoryList"; + + public const string isEditInviteCode = "isEditInviteCode"; + + + public const string webViewMakeUpOnlineTime = "webViewMakeUpOnlineTime"; + + public const string webViewADTaskOnlineTime = "webViewADTaskOnlineTime"; + + + public const string isShowRewardFly101 = "isShowRewardFly101"; + public const string isShowRewardFly102 = "isShowRewardFly102"; + + + public const string playReawrd111 = "playReawrd111"; + + + public const string isShowRewardFly111 = "isShowRewardFly111"; + + + public const string openRewardCount = "openRewardCount"; + + + public const string interRewardShowLevel = "interRewardShowLevel"; + + + public const string isShowOpenReward = "isShowOpenReward"; + + public const string isRealProcessing = "isRealProcessing"; + + + public const string realWatchVideo = "realWatchVideo"; + + + public const string isClickH5Icon = "isClickH5Icon"; + + + public const string lastClickMainIconTime = "lastClickMainIconTime"; + + public const string interH5Url1Count = "interH5Url1Count"; + public const string interH5Url2Count = "interH5Url2Count"; + public const string makeupSatisfyGears = "makeupSatisfyGears"; + public const string makeupRealReportGear = "makeupRealReportGear"; + + + public const string isLastH5Tab = "isLastH5Tab"; + + + public const string adCashFlyShowTime = "adCashFlyShowTime"; + + + public const string adTaskDataList = "adTaskDataList"; + + + public const string adTaskCount = "adTaskCount"; + + + public const string correctAnswerCount = "correctAnswerCount"; + + + public const string achievementAnswerList = "achievementAnswerList"; + + + public const string h5StayTime = "h5StayTime"; + + + public const string achievementH5List = "achievementH5List"; + + + public const string videoWatchCount = "videoWatchCount"; + + + public const string achievementVideoList = "achievementVideoList"; + + + public const string signInCount = "signInCount"; + + + public const string achievementSignInList = "achievementSignInList"; + + + public const string inviteCount = "inviteCount"; + + + public const string achievementInviteList = "achievementInviteList"; + + + public const string naiveStepFinish = "naiveStepFinish"; + + + public const string makeupTaskHistory = "makeupTaskHistory"; + + + public const string makeupTaskH5Time = "makeupTaskH5Time"; + + + public const string makeupConditionMark = "makeupConditionMark"; + + public const string statisticDictionary = "statisticDictionary"; + + + public const string gameStartCount = "gameStartCount"; + + + public const string loginGameTodayTimes = "loginGameTodayTimes"; + + + public const string videoEffective_count = "videoEffective_count"; + + + public const string isLogEffective = "isLogEffective"; + + + public const string data_ver = "data_ver"; + + + public const string haveBeenGameStart = "haveBeenGameStart"; + + + public const string date = "date"; + + + public const string lastLoginDays = "lastLoginDays"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs.meta b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs.meta new file mode 100644 index 0000000..33adfc1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesField_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc5eccf1420ec3a489eb815e618824c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs new file mode 100644 index 0000000..b69e5e5 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs @@ -0,0 +1,1745 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace ScrewsMaster +{ + public partial class PreferencesMgr + { + private void OnInitPreferences() + { + currency102 = preferences.currency102; + maxCurrency102 = preferences.maxCurrency102; + nextNewDayTime = preferences.nextNewDayTime; + playerName = preferences.playerName; + playerAvatarId = preferences.playerAvatarId; + isResetGuide = preferences.isResetGuide; + gameOfCount = preferences.gameOfCount; + winOfGame = preferences.winOfGame; + watchVideoBeginSum = preferences.watchVideoBeginSum; + isGod = preferences.isGod; + facebookId = preferences.facebookId; + facebookName = preferences.facebookName; + facebookAvatarUrl = preferences.facebookAvatarUrl; + isFaceBookLogin = preferences.isFaceBookLogin; + isGuideFinish = preferences.isGuideFinish; + currentQuestionIndex = preferences.currentQuestionIndex; + _gameLevel = preferences.GameLevel; + _battleExp = preferences.BattleExp; + totalCoins = preferences.TotalCoins; + adWatchCount = preferences.AdWatchCount; + _prizeWheelCount = preferences.PrizeWheelCount; + _prizeWheelTime = preferences.PrizeWheelTime; + _payBox1 = preferences.PayBox1; + _payBox2 = preferences.PayBox2; + _items = preferences.Items; + exchangeBindGuide = preferences.exchangeBindGuide; + exchangeAccount = preferences.exchangeAccount; + exchangeName = preferences.exchangeName; + inUseSkin = preferences.inUseSkin; + paypalAccount = preferences.paypalAccount; + isSuccessRedeem = preferences.isSuccessRedeem; + isEditInviteCode = preferences.isEditInviteCode; + webViewMakeUpOnlineTime = preferences.webViewMakeUpOnlineTime; + webViewADTaskOnlineTime = preferences.webViewADTaskOnlineTime; + isShowRewardFly101 = preferences.isShowRewardFly101; + isShowRewardFly102 = preferences.isShowRewardFly102; + playReawrd111 = preferences.playReawrd111; + isShowRewardFly111 = preferences.isShowRewardFly111; + openRewardCount = preferences.openRewardCount; + interRewardShowLevel = preferences.interRewardShowLevel; + isShowOpenReward = preferences.isShowOpenReward; + isRealProcessing = preferences.isRealProcessing; + realWatchVideo = preferences.realWatchVideo; + isClickH5Icon = preferences.isClickH5Icon; + lastClickMainIconTime = preferences.lastClickMainIconTime; + interH5Url1Count = preferences.interH5Url1Count; + interH5Url2Count = preferences.interH5Url2Count; + makeupRealReportGear = preferences.makeupRealReportGear; + isLastH5Tab = preferences.isLastH5Tab; + adCashFlyShowTime = preferences.adCashFlyShowTime; + adTaskCount = preferences.adTaskCount; + correctAnswerCount = preferences.correctAnswerCount; + h5StayTime = preferences.h5StayTime; + videoWatchCount = preferences.videoWatchCount; + signInCount = preferences.signInCount; + inviteCount = preferences.inviteCount; + naiveStepFinish = preferences.naiveStepFinish; + makeupTaskH5Time = preferences.makeupTaskH5Time; + makeupConditionMark = preferences.makeupConditionMark; + gameStartCount = preferences.gameStartCount; + loginGameTodayTimes = preferences.loginGameTodayTimes; + videoEffective_count = preferences.videoEffective_count; + isLogEffective = preferences.isLogEffective; + data_ver = preferences.data_ver; + haveBeenGameStart = preferences.haveBeenGameStart; + date = preferences.date; + lastLoginDays = preferences.lastLoginDays; + thisDayWatchSlyderVideoNum = preferences.thisDayWatchSlyderVideoNum; + nextOpenWheelStampTime = preferences.nextOpenWheelStampTime; + } + + #region ValueType + + private decimal currency102; + + + public decimal Currency102 + { + get { return (decimal)Mathf.Max((float)currency102, 0); } + set + { + if (currency102 == value) return; + + value = (decimal)Mathf.Max((float)value, 0); + + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = currency102; + changeValue.newValue = value; + + currency102 = value; + preferences.currency102 = currency102; + AddToAutoDelaySaveList(PreferencesField.currency102, preferences.currency102); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.currency102, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.currency102); + } + } + + private decimal maxCurrency102; + + + public decimal MaxCurrency102 + { + get { return maxCurrency102; } + set + { + if (maxCurrency102 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = maxCurrency102; + changeValue.newValue = value; + + maxCurrency102 = value; + preferences.maxCurrency102 = maxCurrency102; + AddToAutoDelaySaveList(PreferencesField.maxCurrency102, preferences.maxCurrency102); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.maxCurrency102, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.maxCurrency102); + } + } + + private long nextNewDayTime; + + + public long NextNewDayTime + { + get { return nextNewDayTime; } + set + { + if (nextNewDayTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = nextNewDayTime; + changeValue.newValue = value; + + nextNewDayTime = value; + preferences.nextNewDayTime = nextNewDayTime; + AddToAutoDelaySaveList(PreferencesField.nextNewDayTime, preferences.nextNewDayTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.nextNewDayTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.nextNewDayTime); + } + } + + private string playerName; + + + public string PlayerName + { + get { return playerName; } + set + { + if (playerName == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = playerName; + changeValue.newValue = value; + + playerName = value; + preferences.playerName = playerName; + AddToAutoDelaySaveList(PreferencesField.playerName, preferences.playerName); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.playerName, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.playerName); + } + } + + private int playerAvatarId; + + + public int PlayerAvatarId + { + get { return playerAvatarId; } + set + { + if (playerAvatarId == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = playerAvatarId; + changeValue.newValue = value; + + playerAvatarId = value; + preferences.playerAvatarId = playerAvatarId; + AddToAutoDelaySaveList(PreferencesField.playerAvatarId, preferences.playerAvatarId); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.playerAvatarId, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.playerAvatarId); + } + } + + private bool isResetGuide; + + public bool IsResetGuide + { + get { return isResetGuide; } + set + { + if (isResetGuide == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isResetGuide; + changeValue.newValue = value; + + isResetGuide = value; + preferences.isResetGuide = isResetGuide; + AddToAutoDelaySaveList(PreferencesField.isResetGuide, preferences.isResetGuide); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isResetGuide, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isResetGuide); + } + } + + private int gameOfCount; + + + public int GameOfCount + { + get { return gameOfCount; } + set + { + if (gameOfCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = gameOfCount; + changeValue.newValue = value; + + gameOfCount = value; + preferences.gameOfCount = gameOfCount; + AddToAutoDelaySaveList(PreferencesField.gameOfCount, preferences.gameOfCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.gameOfCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.gameOfCount); + } + } + + private int winOfGame; + + + public int WinOfGame + { + get { return winOfGame; } + set + { + if (winOfGame == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = winOfGame; + changeValue.newValue = value; + + winOfGame = value; + preferences.winOfGame = winOfGame; + AddToAutoDelaySaveList(PreferencesField.winOfGame, preferences.winOfGame); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.winOfGame, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.winOfGame); + } + } + + private int watchVideoBeginSum; + + + public int WatchVideoBeginSum + { + get { return watchVideoBeginSum; } + set + { + if (watchVideoBeginSum == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = watchVideoBeginSum; + changeValue.newValue = value; + + watchVideoBeginSum = value; + preferences.watchVideoBeginSum = watchVideoBeginSum; + AddToAutoDelaySaveList(PreferencesField.watchVideoBeginSum, preferences.watchVideoBeginSum); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.watchVideoBeginSum, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.watchVideoBeginSum); + } + } + + private bool isGod; + + + public bool IsGod + { + get { return isGod; } + set + { + if (isGod == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isGod; + changeValue.newValue = value; + + isGod = value; + preferences.isGod = isGod; + AddToAutoDelaySaveList(PreferencesField.isGod, preferences.isGod); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isGod, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isGod); + } + } + + private string facebookId; + + + public string FacebookId + { + get { return facebookId; } + set + { + if (facebookId == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = facebookId; + changeValue.newValue = value; + + facebookId = value; + preferences.facebookId = facebookId; + AddToAutoDelaySaveList(PreferencesField.facebookId, preferences.facebookId); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.facebookId, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.facebookId); + } + } + + private string facebookName; + + + public string FacebookName + { + get { return facebookName; } + set + { + if (facebookName == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = facebookName; + changeValue.newValue = value; + + facebookName = value; + preferences.facebookName = facebookName; + AddToAutoDelaySaveList(PreferencesField.facebookName, preferences.facebookName); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.facebookName, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.facebookName); + } + } + + private string facebookAvatarUrl; + + + public string FacebookAvatarUrl + { + get { return facebookAvatarUrl; } + set + { + if (facebookAvatarUrl == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = facebookAvatarUrl; + changeValue.newValue = value; + + facebookAvatarUrl = value; + preferences.facebookAvatarUrl = facebookAvatarUrl; + AddToAutoDelaySaveList(PreferencesField.facebookAvatarUrl, preferences.facebookAvatarUrl); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.facebookAvatarUrl, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.facebookAvatarUrl); + } + } + + private bool isFaceBookLogin; + + + public bool IsFaceBookLogin + { + get { return isFaceBookLogin; } + set + { + if (isFaceBookLogin == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isFaceBookLogin; + changeValue.newValue = value; + + isFaceBookLogin = value; + preferences.isFaceBookLogin = isFaceBookLogin; + AddToAutoDelaySaveList(PreferencesField.isFaceBookLogin, preferences.isFaceBookLogin); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isFaceBookLogin, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isFaceBookLogin); + } + } + + private bool isGuideFinish; + + + public bool IsGuideFinish + { + get { return isGuideFinish; } + set + { + if (isGuideFinish == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isGuideFinish; + changeValue.newValue = value; + + isGuideFinish = value; + preferences.isGuideFinish = isGuideFinish; + AddToAutoDelaySaveList(PreferencesField.isGuideFinish, preferences.isGuideFinish); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isGuideFinish, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isGuideFinish); + } + } + + private int currentQuestionIndex; + + + public int CurrentQuestionIndex + { + get { return currentQuestionIndex; } + set + { + if (currentQuestionIndex == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = currentQuestionIndex; + changeValue.newValue = value; + + currentQuestionIndex = value; + preferences.currentQuestionIndex = currentQuestionIndex; + AddToAutoDelaySaveList(PreferencesField.currentQuestionIndex, preferences.currentQuestionIndex); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.currentQuestionIndex, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.currentQuestionIndex); + } + } + + private int _gameLevel; + + public int GameLevel + { + get { return _gameLevel; } + set + { + if (_gameLevel == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _gameLevel; + changeValue.newValue = value; + + _gameLevel = value; + preferences.GameLevel = _gameLevel; + AddToAutoDelaySaveList(PreferencesField.GameLevel, preferences.GameLevel); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.GameLevel, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.GameLevel); + } + } + + private int _battleExp; + + public int BattleExp + { + get { return _battleExp; } + set + { + if (_battleExp == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _battleExp; + changeValue.newValue = value; + + _battleExp = value; + preferences.BattleExp = _battleExp; + AddToAutoDelaySaveList(PreferencesField.BattleExp, preferences.BattleExp); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.BattleExp, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.BattleExp); + } + } + + private int _prizeWheelCount; + + public int PrizeWheelCount + { + get { return _prizeWheelCount; } + set + { + if (_prizeWheelCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _prizeWheelCount; + changeValue.newValue = value; + + _prizeWheelCount = value; + preferences.PrizeWheelCount = _prizeWheelCount; + AddToAutoDelaySaveList(PreferencesField.PrizeWheelCount, preferences.PrizeWheelCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.PrizeWheelCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.PrizeWheelCount); + } + } + + private long _prizeWheelTime; + + public long PrizeWheelTime + { + get { return _prizeWheelTime; } + set + { + if (_prizeWheelTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _prizeWheelTime; + changeValue.newValue = value; + + _prizeWheelTime = value; + preferences.PrizeWheelTime = _prizeWheelTime; + AddToAutoDelaySaveList(PreferencesField.PrizeWheelTime, preferences.PrizeWheelTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.PrizeWheelTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.PrizeWheelTime); + } + } + + private bool _payBox1; + + public bool PayBox1 + { + get { return _payBox1; } + set + { + if (_payBox1 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _payBox1; + changeValue.newValue = value; + + _payBox1 = value; + preferences.PayBox1 = _payBox1; + AddToAutoDelaySaveList(PreferencesField.PayBox1, preferences.PayBox1); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.PayBox1, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.PayBox1); + } + } + private bool _payBox2; + + public bool PayBox2 + { + get { return _payBox2; } + set + { + if (_payBox2 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = _payBox2; + changeValue.newValue = value; + + _payBox2 = value; + preferences.PayBox2 = _payBox2; + AddToAutoDelaySaveList(PreferencesField.PayBox2, preferences.PayBox2); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.PayBox2, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.PayBox2); + } + } + + private int totalCoins; + + public int TotalCoins + { + get { return totalCoins; } + set + { + if (totalCoins == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = totalCoins; + changeValue.newValue = value; + + totalCoins = value; + preferences.TotalCoins = totalCoins; + AddToAutoDelaySaveList(PreferencesField.TotalCoins, preferences.TotalCoins); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.TotalCoins, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.TotalCoins); + } + } + + private int adWatchCount; + public int AdWatchCount + { + get { return adWatchCount; } + set + { + if (adWatchCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = adWatchCount; + changeValue.newValue = value; + + adWatchCount = value; + preferences.AdWatchCount = adWatchCount; + AddToAutoDelaySaveList(PreferencesField.AdWatchCount, preferences.AdWatchCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.AdWatchCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.AdWatchCount); + } + } + + private Dictionary _items; + + public Dictionary Items + { + get { return _items; } + set + { + if (_items == value) return; + ChangeValue> changeValue = PreferencesDispatcher>.Instance.changeValue; + changeValue.oldValue = _items; + changeValue.newValue = value; + + _items = value; + preferences.Items = _items; + AddToAutoDelaySaveList(PreferencesField.Items, preferences.Items); + PreferencesDispatcher>.Instance.Dispatch(PreferencesMsg.Items, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.Items); + } + } + + private bool exchangeBindGuide; + + + public bool ExchangeBindGuide + { + get { return exchangeBindGuide; } + set + { + if (exchangeBindGuide == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = exchangeBindGuide; + changeValue.newValue = value; + + exchangeBindGuide = value; + preferences.exchangeBindGuide = exchangeBindGuide; + AddToAutoDelaySaveList(PreferencesField.exchangeBindGuide, preferences.exchangeBindGuide); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.exchangeBindGuide, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.exchangeBindGuide); + } + } + + private string exchangeAccount; + + + public string ExchangeAccount + { + get { return exchangeAccount; } + set + { + if (exchangeAccount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = exchangeAccount; + changeValue.newValue = value; + + exchangeAccount = value; + preferences.exchangeAccount = exchangeAccount; + AddToAutoDelaySaveList(PreferencesField.exchangeAccount, preferences.exchangeAccount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.exchangeAccount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.exchangeAccount); + } + } + + private string exchangeName; + + + public string ExchangeName + { + get { return exchangeName; } + set + { + if (exchangeName == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = exchangeName; + changeValue.newValue = value; + + exchangeName = value; + preferences.exchangeName = exchangeName; + AddToAutoDelaySaveList(PreferencesField.exchangeName, preferences.exchangeName); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.exchangeName, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.exchangeName); + } + } + + private int inUseSkin; + + + public int InUseSkin + { + get { return inUseSkin; } + set + { + if (inUseSkin == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = inUseSkin; + changeValue.newValue = value; + + inUseSkin = value; + preferences.inUseSkin = inUseSkin; + AddToAutoDelaySaveList(PreferencesField.inUseSkin, preferences.inUseSkin); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.inUseSkin, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.inUseSkin); + } + } + + private string paypalAccount; + + + public string PaypalAccount + { + get { return paypalAccount; } + set + { + if (paypalAccount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = paypalAccount; + changeValue.newValue = value; + + paypalAccount = value; + preferences.paypalAccount = paypalAccount; + AddToAutoDelaySaveList(PreferencesField.paypalAccount, preferences.paypalAccount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.paypalAccount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.paypalAccount); + } + } + + private bool isSuccessRedeem; + + + public bool IsSuccessRedeem + { + get { return isSuccessRedeem; } + set + { + if (isSuccessRedeem == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isSuccessRedeem; + changeValue.newValue = value; + + isSuccessRedeem = value; + preferences.isSuccessRedeem = isSuccessRedeem; + AddToAutoDelaySaveList(PreferencesField.isSuccessRedeem, preferences.isSuccessRedeem); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isSuccessRedeem, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isSuccessRedeem); + } + } + + public string short_name; + public string long_name; + + private bool isEditInviteCode; + + public bool IsEditInviteCode + { + get { return isEditInviteCode; } + set + { + if (isEditInviteCode == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isEditInviteCode; + changeValue.newValue = value; + + isEditInviteCode = value; + preferences.isEditInviteCode = isEditInviteCode; + AddToAutoDelaySaveList(PreferencesField.isEditInviteCode, preferences.isEditInviteCode); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isEditInviteCode, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isEditInviteCode); + } + } + + private decimal webViewMakeUpOnlineTime; + + + public decimal WebViewMakeUpOnlineTime + { + get { return webViewMakeUpOnlineTime; } + set + { + if (webViewMakeUpOnlineTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = webViewMakeUpOnlineTime; + changeValue.newValue = value; + + webViewMakeUpOnlineTime = value; + preferences.webViewMakeUpOnlineTime = webViewMakeUpOnlineTime; + AddToAutoDelaySaveList(PreferencesField.webViewMakeUpOnlineTime, preferences.webViewMakeUpOnlineTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.webViewMakeUpOnlineTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.webViewMakeUpOnlineTime); + } + } + + private decimal webViewADTaskOnlineTime; + + public decimal WebViewADTaskOnlineTime + { + get { return webViewADTaskOnlineTime; } + set + { + if (webViewADTaskOnlineTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = webViewADTaskOnlineTime; + changeValue.newValue = value; + + webViewADTaskOnlineTime = value; + preferences.webViewADTaskOnlineTime = webViewADTaskOnlineTime; + AddToAutoDelaySaveList(PreferencesField.webViewADTaskOnlineTime, preferences.webViewADTaskOnlineTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.webViewADTaskOnlineTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.webViewADTaskOnlineTime); + } + } + + private bool isShowRewardFly102; + + public bool IsShowRewardFly102 + { + get { return isShowRewardFly102; } + set + { + if (isShowRewardFly102 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isShowRewardFly102; + changeValue.newValue = value; + + isShowRewardFly102 = value; + preferences.isShowRewardFly102 = isShowRewardFly102; + AddToAutoDelaySaveList(PreferencesField.isShowRewardFly102, preferences.isShowRewardFly102); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isShowRewardFly102, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isShowRewardFly102); + } + } + + private bool isShowRewardFly101; + + + public bool IsShowRewardFly101 + { + get { return isShowRewardFly101; } + set + { + if (isShowRewardFly101 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isShowRewardFly101; + changeValue.newValue = value; + + isShowRewardFly101 = value; + preferences.isShowRewardFly101 = isShowRewardFly101; + AddToAutoDelaySaveList(PreferencesField.isShowRewardFly101, preferences.isShowRewardFly101); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isShowRewardFly101, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isShowRewardFly101); + } + } + + private decimal playReawrd111; + + + public decimal PlayReawrd111 + { + get { return playReawrd111; } + set + { + if (playReawrd111 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = playReawrd111; + changeValue.newValue = value; + + playReawrd111 = value; + preferences.playReawrd111 = playReawrd111; + AddToAutoDelaySaveList(PreferencesField.playReawrd111, preferences.playReawrd111); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.playReawrd111, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.playReawrd111); + } + } + + private bool isShowRewardFly111; + + + public bool IsShowRewardFly111 + { + get { return isShowRewardFly111; } + set + { + if (isShowRewardFly111 == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isShowRewardFly111; + changeValue.newValue = value; + + isShowRewardFly111 = value; + preferences.isShowRewardFly111 = isShowRewardFly111; + AddToAutoDelaySaveList(PreferencesField.isShowRewardFly111, preferences.isShowRewardFly111); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isShowRewardFly111, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isShowRewardFly111); + } + } + + private int openRewardCount; + + + public int OpenRewardCount + { + get { return openRewardCount; } + set + { + if (openRewardCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = openRewardCount; + changeValue.newValue = value; + + openRewardCount = value; + preferences.openRewardCount = openRewardCount; + AddToAutoDelaySaveList(PreferencesField.openRewardCount, preferences.openRewardCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.openRewardCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.openRewardCount); + } + } + + private int interRewardShowLevel; + + + public int InterRewardShowLevel + { + get { return interRewardShowLevel; } + set + { + if (interRewardShowLevel == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = interRewardShowLevel; + changeValue.newValue = value; + + interRewardShowLevel = value; + preferences.interRewardShowLevel = interRewardShowLevel; + AddToAutoDelaySaveList(PreferencesField.interRewardShowLevel, preferences.interRewardShowLevel); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.interRewardShowLevel, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.interRewardShowLevel); + } + } + + private bool isShowOpenReward; + + + public bool IsShowOpenReward + { + get { return isShowOpenReward; } + set + { + if (isShowOpenReward == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isShowOpenReward; + changeValue.newValue = value; + + isShowOpenReward = value; + preferences.isShowOpenReward = isShowOpenReward; + AddToAutoDelaySaveList(PreferencesField.isShowOpenReward, preferences.isShowOpenReward); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isShowOpenReward, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isShowOpenReward); + } + } + + private bool isRealProcessing; + + public bool IsRealProcessing + { + get { return isRealProcessing; } + set + { + if (isRealProcessing == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isRealProcessing; + changeValue.newValue = value; + + isRealProcessing = value; + preferences.isRealProcessing = isRealProcessing; + AddToAutoDelaySaveList(PreferencesField.isRealProcessing, preferences.isRealProcessing); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isRealProcessing, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isRealProcessing); + } + } + + private int realWatchVideo; + + + public int RealWatchVideo + { + get { return realWatchVideo; } + set + { + if (realWatchVideo == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = realWatchVideo; + changeValue.newValue = value; + + realWatchVideo = value; + preferences.realWatchVideo = realWatchVideo; + AddToAutoDelaySaveList(PreferencesField.realWatchVideo, preferences.realWatchVideo); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.realWatchVideo, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.realWatchVideo); + } + } + + private bool isClickH5Icon; + + + public bool IsClickH5Icon + { + get { return isClickH5Icon; } + set + { + if (isClickH5Icon == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isClickH5Icon; + changeValue.newValue = value; + + isClickH5Icon = value; + preferences.isClickH5Icon = isClickH5Icon; + AddToAutoDelaySaveList(PreferencesField.isClickH5Icon, preferences.isClickH5Icon); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isClickH5Icon, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isClickH5Icon); + } + } + + private long lastClickMainIconTime; + + + public long LastClickMainIconTime + { + get { return lastClickMainIconTime; } + set + { + if (lastClickMainIconTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = lastClickMainIconTime; + changeValue.newValue = value; + + lastClickMainIconTime = value; + preferences.lastClickMainIconTime = lastClickMainIconTime; + AddToAutoDelaySaveList(PreferencesField.lastClickMainIconTime, preferences.lastClickMainIconTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.lastClickMainIconTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.lastClickMainIconTime); + } + } + + private int interH5Url1Count; + + public int InterH5Url1Count + { + get { return interH5Url1Count; } + set + { + if (interH5Url1Count == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = interH5Url1Count; + changeValue.newValue = value; + + interH5Url1Count = value; + preferences.interH5Url1Count = interH5Url1Count; + AddToAutoDelaySaveList(PreferencesField.interH5Url1Count, preferences.interH5Url1Count); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.interH5Url1Count, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.interH5Url1Count); + } + } + + private int interH5Url2Count; + + public int InterH5Url2Count + { + get { return interH5Url2Count; } + set + { + if (interH5Url2Count == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = interH5Url2Count; + changeValue.newValue = value; + + interH5Url2Count = value; + preferences.interH5Url2Count = interH5Url2Count; + AddToAutoDelaySaveList(PreferencesField.interH5Url2Count, preferences.interH5Url2Count); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.interH5Url2Count, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.interH5Url2Count); + } + } + + private int makeupRealReportGear; + + public int MakeupRealReportGear + { + get { return makeupRealReportGear; } + set + { + if (makeupRealReportGear == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = makeupRealReportGear; + changeValue.newValue = value; + + makeupRealReportGear = value; + preferences.makeupRealReportGear = makeupRealReportGear; + AddToAutoDelaySaveList(PreferencesField.makeupRealReportGear, preferences.makeupRealReportGear); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.makeupRealReportGear, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.makeupRealReportGear); + } + } + + private bool isLastH5Tab; + + + public bool IsLastH5Tab + { + get { return isLastH5Tab; } + set + { + if (isLastH5Tab == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isLastH5Tab; + changeValue.newValue = value; + + isLastH5Tab = value; + preferences.isLastH5Tab = isLastH5Tab; + AddToAutoDelaySaveList(PreferencesField.isLastH5Tab, preferences.isLastH5Tab); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isLastH5Tab, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isLastH5Tab); + } + } + + private long adCashFlyShowTime; + + + public long AdCashFlyShowTime + { + get { return adCashFlyShowTime; } + set + { + if (adCashFlyShowTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = adCashFlyShowTime; + changeValue.newValue = value; + + adCashFlyShowTime = value; + preferences.adCashFlyShowTime = adCashFlyShowTime; + AddToAutoDelaySaveList(PreferencesField.adCashFlyShowTime, preferences.adCashFlyShowTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.adCashFlyShowTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.adCashFlyShowTime); + } + } + + private int adTaskCount; + + + public int AdTaskCount + { + get { return adTaskCount; } + set + { + if (adTaskCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = adTaskCount; + changeValue.newValue = value; + + adTaskCount = value; + preferences.adTaskCount = adTaskCount; + AddToAutoDelaySaveList(PreferencesField.adTaskCount, preferences.adTaskCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.adTaskCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.adTaskCount); + } + } + + private int correctAnswerCount; + + + public int CorrectAnswerCount + { + get { return correctAnswerCount; } + set + { + if (correctAnswerCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = correctAnswerCount; + changeValue.newValue = value; + + correctAnswerCount = value; + preferences.correctAnswerCount = correctAnswerCount; + AddToAutoDelaySaveList(PreferencesField.correctAnswerCount, preferences.correctAnswerCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.correctAnswerCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.correctAnswerCount); + } + } + + private int h5StayTime; + + + public int H5StayTime + { + get { return h5StayTime; } + set + { + if (h5StayTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = h5StayTime; + changeValue.newValue = value; + + h5StayTime = value; + preferences.h5StayTime = h5StayTime; + AddToAutoDelaySaveList(PreferencesField.h5StayTime, preferences.h5StayTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.h5StayTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.h5StayTime); + } + } + + private int videoWatchCount; + + + public int VideoWatchCount + { + get { return videoWatchCount; } + set + { + if (videoWatchCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = videoWatchCount; + changeValue.newValue = value; + + videoWatchCount = value; + preferences.videoWatchCount = videoWatchCount; + AddToAutoDelaySaveList(PreferencesField.videoWatchCount, preferences.videoWatchCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.videoWatchCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.videoWatchCount); + } + } + + private int signInCount; + + + public int SignInCount + { + get { return signInCount; } + set + { + if (signInCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = signInCount; + changeValue.newValue = value; + + signInCount = value; + preferences.signInCount = signInCount; + AddToAutoDelaySaveList(PreferencesField.signInCount, preferences.signInCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.signInCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.signInCount); + } + } + + private int inviteCount; + + + public int InviteCount + { + get { return inviteCount; } + set + { + if (inviteCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = inviteCount; + changeValue.newValue = value; + + inviteCount = value; + preferences.inviteCount = inviteCount; + AddToAutoDelaySaveList(PreferencesField.inviteCount, preferences.inviteCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.inviteCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.inviteCount); + } + } + + private bool naiveStepFinish; + + + public bool NaiveStepFinish + { + get { return naiveStepFinish; } + set + { + if (naiveStepFinish == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = naiveStepFinish; + changeValue.newValue = value; + + naiveStepFinish = value; + preferences.naiveStepFinish = naiveStepFinish; + AddToAutoDelaySaveList(PreferencesField.naiveStepFinish, preferences.naiveStepFinish); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.naiveStepFinish, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.naiveStepFinish); + } + } + + private decimal makeupTaskH5Time; + + + public decimal MakeupTaskH5Time + { + get { return makeupTaskH5Time; } + set + { + if (makeupTaskH5Time == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = makeupTaskH5Time; + changeValue.newValue = value; + + makeupTaskH5Time = value; + preferences.makeupTaskH5Time = makeupTaskH5Time; + AddToAutoDelaySaveList(PreferencesField.makeupTaskH5Time, preferences.makeupTaskH5Time); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.makeupTaskH5Time, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.makeupTaskH5Time); + } + } + + private bool makeupConditionMark; + + + public bool MakeupConditionMark + { + get { return makeupConditionMark; } + set + { + if (makeupConditionMark == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = makeupConditionMark; + changeValue.newValue = value; + + makeupConditionMark = value; + preferences.makeupConditionMark = makeupConditionMark; + AddToAutoDelaySaveList(PreferencesField.makeupConditionMark, preferences.makeupConditionMark); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.makeupConditionMark, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.makeupConditionMark); + } + } + + private int gameStartCount; + + + public int GameStartCount + { + get { return gameStartCount; } + set + { + if (gameStartCount == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = gameStartCount; + changeValue.newValue = value; + + gameStartCount = value; + preferences.gameStartCount = gameStartCount; + AddToAutoDelaySaveList(PreferencesField.gameStartCount, preferences.gameStartCount); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.gameStartCount, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.gameStartCount); + } + } + + private int loginGameTodayTimes; + + + public int LoginGameTodayTimes + { + get { return loginGameTodayTimes; } + set + { + if (loginGameTodayTimes == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = loginGameTodayTimes; + changeValue.newValue = value; + + loginGameTodayTimes = value; + preferences.loginGameTodayTimes = loginGameTodayTimes; + AddToAutoDelaySaveList(PreferencesField.loginGameTodayTimes, preferences.loginGameTodayTimes); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.loginGameTodayTimes, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.loginGameTodayTimes); + } + } + + private int videoEffective_count; + + + public int VideoEffective_count + { + get { return videoEffective_count; } + set + { + if (videoEffective_count == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = videoEffective_count; + changeValue.newValue = value; + + videoEffective_count = value; + preferences.videoEffective_count = videoEffective_count; + AddToAutoDelaySaveList(PreferencesField.videoEffective_count, preferences.videoEffective_count); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.videoEffective_count, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.videoEffective_count); + } + } + + private bool isLogEffective; + + + public bool IsLogEffective + { + get { return isLogEffective; } + set + { + if (isLogEffective == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = isLogEffective; + changeValue.newValue = value; + + isLogEffective = value; + preferences.isLogEffective = isLogEffective; + AddToAutoDelaySaveList(PreferencesField.isLogEffective, preferences.isLogEffective); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.isLogEffective, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.isLogEffective); + } + } + + private long data_ver; + + + public long Data_ver + { + get { return data_ver; } + set + { + if (data_ver == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = data_ver; + changeValue.newValue = value; + + data_ver = value; + preferences.data_ver = data_ver; + Save(PreferencesField.data_ver, preferences.data_ver); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.data_ver, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.data_ver); + } + } + + private bool haveBeenGameStart; + + + public bool HaveBeenGameStart + { + get { return haveBeenGameStart; } + set + { + if (haveBeenGameStart == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = haveBeenGameStart; + changeValue.newValue = value; + + haveBeenGameStart = value; + preferences.haveBeenGameStart = haveBeenGameStart; + AddToAutoDelaySaveList(PreferencesField.haveBeenGameStart, preferences.haveBeenGameStart); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.haveBeenGameStart, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.haveBeenGameStart); + } + } + + private string date; + + + public string Date + { + get { return date; } + set + { + if (date == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = date; + changeValue.newValue = value; + + date = value; + preferences.date = date; + AddToAutoDelaySaveList(PreferencesField.date, preferences.date); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.date, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.date); + } + } + + private int lastLoginDays; + + + public int LastLoginDays + { + get { return lastLoginDays; } + set + { + if (lastLoginDays == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = lastLoginDays; + changeValue.newValue = value; + + lastLoginDays = value; + preferences.lastLoginDays = lastLoginDays; + AddToAutoDelaySaveList(PreferencesField.lastLoginDays, preferences.lastLoginDays); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.lastLoginDays, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.lastLoginDays); + } + } + + #endregion + + #region RefType + + public List SignState + { + get + { + if (preferences.signState == null) preferences.signState = new List(); + return preferences.signState; + } + } + + public void SaveSignState() + { + AddToAutoDelaySaveList(PreferencesField.signState, SignState); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.signState); + dataDispatcher.Dispatch(PreferencesMsg.signState); + } + + + public List CompleteGuideList + { + get + { + if (preferences.completeGuideList == null) preferences.completeGuideList = new List(); + return preferences.completeGuideList; + } + } + + public void SaveCompleteGuideList() + { + AddToAutoDelaySaveList(PreferencesField.completeGuideList, CompleteGuideList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.completeGuideList); + dataDispatcher.Dispatch(PreferencesMsg.completeGuideList); + } + + + public List OnceStatistcList + { + get + { + if (preferences.onceStatistcList == null) preferences.onceStatistcList = new List(); + return preferences.onceStatistcList; + } + } + + public void SaveOnceStatistcList() + { + AddToAutoDelaySaveList(PreferencesField.onceStatistcList, OnceStatistcList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.onceStatistcList); + dataDispatcher.Dispatch(PreferencesMsg.onceStatistcList); + } + + + public List HaveRedeemedSkin + { + get + { + if (preferences.haveRedeemedSkin == null) preferences.haveRedeemedSkin = new List(); + return preferences.haveRedeemedSkin; + } + } + + public void SaveHaveRedeemedSkin() + { + AddToAutoDelaySaveList(PreferencesField.haveRedeemedSkin, HaveRedeemedSkin); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.haveRedeemedSkin); + dataDispatcher.Dispatch(PreferencesMsg.haveRedeemedSkin); + } + + public List InviteDataList + { + get + { + if (preferences.inviteDataList == null) preferences.inviteDataList = new List(); + return preferences.inviteDataList; + } + } + + public void SaveInviteDataList() + { + AddToAutoDelaySaveList(PreferencesField.inviteDataList, InviteDataList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.inviteDataList); + dataDispatcher.Dispatch(PreferencesMsg.inviteDataList); + } + + + public List InviteRecordList + { + get + { + if (preferences.inviteRecordList == null) preferences.inviteRecordList = new List(); + return preferences.inviteRecordList; + } + } + + public void SaveInviteRecordList() + { + AddToAutoDelaySaveList(PreferencesField.inviteRecordList, InviteRecordList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.inviteRecordList); + dataDispatcher.Dispatch(PreferencesMsg.inviteRecordList); + } + + + public List InviteMakeUpHistoryList + { + get + { + if (preferences.inviteMakeUpHistoryList == null) + preferences.inviteMakeUpHistoryList = new List(); + return preferences.inviteMakeUpHistoryList; + } + } + + public void SaveInviteMakeUpHistoryList() + { + AddToAutoDelaySaveList(PreferencesField.inviteMakeUpHistoryList, InviteMakeUpHistoryList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.inviteMakeUpHistoryList); + dataDispatcher.Dispatch(PreferencesMsg.inviteMakeUpHistoryList); + } + + public List MakeupSatisfyGears + { + get + { + if (preferences.makeupSatisfyGears == null) preferences.makeupSatisfyGears = new List(); + return preferences.makeupSatisfyGears; + } + } + + public void SaveMakeupSatisfyGears() + { + AddToAutoDelaySaveList(PreferencesField.makeupSatisfyGears, MakeupSatisfyGears); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.makeupSatisfyGears); + dataDispatcher.Dispatch(PreferencesMsg.makeupSatisfyGears); + } + + + public List AdTaskDataList + { + get + { + if (preferences.adTaskDataList == null) preferences.adTaskDataList = new List(); + return preferences.adTaskDataList; + } + } + + public void SaveAdTaskDataList() + { + AddToAutoDelaySaveList(PreferencesField.adTaskDataList, AdTaskDataList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.adTaskDataList); + dataDispatcher.Dispatch(PreferencesMsg.adTaskDataList); + } + + + public List AchievementAnswerList + { + get + { + if (preferences.achievementAnswerList == null) preferences.achievementAnswerList = new List(); + return preferences.achievementAnswerList; + } + } + + public void SaveAchievementAnswerList() + { + AddToAutoDelaySaveList(PreferencesField.achievementAnswerList, AchievementAnswerList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.achievementAnswerList); + dataDispatcher.Dispatch(PreferencesMsg.achievementAnswerList); + } + + + public List AchievementSignInList + { + get + { + if (preferences.achievementSignInList == null) preferences.achievementSignInList = new List(); + return preferences.achievementSignInList; + } + } + + public void SaveAchievementSignInList() + { + AddToAutoDelaySaveList(PreferencesField.achievementSignInList, AchievementSignInList); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.achievementSignInList); + dataDispatcher.Dispatch(PreferencesMsg.achievementSignInList); + } + + + public List MakeupTaskHistory + { + get + { + if (preferences.makeupTaskHistory == null) preferences.makeupTaskHistory = new List(); + return preferences.makeupTaskHistory; + } + } + + public void SaveMakeupTaskHistory() + { + AddToAutoDelaySaveList(PreferencesField.makeupTaskHistory, MakeupTaskHistory); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.makeupTaskHistory); + dataDispatcher.Dispatch(PreferencesMsg.makeupTaskHistory); + } + + public Dictionary StatisticDictionary + { + get + { + if (preferences.statisticDictionary == null) + preferences.statisticDictionary = new Dictionary(); + return preferences.statisticDictionary; + } + } + + public void SaveStatisticDictionary() + { + AddToAutoDelaySaveList(PreferencesField.statisticDictionary, StatisticDictionary); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.statisticDictionary); + dataDispatcher.Dispatch(PreferencesMsg.statisticDictionary); + } + + #endregion + + private long nextOpenWheelStampTime; + + + public long NextOpenWheelStampTime + { + get { return nextOpenWheelStampTime; } + set + { + if (nextOpenWheelStampTime == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = nextOpenWheelStampTime; + changeValue.newValue = value; + + nextOpenWheelStampTime = value; + preferences.nextOpenWheelStampTime = nextOpenWheelStampTime; + AddToAutoDelaySaveList(PreferencesField.nextOpenWheelStampTime, preferences.nextOpenWheelStampTime); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.nextOpenWheelStampTime, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.nextOpenWheelStampTime); + } + } + + private int thisDayWatchSlyderVideoNum; + + + public int ThisDayWatchSlyderVideoNum + { + get { return thisDayWatchSlyderVideoNum; } + set + { + if (thisDayWatchSlyderVideoNum == value) return; + ChangeValue changeValue = PreferencesDispatcher.Instance.changeValue; + changeValue.oldValue = thisDayWatchSlyderVideoNum; + changeValue.newValue = value; + + thisDayWatchSlyderVideoNum = value; + preferences.thisDayWatchSlyderVideoNum = thisDayWatchSlyderVideoNum; + AddToAutoDelaySaveList(PreferencesField.thisDayWatchSlyderVideoNum, + preferences.thisDayWatchSlyderVideoNum); + PreferencesDispatcher.Instance.Dispatch(PreferencesMsg.thisDayWatchSlyderVideoNum, changeValue); + dataDispatcher.Dispatch(PreferencesMsg.thisDayWatchSlyderVideoNum); + } + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs.meta b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs.meta new file mode 100644 index 0000000..8e342c0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMgr_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 935e480d49b8ffa4381022530d2f6acc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs new file mode 100644 index 0000000..a5dc44c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs @@ -0,0 +1,217 @@ +namespace ScrewsMaster +{ + public static class PreferencesMsg + { + public const string currency102 = "Preferences_currency101"; + public const string maxCurrency102 = "Preferences_maxCurrency101"; + + public const string nextNewDayTime = "Preferences_nextNewDayTime"; + public const string nextOpenWheelStampTime = "Preferences_nextOpenWheelStampTime"; + public const string thisDayWatchSlyderVideoNum = "Preferences_thisDayWatchSlyderVideoNum"; + public const string playerName = "Preferences_playerName"; + public const string playerAvatarId = "Preferences_playerAvatarId"; + public const string signState = "Preferences_signState"; + + + public const string completeGuideList = "Preferences_completeGuideList"; + + public const string isResetGuide = "Preferences_isResetGuide"; + + + public const string gameOfCount = "Preferences_gameOfCount"; + + + public const string winOfGame = "Preferences_winOfGame"; + + + public const string onceStatistcList = "Preferences_onceStatistcList"; + + + public const string watchVideoBeginSum = "Preferences_watchVideoBeginSum"; + + + public const string isGod = "Preferences_isGod"; + + + public const string facebookId = "Preferences_facebookId"; + + + public const string facebookName = "Preferences_facebookName"; + + + public const string facebookAvatarUrl = "Preferences_facebookAvatarUrl"; + + + public const string updataFBLogin_Data = "Preferences_updataFBLogin_Data"; + + + public const string isFaceBookLogin = "Preferences_isFaceBookLogin"; + + + public const string isGuideFinish = "Preferences_isGuideFinish"; + + + public const string currentQuestionIndex = "Preferences_currentQuestionIndex"; + + public const string GameLevel = "Preferences_GameLevel"; + public const string BattleExp = "Preferences_BattleExp"; + public const string TotalCoins = "Preferences_TotalCoins"; + public const string PayBox1 = "Preferences_PayBox1"; + public const string PayBox2 = "Preferences_PayBox2"; + public const string Items = "Preferences_Items"; + public const string PrizeWheelCount = "Preferences_PrizeWheelCount"; + public const string PrizeWheelTime = "Preferences_PrizeWheelTime"; + public const string AdWatchCount = "Preferences_AdWatchCount"; + + + public const string exchangeBindGuide = "Preferences_exchangeBindGuide"; + + + public const string exchangeAccount = "Preferences_exchangeAccount"; + + + public const string exchangeName = "Preferences_exchangeName"; + + + public const string haveRedeemedSkin = "Preferences_haveRedeemedSkin"; + + + public const string inUseSkin = "Preferences_inUseSkin"; + + + public const string paypalAccount = "Preferences_paypalAccount"; + + + public const string isSuccessRedeem = "Preferences_isSuccessRedeem"; + + public const string inviteDataList = "Preferences_inviteDataList"; + + + public const string inviteRecordList = "Preferences_inviteRecordList"; + + + public const string inviteMakeUpHistoryList = "Preferences_inviteMakeUpHistoryList"; + + public const string isEditInviteCode = "Preferences_isEditInviteCode"; + + + public const string webViewMakeUpOnlineTime = "Preferences_webViewMakeUpOnlineTime"; + + public const string webViewADTaskOnlineTime = "Preferences_webViewADTaskOnlineTime"; + + + public const string isShowRewardFly101 = "Preferences_isShowRewardFly101"; + public const string isShowRewardFly102 = "Preferences_isShowRewardFly102"; + + + public const string playReawrd111 = "Preferences_playReawrd111"; + + + public const string isShowRewardFly111 = "Preferences_isShowRewardFly111"; + + + public const string openRewardCount = "Preferences_openRewardCount"; + + + public const string interRewardShowLevel = "Preferences_interRewardShowLevel"; + + + public const string isShowOpenReward = "Preferences_isShowOpenReward"; + + public const string isRealProcessing = "Preferences_isRealProcessing"; + + + public const string realWatchVideo = "Preferences_realWatchVideo"; + + + public const string isClickH5Icon = "Preferences_isClickH5Icon"; + + + public const string lastClickMainIconTime = "Preferences_lastClickMainIconTime"; + + public const string interH5Url1Count = "Preferences_interH5Url1Count"; + public const string interH5Url2Count = "Preferences_interH5Url2Count"; + public const string makeupSatisfyGears = "Preferences_makeupSatisfyGears"; + public const string makeupRealReportGear = "Preferences_makeupRealReportGear"; + + + public const string isLastH5Tab = "Preferences_isLastH5Tab"; + + + public const string adCashFlyShowTime = "Preferences_adCashFlyShowTime"; + + + public const string adTaskDataList = "Preferences_adTaskDataList"; + + + public const string adTaskCount = "Preferences_adTaskCount"; + + + public const string correctAnswerCount = "Preferences_correctAnswerCount"; + + + public const string achievementAnswerList = "Preferences_achievementAnswerList"; + + + public const string h5StayTime = "Preferences_h5StayTime"; + + + public const string achievementH5List = "Preferences_achievementH5List"; + + + public const string videoWatchCount = "Preferences_videoWatchCount"; + + + public const string achievementVideoList = "Preferences_achievementVideoList"; + + + public const string signInCount = "Preferences_signInCount"; + + + public const string achievementSignInList = "Preferences_achievementSignInList"; + + + public const string inviteCount = "Preferences_inviteCount"; + + + public const string achievementInviteList = "Preferences_achievementInviteList"; + + + public const string naiveStepFinish = "Preferences_naiveStepFinish"; + + + public const string makeupTaskHistory = "Preferences_makeupTaskHistory"; + + + public const string makeupTaskH5Time = "Preferences_makeupTaskH5Time"; + + + public const string makeupConditionMark = "Preferences_makeupConditionMark"; + + public const string statisticDictionary = "Preferences_statisticDictionary"; + + + public const string gameStartCount = "Preferences_gameStartCount"; + + + public const string loginGameTodayTimes = "Preferences_loginGameTodayTimes"; + + + public const string videoEffective_count = "Preferences_videoEffective_count"; + + + public const string isLogEffective = "Preferences_isLogEffective"; + + + public const string data_ver = "Preferences_data_ver"; + + + public const string haveBeenGameStart = "Preferences_haveBeenGameStart"; + + + public const string date = "Preferences_date"; + + + public const string lastLoginDays = "Preferences_lastLoginDays"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs.meta b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs.meta new file mode 100644 index 0000000..baf5d0a --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/PreferencesMgr/PreferencesMsg_AutoCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d352f19554a6f98469bd971e95579515 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Register.meta b/Assets/CrazyZoo/Runtime/Logic/Register.meta new file mode 100644 index 0000000..7f63141 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ec1cb10615999c74096dd60afb7502b5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs b/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs new file mode 100644 index 0000000..50442a3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs @@ -0,0 +1,29 @@ +namespace ScrewsMaster +{ + public static class AppManagerRegister + { + public static void Register() + { + var managerOfManager = ManagerOfManager.Instance; + managerOfManager.AddManager(CameraManager.Instance); + managerOfManager.AddManager(AudioManager.Instance); + managerOfManager.AddManager(UIManager.Instance); + + managerOfManager.AddManager(HallManager.Instance); + managerOfManager.AddManager(FXManager.Instance); + managerOfManager.AddManager(NetworkManager.Instance); + } + + public static void RegisterData() + { + RegisterFont(); + } + + private static void RegisterFont() + { + UIManager uiManager = UIManager.Instance; + uiManager.RegisterDefaultFont("KhmerUIb"); + uiManager.RegisterFont("KhmerUIb"); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs.meta new file mode 100644 index 0000000..6aa7727 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/AppManagerRegister.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8090c438fd3dff489a9bf404d95c712 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs b/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs new file mode 100644 index 0000000..1e7db95 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs @@ -0,0 +1,32 @@ +namespace ScrewsMaster +{ + public static class ManagerRegister + { + public static void Register() + { + var managerOfManager = ManagerOfManager.Instance; + managerOfManager.AddManager(ModuleManager.Instance); + + managerOfManager.AddManager(DateTimeManager.Instance); + managerOfManager.AddManager(GameIManager.Instance); + managerOfManager.AddManager(SceneManager.Instance); + + managerOfManager.AddManager(SceneSwitchManager.Instance); + managerOfManager.AddManager(TimerIManager.Instance); + + managerOfManager.AddManager(PreferencesMgr.Instance); + } + + public static void RegisterData() + { + SceneManagerRegister.AutoRegisterScene(); + ModuleManagerRegister.AutoRegisterModel(); + ModuleManagerRegister.AutoRegisterUIType(); + ModuleManagerRegister.AutoRegisterCtrl(); + ModuleManagerRegister.AutoRegisterUICtrl(); + UIManagerRegister.AdaptSafeArea(); + UIManagerRegister.AutoRegisterBinder(); + UIManagerRegister.AutoRegisterCommonPackages(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs.meta new file mode 100644 index 0000000..2b239d8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/ManagerRegister.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bced0094754a5d54b981ced997602e71 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs b/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs new file mode 100644 index 0000000..859a554 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs @@ -0,0 +1,12 @@ + +namespace ScrewsMaster +{ + public static class SceneManagerRegister + { + public static void AutoRegisterScene() + { + var sceneManager = SceneManager.Instance; + sceneManager.AddScene(new MainScene()); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs.meta new file mode 100644 index 0000000..70a474b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/SceneManagerRegister.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f494af2b167fb694693b1e327f3521ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs b/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs new file mode 100644 index 0000000..e1435c4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs @@ -0,0 +1,52 @@ +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public static class UIManagerRegister + { + public static void AutoRegisterBinder() + { + FGUI.A000_common.A000_commonBinder.BindAll(); + FGUI.A001_bigImg.A001_bigImgBinder.BindAll(); + FGUI.SLoading.SLoadingBinder.BindAll(); + FGUI.G001_login.G001_loginBinder.BindAll(); + FGUI.G002_main.G002_mainBinder.BindAll(); + FGUI.G003_play.G003_playBinder.BindAll(); + FGUI.G004_webview.G004_webviewBinder.BindAll(); + FGUI.G006_menu.G006_menuBinder.BindAll(); + FGUI.G008_reward.G008_rewardBinder.BindAll(); + FGUI.G007_makeup.G007_makeupBinder.BindAll(); + FGUI.G009_video.G009_videoBinder.BindAll(); + FGUI.G012_openReward.G012_openRewardBinder.BindAll(); + FGUI.G502_Fx.G502_FxBinder.BindAll(); + FGUI.G601_Coin.G601_CoinBinder.BindAll(); + FGUI.SC001_Tips.SC001_TipsBinder.BindAll(); + FGUI.SC004_Mask.SC004_MaskBinder.BindAll(); + FGUI.SC005_NetIdle.SC005_NetIdleBinder.BindAll(); + FGUI.SC006_privacy.SC006_privacyBinder.BindAll(); + FGUI.G014_SignIn.G014_SignInBinder.BindAll(); + FGUI.G018_GameHome.G018_GameHomeBinder.BindAll(); + FGUI.G019_Rank.G019_RankBinder.BindAll(); + FGUI.G020_PrizeWheel.G020_PrizeWheelBinder.BindAll(); + FGUI.SaveingPot.SaveingPotBinder.BindAll(); + FGUI.failpack.failpackBinder.BindAll(); + FGUI.bkg_jilu.bkg_jiluBinder.BindAll(); + FGUI.threeDaysGift.threeDaysGiftBinder.BindAll(); + FGUI.bkg_reward_new.bkg_reward_newBinder.BindAll(); + } + + public static void AutoRegisterCommonPackages() + { + List commonPackages = new List(); + + commonPackages.Add("A000_common"); + + UIManager.Instance.RegisterCommonPackages(commonPackages); + } + + public static void AdaptSafeArea() + { + UIManager.Instance.AdaptSafeArea(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs.meta b/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs.meta new file mode 100644 index 0000000..83b5d6f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/Register/UIManagerRegister.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5acb072f033b2aa47a957646f9be3960 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/System.meta b/Assets/CrazyZoo/Runtime/Logic/System.meta new file mode 100644 index 0000000..622ac43 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 24fd448dc30f4b3ba51c9af54d02991f +timeCreated: 1692256098 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game.meta b/Assets/CrazyZoo/Runtime/Logic/System/Game.meta new file mode 100644 index 0000000..c08741b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 77c9a25febe54dffbb6afade123b3a42 +timeCreated: 1692267362 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs new file mode 100644 index 0000000..1b57db7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; + +namespace ScrewsMaster +{ + public class ConsumeSystem : BaseSystem + { + public ConsumeSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + public sealed override void Init() + { + base.Init(); + + AddListener(); + } + + private void AddListener() + { + CtrlDispatcher.Instance.AddListener(CtrlMsg.ConsumeResources, OnConsumeResources); + } + + private void OnConsumeResources(object obj) + { + ConsumeVal consumeVal = (ConsumeVal)obj; + + int consumeSuccessCount = 0; + for (var index = 0; index < consumeVal.ItemId.Count; index++) + { + var item = consumeVal.ItemId[index]; + var itemValue = consumeVal.ItemVal[index]; + switch (item) + { + case 101: + if (itemValue <= GameHelper.Get102()) + { + consumeSuccessCount++; + } + else + { + GameHelper.ShowTips("No enough", true); + } + + break; + } + } + + if (consumeVal.isConsume) + { + if (consumeSuccessCount == consumeVal.ItemId.Count) + { + for (var index = 0; index < consumeVal.ItemId.Count; index++) + { + var item = consumeVal.ItemId[index]; + var itemValue = consumeVal.ItemVal[index]; + switch (item) + { + case 101: + if (itemValue <= GameHelper.Get102()) + { + PreferencesMgr.Instance.Currency102 -= itemValue; + } + + break; + } + } + + consumeVal.onfinish?.Invoke(true); + } + else + { + consumeVal.onfinish?.Invoke(false); + } + } + else + { + consumeVal.onfinish?.Invoke(consumeSuccessCount == consumeVal.ItemId.Count); + } + + consumeVal.Release(); + } + + #region 消耗资源 + + public static void Consume(int itemId, int itemNum, Action onCompleted = null, bool isConsume = true) + { + ConsumeVal consumeVal = ConsumeVal.Get(itemId, itemNum, onCompleted); + consumeVal.isConsume = isConsume; + CtrlDispatcher.Instance.Dispatch(CtrlMsg.ConsumeResources, consumeVal); + } + + public static void Consume(int itemId, decimal itemNum, Action onCompleted = null, bool isConsume = true) + { + ConsumeVal consumeVal = ConsumeVal.Get(itemId, itemNum, onCompleted); + consumeVal.isConsume = isConsume; + CtrlDispatcher.Instance.Dispatch(CtrlMsg.ConsumeResources, consumeVal); + } + + + public static void Consume(int[] itemIds, int[] itemNums, Action onCompleted = null, + bool isConsume = true) + { + ConsumeVal consumeVal = ConsumeVal.Get(); + consumeVal.onfinish = onCompleted; + for (int i = 0; i < itemIds.Length; i++) + { + consumeVal.AddConsume(itemIds[i], itemNums[i]); + } + + consumeVal.isConsume = isConsume; + CtrlDispatcher.Instance.Dispatch(CtrlMsg.ConsumeResources, consumeVal); + } + + public static void Consume(int[] itemIds, decimal[] itemNums, Action onCompleted = null, + bool isConsume = true) + { + ConsumeVal consumeVal = ConsumeVal.Get(); + consumeVal.onfinish = onCompleted; + for (int i = 0; i < itemIds.Length; i++) + { + consumeVal.AddConsume(itemIds[i], itemNums[i]); + } + + consumeVal.isConsume = isConsume; + CtrlDispatcher.Instance.Dispatch(CtrlMsg.ConsumeResources, consumeVal); + } + + #endregion + + public static void CheckItem(int itemId, int itemNum, Action onCompleted = null) + { + Consume(itemId, itemNum, onCompleted, false); + } + + public static void CheckItem(int itemId, decimal itemNum, Action onCompleted = null) + { + Consume(itemId, itemNum, onCompleted, false); + } + + public static void CheckItem(int[] itemId, int[] itemNum, Action onCompleted = null) + { + Consume(itemId, itemNum, onCompleted, false); + } + + public static void CheckItem(int[] itemId, decimal[] itemNum, Action onCompleted = null) + { + Consume(itemId, itemNum, onCompleted, false); + } + } + + + public class ConsumeVal + { + private static ObjectPool _pool = new ObjectPool(); + + public static ConsumeVal Get() + { + ConsumeVal val = _pool.Get(); + return val; + } + + public static ConsumeVal Get(int id, decimal sum) + { + return Get(id, sum); + } + + public static ConsumeVal Get(int id, decimal sum, Action finish = null) + { + ConsumeVal val = _pool.Get(); + val.AddConsume(id, sum); + val.onfinish = finish; + return val; + } + + + public void Release() + { + ItemId.Clear(); + ItemVal.Clear(); + isConsume = true; + onfinish = null; + _pool.Release(this); + } + + public ConsumeVal() + { + } + + public Action onfinish; + + public List ItemId = new List(); + public List ItemVal = new List(); + + public bool isConsume = true; + + public void AddConsume(int id, decimal sum) + { + ItemId.Add(id); + ItemVal.Add(sum); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs.meta new file mode 100644 index 0000000..573fecc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/ConsumeSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fcd01defe47f4c65b155e8edb148d1cc +timeCreated: 1692785015 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs new file mode 100644 index 0000000..d7ac4bc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs @@ -0,0 +1,558 @@ +using System; +using System.Linq; +using UnityEngine; + +namespace ScrewsMaster +{ + public class GameDataSystem : BaseSystem + { + public Action UpdateSecondEvent; + + private Action onChangeDollar; + + private Action onChangeGiftSwitch; + + public GameDataSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + public sealed override void Init() + { + base.Init(); + AddListener(); + } + + private void AddListener() + { + CtrlDispatcher.Instance.AddListener(CtrlMsg.Game_StartBefore, InitPreferences); + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.currency102, OnChange102); + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.playReawrd111, OnChange111); + CtrlDispatcher.Instance.AddListener(CtrlMsg.GameNewDays, NewDay); + CtrlDispatcher.Instance.AddListener(CtrlMsg.Module_GiftSwitchChange, OnChangeGiftSwitch); + GameDispatcher.Instance.AddListener(GameMsg.RefreshADTask, RefreshADTaskData); + CtrlDispatcher.Instance.AddListener(CtrlMsg.WatchVideoFinish, AddWatchVideo); + CtrlDispatcher.Instance.AddListener(CtrlMsg.WatchIntVideoFinish, AddIntWatchVideo); + + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.isShowRewardFly101, OnChangeRewardFly101); + PreferencesDispatcher.Instance.AddListener(PreferencesMsg.isShowRewardFly111, OnChangeRewardFly111); + GameDispatcher.Instance.AddListener(GameMsg.ProcessReward, OnGetReward); + GameDispatcher.Instance.AddListener(GameMsg.RefreshMakeupData, OnRefreshMakeupData); + + } + + private void OnChangeGiftSwitch(object obj) + { + onChangeGiftSwitch?.Invoke(); + } + + + private void InitPreferences(object obj) + { + if (GameHelper.Get102() == -1) + { + PreferencesMgr.Instance.Currency102 = 0; + } + + // if (PreferencesMgr.Instance.PlayerName.IsNullOrWhiteSpace()) + // { + // PreferencesMgr.Instance.PlayerName = "CrazyZoo"; + // } + + if (!GameHelper.IsContinuousSignIn()) + { + PreferencesMgr.Instance.SignState.Clear(); + PreferencesMgr.Instance.SaveSignState(); + } + + if (PreferencesMgr.Instance.PlayerName.IsNullOrWhiteSpace()) + { + if (ModuleManager.Instance.GetModel(ModelConst.LoginModel) is LoginModel loginModel) + { + PreferencesMgr.Instance.PlayerName = loginModel.invite_code; + } + } + + PreferencesMgr.Instance.IsShowRewardFly101 = false; + PreferencesMgr.Instance.IsShowRewardFly102 = false; + + InitAchievement(); + + CheckMakeupTaskData(); + + + PreferencesMgr.Instance.IsLastH5Tab = true; + } + + + private void OnRefreshMakeupData(object obj) + { + AddMakeupTaskData(); + } + + + private void CheckMakeupTaskData() + { + if (!GameHelper.IsGiftSwitch()) + { + return; + } + + + if (PreferencesMgr.Instance.MakeupTaskHistory.Count == 0) + { + AddMakeupTaskData(); + } + else + { + var common = ConfigSystem.GetConfig(); + + foreach (var makeuptaskData in PreferencesMgr.Instance.MakeupTaskHistory) + { + if (makeuptaskData.status == MakeupTaskStatus.Inline + && makeuptaskData.inlineNum > common.inlineMin) + { + + + + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId); + + var days = PlayerPrefs.GetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}", 0); + if (days == DateTime.Today.Day) + { + continue; + } + + PlayerPrefs.SetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}", DateTime.Today.Day); + var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0], + common.inlineLoginDown[1]); + makeuptaskData.loginSpeedNum += loginNum; + //如果登录减少人数大于配置的阈值,则不能减少排名了 + Debug.Log($"登录累计增加的排名为:{makeuptaskData.loginSpeedNum} 阈值为:{redeemVOModel.Login_Limit_times}"); + if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times) + { + makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times; + continue; + } + + //Debug.Log($"订单为: {makeuptaskData.tableId} 通过登录减少的排名为:{loginNum}"); + makeuptaskData.inlineNum -= loginNum; + if (makeuptaskData.inlineNum < common.inlineMin) + { + makeuptaskData.inlineNum = common.inlineMin; + } + } + } + + PreferencesMgr.Instance.SaveMakeupTaskHistory(); + } + if (SaveData.GetSaveobject().saveingpot_history.Count == 0) + { + // Debug.Log("tianjialishiiiiiiiiiiiiii"); + // AddMakeupTaskData(); + } + else + { + var common = ConfigSystem.GetConfig(); + foreach (var makeuptaskData in SaveData.GetSaveobject().saveingpot_history) + { + if (makeuptaskData.status == SaveingPotTaskStatus.Inline + && makeuptaskData.inlineNum > common.inlineMin) + { + + + + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId); + + var days = PlayerPrefs.GetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}_pot", 0); + if (days == DateTime.Today.Day) + { + continue; + } + + PlayerPrefs.SetInt($"days_{NetworkKit.userId}_{makeuptaskData.tableId}_pot", DateTime.Today.Day); + var loginNum = CommonHelper.RandomRange(common.inlineLoginDown[0], + common.inlineLoginDown[1]); + makeuptaskData.loginSpeedNum += loginNum; + //如果登录减少人数大于配置的阈值,则不能减少排名了 + // Debug.Log($"登录累计增加的排名为:{makeuptaskData.loginSpeedNum} 阈值为:{redeemVOModel.Login_Limit_times}"); + if (makeuptaskData.loginSpeedNum > redeemVOModel.Login_Limit_times) + { + makeuptaskData.loginSpeedNum = redeemVOModel.Login_Limit_times; + continue; + } + + //Debug.Log($"订单为: {makeuptaskData.tableId} 通过登录减少的排名为:{loginNum}"); + makeuptaskData.inlineNum -= loginNum; + if (makeuptaskData.inlineNum < common.inlineMin) + { + makeuptaskData.inlineNum = common.inlineMin; + } + } + } + } + SaveData.saveDataFunc(); + } + + private void CheckSpeedUpTaskData(int type = 1) + { + if (!GameHelper.IsGiftSwitch()) + { + return; + } + + var common = ConfigSystem.GetConfig(); + + if (type == 1 && PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + foreach (var makeuptaskData in PreferencesMgr.Instance.MakeupTaskHistory) + { + if (makeuptaskData.status == MakeupTaskStatus.Inline + && makeuptaskData.inlineNum > common.inlineMin) + { + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId); + + var dowmNum = redeemVOModel.AD_Down; + // Debug.Log($"CheckSpeedUpTaskData dowmNum=== {dowmNum} makeuptaskData.WatchVideoSpeedNum ==== {makeuptaskData.WatchVideoSpeedNum}"); + + makeuptaskData.WatchVideoSpeedNum += dowmNum; + //如果看广告的减少人数大于配置的阈值,则不能减少排名了 + if (makeuptaskData.WatchVideoSpeedNum > redeemVOModel.AD_Limit_times) + { + makeuptaskData.WatchVideoSpeedNum = redeemVOModel.AD_Limit_times; + continue; + } + + //Debug.Log($"订单为: {makeuptaskData.tableId} 通过看广告减少的排名为:{dowmNum}"); + makeuptaskData.inlineNum -= dowmNum; + //Debug.Log($"订单为: {makeuptaskData.tableId} 减少后的排名:{makeuptaskData.inlineNum}"); + if (makeuptaskData.inlineNum < common.inlineMin) + { + makeuptaskData.inlineNum = common.inlineMin; + } + } + } + } + if (type == 2 && SaveData.GetSaveobject().saveingpot_history.Count > 0) + { + foreach (var makeuptaskData in SaveData.GetSaveobject().saveingpot_history) + { + if (makeuptaskData.status == SaveingPotTaskStatus.Inline + && makeuptaskData.inlineNum > common.inlineMin) + { + var redeemVOModel = ConfigSystem.GetConfig().dataList + .FirstOrDefault(redeem => redeem.id == makeuptaskData.tableId); + + var dowmNum = redeemVOModel.AD_Down; + // Debug.Log($"CheckSpeedUpTaskData dowmNum=== {dowmNum} makeuptaskData.WatchVideoSpeedNum ==== {makeuptaskData.WatchVideoSpeedNum}"); + + makeuptaskData.WatchVideoSpeedNum += dowmNum; + //如果看广告的减少人数大于配置的阈值,则不能减少排名了 + if (makeuptaskData.WatchVideoSpeedNum > redeemVOModel.AD_Limit_times) + { + makeuptaskData.WatchVideoSpeedNum = redeemVOModel.AD_Limit_times; + continue; + } + + //Debug.Log($"订单为: {makeuptaskData.tableId} 通过看广告减少的排名为:{dowmNum}"); + makeuptaskData.inlineNum -= dowmNum; + //Debug.Log($"订单为: {makeuptaskData.tableId} 减少后的排名:{makeuptaskData.inlineNum}"); + if (makeuptaskData.inlineNum < common.inlineMin) + { + makeuptaskData.inlineNum = common.inlineMin; + } + } + } + } + } + public void AddMakeupTaskData() + { + var makeupVOModel = ConfigSystem.GetConfig(); + if (makeupVOModel == null || makeupVOModel.dataList == null || makeupVOModel.dataList.Count <= 0) + { + return; + } + + + var lastId = -1; + + var isRepeat = PreferencesMgr.Instance.MakeupTaskHistory.Count >= makeupVOModel.dataList.Count; + if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + var makeupTaskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + + if (makeupTaskData.status != MakeupTaskStatus.Inline) + { + return; + } + + lastId = makeupTaskData.tableId; + } + + + if (lastId == makeupVOModel.dataList.Last().id) + { + lastId = -1; + } + + foreach (var makeupVo in makeupVOModel.dataList) + { + if (makeupVo.id > lastId) + { + if ((isRepeat && !makeupVo.is_onetime) || !isRepeat) + { + var makeupTaskData = new MakeupTaskData(); + makeupTaskData.tableId = makeupVo.id; + makeupTaskData.id = PreferencesMgr.Instance.MakeupTaskHistory.Count + 1; + makeupTaskData.amountStr = $"{GameHelper.Get102Str(makeupVo.item_need)}"; + makeupTaskData.amount = makeupVo.item_need; + makeupTaskData.orderID = GameHelper.GetRandomNum(8); + + PreferencesMgr.Instance.MakeupTaskHistory.Add(makeupTaskData); + makeupTaskData.SetStatus(MakeupTaskStatus.None); + PreferencesMgr.Instance.SaveMakeupTaskHistory(); + + PreferencesMgr.Instance.MakeupTaskH5Time = 0; + break; + } + } + } + } + + private void InitAchievement() + { + var achieveVOModel = ConfigSystem.GetConfig(); + if (PreferencesMgr.Instance.AchievementAnswerList.Count == 0 && achieveVOModel != null && + achieveVOModel.dataList.Count > 0) + { + var achieveVo = achieveVOModel.dataList[0]; + for (var i = 0; i < achieveVo.tol_num.Length; i++) + { + PreferencesMgr.Instance.AchievementAnswerList.Add(false); + } + } + + if (PreferencesMgr.Instance.AchievementSignInList.Count == 0 && achieveVOModel != null && + achieveVOModel.dataList.Count > 0) + { + var achieveVo = achieveVOModel.dataList[1]; + for (var i = 0; i < achieveVo.tol_num.Length; i++) + { + PreferencesMgr.Instance.AchievementSignInList.Add(false); + } + } + } + + + private void OnChange102(ChangeValue obj) + { + var val = obj.newValue - obj.oldValue; + if (val > 0) + { + PreferencesMgr.Instance.MaxCurrency102 += val; + } + + if (!PreferencesMgr.Instance.IsShowRewardFly101) + { + GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed); + } + + onChangeDollar?.Invoke(); + } + + + private void OnChange111(ChangeValue obj) + { + if (!PreferencesMgr.Instance.IsShowRewardFly111) + { + GameDispatcher.Instance.Dispatch(GameMsg.Update111Completed); + } + } + + private void NewDay(object obj) + { + PreferencesMgr.Instance.IsShowOpenReward = true; + } + + private void RefreshADTaskData(object obj = null) + { + } + private void AddIntWatchVideo(object obj = null) + { + if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + CheckSpeedUpTaskData(); + } + } + private void AddWatchVideo(object obj = null) + { + PreferencesMgr.Instance.VideoWatchCount++; + GameDispatcher.Instance.Dispatch(GameMsg.RefreshTodoUI); + + if (PreferencesMgr.Instance.MakeupTaskHistory.Count > 0) + { + CheckSpeedUpTaskData(); + + var taskData = PreferencesMgr.Instance.MakeupTaskHistory.Last(); + if (taskData.status == MakeupTaskStatus.Task) + { + var makeupVo = ConfigSystem.GetConfig().GetData(taskData.tableId); + if (makeupVo != null && taskData.videoCount < makeupVo.ad_need) + { + taskData.videoCount++; + NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.watch_ad_number, 1); + PreferencesMgr.Instance.SaveMakeupTaskHistory(); + PlayerPrefs.SetInt("fin_ad_num", 0); + } + else + { + if (PlayerPrefs.GetInt("fin_ad_num", 0) == 0) + { + NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.finish_ad_number, 1); + PlayerPrefs.SetInt("fin_ad_num", 1); + } + + } + } + + } + if (SaveData.GetSaveobject().saveingpot_history.Count > 0) + { + SaveingPotHelper.TestingClearTime(); + CheckSpeedUpTaskData(2); + SaveingPotClass taskData = SaveData.GetSaveobject().saveingpot_history.Last(); + Makeup_2 makeupVo = ConfigSystem.GetConfig().GetData(taskData.tableId); + SaveData.GetSaveobject().saveingpot_cash += makeupVo.ADIncrease; + GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot); + if (ConfigSystem.GetConfig().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch()) + { + if ((SaveData.GetSaveobject().saveingpot_cash > taskData.amount) && (!taskData.auto_show) && !UIManager.Instance.IsExistUI(UIConst.H5UI)) + { + + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SaveingPotUI_Open); + taskData.auto_show = true; + } + } + + if (taskData.status == SaveingPotTaskStatus.Task) + { + ; + if (makeupVo != null && taskData.videoCount < makeupVo.ad_need) + { + taskData.videoCount++; + NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.watch_ad_number, 1); + PlayerPrefs.SetInt("fin_ad_num_saveingpot", 0); + } + else + { + if (PlayerPrefs.GetInt("fin_ad_num_saveingpot", 0) == 0) + { + NetworkKit.BuriedPoint(BuriedPointEvent.ad_task, BuriedPointEvent.finish_ad_number, 1); + PlayerPrefs.SetInt("fin_ad_num_saveingpot", 1); + } + + } + } + + } + } + + private void OnChangeRewardFly101(ChangeValue obj) + { + var oldValue = obj.oldValue; + var newValue = obj.newValue; + + InitChangeRewardFly(101, oldValue, newValue); + } + + private void OnChangeRewardFly111(ChangeValue obj) + { + var oldValue = obj.oldValue; + var newValue = obj.newValue; + + InitChangeRewardFly(111, oldValue, newValue); + } + + private void InitChangeRewardFly(int id, bool oldValue, bool newValue) + { + if (oldValue) + { + if (newValue) + { + } + else + { + switch (id) + { + case 101: + GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed); + break; + case 102: + GameDispatcher.Instance.Dispatch(GameMsg.Update102Completed); + break; + case 111: + GameDispatcher.Instance.Dispatch(GameMsg.Update111Completed); + break; + } + } + } + else + { + if (newValue) + { + } + else + { + } + } + } + + + private void OnGetReward(object obj) + { + if (obj is RewardData rewardModel) + { + foreach (var rewardData in rewardModel.GetRewardDataList()) + { + ProcessData(rewardData); + } + } + } + + + private void ProcessData(RewardSingleData rewardSingleData) + { + if (rewardSingleData.origin == RewardOrigin.None) + { + return; + } + + switch (rewardSingleData.id) + { + case 101: + GameHelper.AddGoldNumber((int)rewardSingleData.GetTotalValue()); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + break; + case 102: + GameHelper.AddMoney((float)rewardSingleData.GetTotalValue()); + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + break; + case 111: + { + var dollar = PreferencesMgr.Instance.PlayReawrd111; + dollar += rewardSingleData.GetTotalValue(); + + PreferencesMgr.Instance.PlayReawrd111 = dollar; + break; + } + } + + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs.meta new file mode 100644 index 0000000..8ffcb44 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/GameDataSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b33f1a409b61479e9b014ab951bbff47 +timeCreated: 1692256149 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs new file mode 100644 index 0000000..0aab50f --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs @@ -0,0 +1,206 @@ +using DG.Tweening; +using ScrewsMaster; +using UnityEngine; + +public class RewardSystem : BaseSystem +{ + public RewardSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + public sealed override void Init() + { + base.Init(); + AddListener(); + } + + private void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.GetReward, OnGetReward); + } + + + private void OnGetReward(object obj) + { + if (!(obj is RewardData rewardData)) + { + return; + } + + + if (IsRewardDialog(rewardData)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardUI_Open, rewardData); + } + else + { + if (IsRewardNumber(rewardData)) + { + rewardData.OnCompleted(true); + GameDispatcher.Instance.Dispatch(GameMsg.ProcessReward, rewardData); + } + else + { + GetReward(rewardData); + } + } + } + + + public static bool IsRewardFly(RewardData rewardData) + { + return (RewardDisplayType.RewardFly & rewardData.displayType) == RewardDisplayType.RewardFly; + } + + + public static bool IsRewardValueChange(RewardData rewardData) + { + return (RewardDisplayType.ValueChange & rewardData.displayType) == RewardDisplayType.ValueChange; + } + + + public static bool IsRewardNumber(RewardData rewardData) + { + return (RewardDisplayType.Number & rewardData.displayType) == RewardDisplayType.Number; + } + + + public static bool IsRewardDialog(RewardData rewardData) + { + return (RewardDisplayType.Dialog & rewardData.displayType) == RewardDisplayType.Dialog; + } + + + public static void GetReward(RewardData rewardData) + { + PlayReward(rewardData); + GameDispatcher.Instance.Dispatch(GameMsg.ProcessReward, rewardData); + } + + private static Tween _tween; + + + private static void PlayReward(RewardData rewardData) + { + if (rewardData == null) return; + var completed = 0; + foreach (var rewardSingleData in rewardData.GetRewardDataList()) + { + var id = rewardSingleData.id; + var sum = rewardSingleData.value; + + if (sum <= 0) + { + continue; + } + + + var isValueChange = IsRewardValueChange(rewardData); + if (isValueChange) + { + if (rewardSingleData.endPosition == Vector2.zero && id is 101 or 102) + { + if (!UIManager.Instance.IsExistUI(UIConst.H5UI)) + { + if (_tween is { active: true }) + { + _tween?.Kill(); + } + + GameHelper.OnRiseUI(id); + } + } + else if (id == 111) + { + if (_tween is { active: true }) + { + _tween?.Kill(); + } + } + + + SetRewardValueChangeState(id, true); + } + + + if (!rewardSingleData.IsCanFly()) + { + continue; + } + + + var isNeedFly = IsRewardFly(rewardData); + + var rewardDisplayModel = new RewardDisplayData(rewardSingleData) + { + isSingle = rewardData.isSingle, + isPlayAudio = true, + isNeedFly = isNeedFly, + isNeedValueChange = isValueChange, + audioName = AudioConst.CoinFly + }; + + rewardDisplayModel.SetUpdate(changeValue => { OnChangeValue(id, changeValue); }); + rewardDisplayModel.SetUpdateComplete(() => + { + completed++; + if (isValueChange) + { + SetRewardValueChangeState(id, false); + if (id == 101) + { + if (!UIManager.Instance.IsExistUI(UIConst.H5UI)) + { + _tween = DOVirtual.DelayedCall(0.5f, + () => { GameHelper.OnRiseUIRecover(id, UILayerType.Normal); }); + } + } + } + + if (completed >= rewardData.GetRewardFlyCount()) + { + rewardData.OnCompleted(true); + } + }); + + rewardSingleData.InitFlyPosition(); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RewardAniUI_Open, rewardDisplayModel); + } + } + + private static void SetRewardValueChangeState(int id, bool isShow) + { + switch (id) + { + case 101: + PreferencesMgr.Instance.IsShowRewardFly101 = isShow; + break; + case 102: + PreferencesMgr.Instance.IsShowRewardFly102 = isShow; + break; + case 111: + PreferencesMgr.Instance.IsShowRewardFly111 = isShow; + break; + } + } + + private static void OnChangeValue(int id, decimal changeValue) + { + switch (id) + { + case 101: + GameDispatcher.Instance.Dispatch(GameMsg.Update101, changeValue); + break; + case 102: + GameDispatcher.Instance.Dispatch(GameMsg.Update101, changeValue); + break; + case 111: + GameDispatcher.Instance.Dispatch(GameMsg.Update111, changeValue); + break; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs.meta new file mode 100644 index 0000000..4cdbfd2 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/RewardSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b41a4be29284494880840871bb69070a +timeCreated: 1692696618 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs new file mode 100644 index 0000000..f3e9415 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs @@ -0,0 +1,78 @@ +namespace ScrewsMaster +{ + public class WindowSystem : BaseSystem + { + public WindowSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + TaskSequence startGameSequence = new TaskSequence(); + TaskSequence backMainSequence = new TaskSequence(); + + public sealed override void Init() + { + base.Init(); + + AddListener(); + } + + private void AddListener() + { + CtrlDispatcher.Instance.AddOnceListener(CtrlMsg.Game_Start, StartGame); + GameDispatcher.Instance.AddListener(GameMsg.BackMainScene, BackMain); + } + + private void StartGame(object obj) + { + startGameSequence.Clear(); + + if (GameHelper.IsOpenGuide()) + { + } + + if (startGameSequence.Count == 0) + { + End(); + } + else + { + startGameSequence.Run(); + } + } + + + private void End() + { + } + + private bool haveBackMain = false; + + private void BackMain(object obj) + { + if (!GameHelper.IsGiftSwitch()) + { + return; + } + + backMainSequence.Clear(); + haveBackMain = true; + backMainSequence.Run(); + } + + private void AddRateUs(TaskSequence backMainSequence) + { + bool isAdd = 5 == PreferencesMgr.Instance.GameOfCount; + + backMainSequence.Add(isAdd, (procedure) => + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.RateUsDialogUI_Open); + UICtrlDispatcher.Instance.AddOnceListener(UICtrlMsg.RateUsDialogUI_Close, + (e) => { procedure.InvokeComplete(); }); + }); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs.meta new file mode 100644 index 0000000..67d0fa4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Game/WindowSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1b4c0d23d2744f868b80f5ea89b2bddf +timeCreated: 1692848262 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network.meta b/Assets/CrazyZoo/Runtime/Logic/System/Network.meta new file mode 100644 index 0000000..ddf0c46 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9b8a1ab8e5a64e3f88ab5bca879f13d6 +timeCreated: 1692267374 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs new file mode 100644 index 0000000..3d8e982 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs @@ -0,0 +1,487 @@ +using System; +using System.IO; +using UnityEngine; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Newtonsoft.Json.Linq; +using Roy; + +namespace ScrewsMaster +{ + public class ConfigSystem : BaseSystem + { + + public const string ConfigFileNameKey = "configFileName"; + + public static List light_weblist = new List(); + public static List dark_weblist = new List(); + public static string web_through_str; + private static readonly Dictionary ConfigData = new Dictionary(); + private LoginModel _loginModel; + + private int _initConfigErrorCount; + + public ConfigSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + public sealed override void Init() + { + base.Init(); + AddListener(); + } + + private void AddListener() + { + NetworkDispatcher.Instance.AddListener(NetworkMsg.GetConfig, OnGetConfig); + } + + private void RemoveListener() + { + NetworkDispatcher.Instance.RemoveListener(NetworkMsg.GetConfig, OnGetConfig); + } + + private void OnGetConfig(object obj) + { + _initConfigErrorCount = 0; + var reqData = new RespLoginFunnelData + { + type = "loadBegin", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData);//加载开始打点 + + OnRequestGetConfig(); + } + + private void OnRequestGetConfig() + { + _loginModel = GameHelper.GetLoginModel(); + + if (_initConfigErrorCount > 6) + { + GameHelper.ShowTips("Configuration file failed to load, please try again later"); + return; + } + + // if (IsFirstLaunch()) + // { + // FirstLaunchCopyConfig();// 进行首次启动的操作 + // return; + // } + + bool needDownloadConfigFile = HasNewConfig(); + //需要下载配置的话等待下载更新 + if (needDownloadConfigFile) + { + DownloadConfig(); + return; + } + + ReadLocalConfig(); + } + + /// + /// 判断是首次打开游戏 + /// + /// + public bool IsFirstLaunch() + { + return !PlayerPrefs.HasKey("FirstLaunch"); + } + + /// + /// 设置首次启动游戏 + /// + private void SetFirstLaunch() + { + PlayerPrefs.SetInt("FirstLaunch", 1); + } + + /// + /// 首次启动游戏拷贝配置文件到PersistentData目录下 + /// + private void FirstLaunchCopyConfig() + { + SetFirstLaunch(); + FileNetworkManager.GetInstance.CopyStreamingAssetsToPersistentDataPath((result) => + { + var isSuccess = false; + if (result) + { + var names = FileNetworkManager.GetInstance.GetFileNamesFromPersistentDataPath(FileNetworkManager.FolderName); + if (names.Length > 0) + { + PlayerPrefs.SetString(ConfigFileNameKey, names[0]);//项目当前文件中的配置版本 + isSuccess = true; + } + } + else + { + Debug.LogError("拷贝文件失败"); + } + + if (isSuccess) + { + OnRequestGetConfig(); + } + else + { + _initConfigErrorCount++; + } + }); + } + + /// + /// 下载配置文件 + /// + private void DownloadConfig() + { + var cdnConfigFileName = _loginModel.setting; + FileNetworkManager.GetInstance.ReadData($"{NetworkKit.CDNUrl}config/{cdnConfigFileName}", (result) => + { + if (!string.IsNullOrEmpty(result)) + { + PlayerPrefs.SetString(ConfigFileNameKey, cdnConfigFileName);//更新当前配置文件文件名 + FileNetworkManager.GetInstance.WriteToPersistentData(FileNetworkManager.GetInstance.GetConfigFOlderPath(), cdnConfigFileName, result); + ReloadConfig(result); + SaveingPotHelper.ResetHistory(); + } + else + { + _initConfigErrorCount++; + Debug.LogError("下载配置文件失败"); + ReadLocalConfig(); + } + + }); + } + + /// + /// 读取本地配置文件 + /// + private void ReadLocalConfig() + { + string savedCfgName = PlayerPrefs.GetString(ConfigFileNameKey); + var path = Path.Combine(FileNetworkManager.GetInstance.GetConfigFOlderPath(), savedCfgName); + FileNetworkManager.GetInstance.ReadData(path, (result) => + { + if (!string.IsNullOrEmpty(result)) + { + ReloadConfig(result); + } + else + { + _initConfigErrorCount++; + Debug.LogError("读取本地数据异常"); + // DownloadConfig(); + + //读取本地配置文件失败,重新从默认位置拷贝原始配置文件到配置文件夹下 + FirstLaunchCopyConfig(); + } + }); + } + + /// + /// 重新加载配置 + /// + /// + private void ReloadConfig(string json) + { + var reqData = new RespLoginFunnelData + { + type = "loadFinish", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData);//加载完成打点 + + ParseConfig(json); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close); + AppDispatcher.Instance.Dispatch(AppMsg.LoginInit); + + CtrlDispatcher.Instance.Dispatch(CtrlMsg.Game_StartBefore); + } + + /// + /// 检查是否有新的配置 + /// + /// + private bool HasNewConfig() + { + var cdnConfigFileName = _loginModel.setting; + + if (!PlayerPrefs.HasKey(ConfigFileNameKey)) return true; + + string savedCfgName = PlayerPrefs.GetString(ConfigFileNameKey); + bool needDownloadConfigFile = false; + + if (!string.IsNullOrEmpty(cdnConfigFileName)) + { + //如果本地Player Prefs里没有保存配置文件名 + if (string.IsNullOrEmpty(savedCfgName)) + { + needDownloadConfigFile = true; + } + else + { + //与CDN上的对比名称 + if (!savedCfgName.Equals(cdnConfigFileName)) + { + needDownloadConfigFile = true; + } + } + } + + return needDownloadConfigFile; + } + + private void ParseConfig(string json) + { + if (json == null) + { + return; + } + if (!json.StartsWith("{")) + { + json = Base64Kit.Decode(json, NetworkManager.packName); + } + var dictionary = SerializeUtil.ToObject>(json); + ParseGameConfig(dictionary); + // ParseQuestionConfig(dictionary); + + // GameDispatcher.Instance.Dispatch(GameMsg.UpdateHotFixProgress, 100); + } + + #region 游戏配置 + + private void ParseGameConfig(IReadOnlyDictionary dictionary) + { + LoadConfig(dictionary, "Common"); + LoadConfigList(dictionary, "turntable"); + LoadConfigList(dictionary, "langDisplay"); + LoadConfigList(dictionary, "rewardNum"); + LoadConfigList(dictionary, "achieve"); + LoadConfigList(dictionary, "Durationtasks"); + LoadConfigList(dictionary, "Paidcoins"); + LoadConfigList(dictionary, "PassingTasks"); + LoadConfigList(dictionary, "Passportrewards"); + LoadConfigList(dictionary, "SmallrewardNum"); + LoadConfigList(dictionary, "LargerewardNum"); + LoadConfigList(dictionary, "paymentType"); + LoadConfigList(dictionary, "makeup"); + LoadConfigList(dictionary, "makeup_2"); + LoadConfigList(dictionary, "Paidgift"); + // LoadConfig(dictionary, "GameUrlsConst"); + // LoadConfigList(dictionary, "GameUrls"); + LoadConfigList(dictionary, "LevelData"); + LoadConfigList(dictionary, "LevelData_2"); + LoadConfigList(dictionary, "LevelData_3"); + LoadConfigList(dictionary, "PrizeWheelData"); + LoadConfigList(dictionary, "exBrPool"); + LoadConfigList(dictionary, "exBrPool"); + LoadConfigList(dictionary, "Multigift"); + + if (dictionary.TryGetValue("SignDailyReward", out var signDailyReward)) + { + var signDailyRewardModel = new SignDailyRewardModel(); + + signDailyRewardModel.dataList = SerializeUtil.ToObject>(signDailyReward.ToString()); + + ConfigData[typeof(SignDailyRewardModel)] = signDailyRewardModel; + } + + if (GetConfigFormName(dictionary, "exBrPool", out var exBrPool)) + { + var exBrPoolModel = new exBrPoolModel + { dataList = SerializeUtil.ToObject>(exBrPool) }; + ConfigData[typeof(exBrPoolModel)] = exBrPoolModel; + GetConfig().config_name_list = GetConfig().dataList[0].user_name.Split(",").ToList(); + GetConfig().config_money_list = GetConfig().dataList[0].amount.Split(",").ToList(); + } + if (GetConfigFormName(dictionary, "exBrPool_2", out var exBrPool_2)) + { + var exBrPoolModel_2 = new exBrPoolModel_2 + { dataList = SerializeUtil.ToObject>(exBrPool_2) }; + ConfigData[typeof(exBrPoolModel_2)] = exBrPoolModel_2; + GetConfig().config_name_list = GetConfig().dataList[0].user_name.Split(",").ToList(); + GetConfig().config_money_list = GetConfig().dataList[0].amount.Split(",").ToList(); + } + if (dictionary.TryGetValue("GameUrls", out var GameUrls)) + { + light_weblist.Clear(); + dark_weblist.Clear(); + web_through_str = ""; + List alllist = new List(); + alllist = SerializeUtil.ToObject>(GameUrls.ToString()); + List type_list = new List(); + for (int i = 0; i < alllist.Count; i++) + { + + if (alllist[i].webType == 2) + { + if (GameHelper.IsGiftSwitch() && (alllist[i].isMagic == 1)) light_weblist.Add(alllist[i]); + else if (!GameHelper.IsGiftSwitch() && (alllist[i].isMagic == 0)) light_weblist.Add(alllist[i]); + } + else + { + dark_weblist.Add(alllist[i]); + if (!type_list.Contains(alllist[i].wvType)) + { + web_through_str += alllist[i].wvthrough; + web_through_str += "|"; + type_list.Add(alllist[i].wvType); + } + } + + } + web_through_str.Remove(web_through_str.Length - 1); + var gameUrlsModel = new GameUrlsModel + { + dataList = light_weblist + }; + ConfigData[typeof(GameUrlsModel)] = gameUrlsModel; + } + } + + private void LoadConfig(IReadOnlyDictionary dictionary, string key) + { + if (ParseConfig(dictionary, key, out T data)) + { + ConfigData[typeof(T)] = data; + } + } + + private void LoadConfigList(IReadOnlyDictionary dictionary, string key) + where T : IDataList, new() + { + if (ParseConfig(dictionary, key, out List dataList)) + { + ConfigData[typeof(T)] = new T { dataList = dataList }; + } + } + + private bool ParseConfig(IReadOnlyDictionary dictionary, string key, out T obj) + { + obj = default; + if (!GetConfigFormName(dictionary, key, out var config)) + { + Debug.LogWarning($"Excel Not find Sheet: {key}"); + return false; + } + + try + { + var tempObj = SerializeUtil.ToObject(config); + if (tempObj != null) + { +#if UNITY_EDITOR + CheckMissFields(key, tempObj, config); +#endif + obj = tempObj; + return true; + } + } + catch (Exception ex) + { + // 在此处添加异常处理逻辑,例如日志记录 + Debug.LogError("Error deserializing config data for type " + typeof(T).Name + ": " + ex.Message); + } + + return false; + } + + private void CheckMissFields(string key, T tempObj, string configValue) + { + var missingFields = new List(); + + if (tempObj is IEnumerable tempArray) + { + missingFields = CheckMissingFieldsInArray(tempArray.FirstOrDefault()?.GetType(), configValue); + } + else + { + missingFields = CheckMissingFields(tempObj.GetType(), configValue); + } + + if (missingFields.Count > 0) + { + Debug.LogWarning($"Excel Sheet: {key} Missing fields in JSON: " + string.Join(", ", missingFields.Distinct())); + } + } + + public static List CheckMissingFieldsInArray(Type objType, string jsonString) + { + var missingFields = new List(); + var jsonArray = JArray.Parse(jsonString); + + foreach (var item in jsonArray) + { + missingFields.AddRange(CheckMissingFields(objType, item.ToString())); + } + + return missingFields; + } + + public static List CheckMissingFields(Type objType, string jsonString) + { + var missingFields = new List(); + + try + { + var jsonObject = SerializeUtil.ToObject>(jsonString); + var fields = objType.GetFields(BindingFlags.Public | BindingFlags.Instance); + + foreach (var field in fields) + { + if (!jsonObject.ContainsKey(field.Name)) + { + missingFields.Add(field.Name); + } + } + } + catch (Exception ex) + { + Debug.Log("Error checking missing fields for type " + objType.Name + ": " + ex.Message); + } + + return missingFields; + } + + private bool GetConfigFormName(IReadOnlyDictionary dictionary, string formName, out string config) + { + config = null; + var lastName = formName + _loginModel.ConfigType; + var isHaveConfig = dictionary.ContainsKey(lastName); + if (!isHaveConfig) + { + if (_loginModel.ConfigType == "") + { + return false; + } + lastName = formName; + } + + Debug.Log($"lastName============= {lastName}"); + var isHaveGameUrlsConst = dictionary.TryGetValue(lastName, out var gameUrlsConst); + config = isHaveGameUrlsConst ? gameUrlsConst.ToString() : null; + return isHaveGameUrlsConst; + } + #endregion + + public static T GetConfig() + { + return ConfigData.TryGetValue(typeof(T), out var value) ? (T)value : default; + } + + public override void Dispose() + { + base.Dispose(); + RemoveListener(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs.meta new file mode 100644 index 0000000..5829a89 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/ConfigSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3a3bd721f95842948573aea8599cd364 +timeCreated: 1692603665 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs new file mode 100644 index 0000000..e96a356 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs @@ -0,0 +1,155 @@ +using System.Collections; + +namespace ScrewsMaster +{ + using UnityEngine; + + public class LoginSystem : BaseSystem + { + private bool _loginSuccess = false; + private LoginModel _loginModel; + public LoginSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + + public sealed override void Init() + { + base.Init(); + InitData(); + AddListener(); + } + + private void InitData() + { + } + + private void AddListener() + { + NetworkDispatcher.Instance.AddListener(NetworkMsg.Login, RequestLogin); + } + + private void RemoveListener() + { + NetworkDispatcher.Instance.RemoveListener(NetworkMsg.Login, RequestLogin); + } + + private void RequestLogin(object obj = null) + { + var requestLoginData = new RequestLoginData + { +#if !UNITY_EDITOR + device_id = SystemInfo.deviceUniqueIdentifier, +#else + device_id = "test004013", +#endif + // pack_name = Application.identifier, + app_version = Application.version, + pack_name = NetworkManager.packName, + channel = SuperApplication.Instance.attribution, + sim = NetworkManager.haveSimCard + }; + + var reqData = new RespLoginFunnelData + { + type = "loginSend", + payload = "" + }; + NetworkKit.PostFunnelLogin(reqData); + + CrazyAsyKit.StartCoroutine(LoginCoroutine(requestLoginData)); + } + + private IEnumerator LoginCoroutine(RequestLoginData reqData) + { + var count = 0; + while (count < 5) + { + + yield return new WaitForSeconds(count == 0 ? 0 : 5f); + yield return LoginRequest(reqData); + + if (_loginSuccess) + { + OnLoginSuccess(_loginModel); + yield break; + } + + if (count == 4) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.TipsUI_Open); + } + + Debug.LogError($"登录失败重试 {count}"); + + count++; + } + } + + private IEnumerator LoginRequest(RequestLoginData reqData) + { + yield return NetworkKit.Post("login", reqData, (isSuccess, loginData) => + { + _loginSuccess = isSuccess; + _loginModel = loginData; + TrackLoginActivity(_loginSuccess); + }); + } + + private void OnLoginSuccess(LoginModel loginData) + { + var loginModel = GameHelper.GetLoginModel(); + loginModel.cdn_url = loginData.cdn_url; + loginModel.setting = loginData.setting; + loginModel.play_data = loginData.play_data; + loginModel.token = loginData.token; + loginModel.uid = loginData.uid; + loginModel.country = loginData.country; + loginModel.expires_at = loginData.expires_at; + loginModel.is_magic = loginData.is_magic; + loginModel.invite_code = loginData.invite_code; + loginModel.invite_url = loginData.invite_url; + loginModel.last_login_time = loginData.last_login_time; + loginModel.login_time = loginData.login_time; + loginModel.reg_time = loginData.reg_time; + loginModel.new_player = loginData.new_player; + loginModel.ConfigType = loginData.is_magic ? "_" : "_A"; + loginModel.play_data_ver = loginData.play_data_ver; + loginModel.debug_log = loginData.debug_log; + loginModel.enwp = loginData.enwp; + loginModel.preferences = new Preferences(); + NetworkKit.CDNUrl = $"{loginData.cdn_url}/"; + NetworkKit.userId = loginData.uid; + NetworkKit.SetCacheToken(loginData.token); + RequestHeart(); + TimerHelper.UnscaleGeneral.AddLoopTimer(60, (timer) => { RequestHeart(); }); + NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetPlayData); + MaxADKit.Init(); + } + + private void TrackLoginActivity(bool isSuccess) + { + var reqData = new RespLoginFunnelData + { + type = "loginRecv", + payload = isSuccess ? "success" : "fail" + }; + NetworkKit.PostFunnelLogin(reqData); + } + + private void RequestHeart() + { + NetworkKit.PostWithHeader("user/health"); + } + + public override void Dispose() + { + base.Dispose(); + RemoveListener(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs.meta new file mode 100644 index 0000000..471860b --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/LoginSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0e448e373b1b484b8918ec80a7f28448 +timeCreated: 1692267393 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs b/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs new file mode 100644 index 0000000..45c1185 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs @@ -0,0 +1,84 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace ScrewsMaster +{ + public class PlayDataSystem : BaseSystem + { + public PlayDataSystem(bool isAutoInit = true) + { + if (isAutoInit) + { + Init(); + } + } + + public sealed override void Init() + { + base.Init(); + + AddListener(); + } + + private void AddListener() + { + NetworkDispatcher.Instance.AddListener(NetworkMsg.GetPlayData, OnRequestPlayData); + NetworkDispatcher.Instance.AddListener(NetworkMsg.SavePlayData, OnRequestSavePlayData); + } + + private void RemoveListener() + { + NetworkDispatcher.Instance.RemoveListener(NetworkMsg.GetPlayData, OnRequestPlayData); + NetworkDispatcher.Instance.RemoveListener(NetworkMsg.SavePlayData, OnRequestSavePlayData); + } + + private void OnRequestPlayData(object args) + { + NetworkKit.PostWithHeader("user/userData", (isSuccess, obj) => + { + var loginModel = GameHelper.GetLoginModel(); + loginModel.preferences = obj; + + PreferencesMgr.Instance.InitPreferences(); + NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetConfig); + }); + } + + private void OnRequestSavePlayData(object obj) + { + if (obj != null) + { + var msg = obj as Dictionary; + + if (msg == null) + { + return; + } + + var version = 1L; + if (msg.TryGetValue("data_ver", out var ver)) + { + if (version != default) + { + version = (long)ver; + } + } + + var data = SerializeUtil.ToJson>(msg); + + var requestData = new RequestSavePlayData + { + version = version, + data = data + }; + NetworkKit.PostWithHeader("user/updateData", requestData); + } + } + + public override void Dispose() + { + base.Dispose(); + RemoveListener(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs.meta b/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs.meta new file mode 100644 index 0000000..6653764 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/System/Network/PlayDataSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7b2141f8f0f64581b0f291d0ca27ece2 +timeCreated: 1692343794 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit.meta new file mode 100644 index 0000000..8a010e7 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9f5abaabbebd64447aa4f862c76ba39c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs new file mode 100644 index 0000000..4cdb30c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs @@ -0,0 +1,23 @@ +using ScrewsMaster; +using UnityEngine; + +public sealed class AnimationCurveData : ScriptableObject +{ + private static AnimationCurveData instance; + + public static AnimationCurveData Instance + { + get + { + if (instance == null) + { + instance = LoadKit.Instance.LoadAsset("Data.ScriptableObjectData", + "AnimationCurveData"); + } + + return instance; + } + } + + public AnimationCurve LuckySpinAniCurve; +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs.meta new file mode 100644 index 0000000..05ea308 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/AnimationCurveData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b0a921ff368c47588249df420aa52091 +timeCreated: 1704964086 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs new file mode 100644 index 0000000..c6050e3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs @@ -0,0 +1,32 @@ +using System; +using System.Text; + +namespace FutureCore +{ + public static class Base64EncodeUtil + { + public static string Base64Encode(string source) + { + return Base64Encode(Encoding.UTF8, source); + } + + public static string Base64Decode(string result) + { + return Base64Decode(Encoding.UTF8, result); + } + + public static string Base64Encode(Encoding encoding, string source) + { + byte[] bytes = encoding.GetBytes(source); + string encode = Convert.ToBase64String(bytes); + return encode; + } + + public static string Base64Decode(Encoding encoding, string result) + { + byte[] bytes = Convert.FromBase64String(result); + string decode = encoding.GetString(bytes); + return decode; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs.meta new file mode 100644 index 0000000..b91d2da --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/Base64EncodeUtil.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7cb6f0cfcd844347bfe34d48a1f77555 +timeCreated: 1693215248 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs new file mode 100644 index 0000000..7f8a059 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs @@ -0,0 +1,31 @@ +using System; +using DG.Tweening; +using FairyGUI; +using ScrewsMaster; + +public static class CommonExpand +{ + public static GTweener FadeIn(this GObject obj, float duration = 0.3f, float delay = 0) + { + return CommonHelper.FadeIn(obj, duration, delay); + } + + public static GTweener FadeOut(this GObject obj, float duration = 0.3f, float delay = 0) + { + return CommonHelper.FadeOut(obj, duration, delay); + } + + public static void SetClick(this GObject button, Action action, bool isNetworkCheck = false, + bool isQuickClickCheck = true) + { + CommonHelper.InitGButton(button, action, isNetworkCheck, isQuickClickCheck); + } + + public static void SafeKill(this Tween tween) + { + if (tween != null && tween.IsActive()) + { + tween.Kill(); + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs.meta new file mode 100644 index 0000000..f3e3347 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CommonExpand.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 774c7c1119b44f86819883ab6e9240ec +timeCreated: 1681803724 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs new file mode 100644 index 0000000..56137cd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using DG.Tweening; +using FairyGUI; +using UnityEngine.UI; + +namespace ScrewsMaster +{ + public enum CountDownType + { + Second, + Minute, + Hour, + Day + } + + public class CountDownKit + { + private int countDownTime; + private int leftTime = 0; + private GTextField textGComponent; + private GProgressBar barGComponent; + private Text textComponent; + private CountDownType countDownType = CountDownType.Second; + private Dictionary onTriggerEventDict = new Dictionary(); + private Tween timer; + private Action onCompletedEvent; + private long endTime; + private bool isDependenceServerTime = true; + + public CountDownKit SetTime(int second) + { + countDownTime = second; + leftTime = countDownTime; + return this; + } + + public CountDownKit SetCountDownType(CountDownType countDownType) + { + this.countDownType = countDownType; + return this; + } + + public CountDownKit SetText(GTextField gText) + { + textComponent = null; + textGComponent = gText; + return this; + } + + public CountDownKit SetBar(GProgressBar gProgressBar) + { + barGComponent = null; + barGComponent = gProgressBar; + return this; + } + + public int interval = 1; + + public void Start() + { + endTime = (int)(DateTimeManager.Instance.GetServerCurrTimestamp() / 1000) + leftTime; + UpdateView(); + timer = DOVirtual.DelayedCall(interval, () => + { + leftTime -= interval; + if (isDependenceServerTime) + { + var current = DateTimeManager.Instance.GetServerCurrTimestamp() / 1000; + if (endTime <= current) + { + leftTime = 0; + } + } + + UpdateView(); + if (leftTime <= 0) + { + Stop(); + OnCompleted(); + } + else + { + OnTrigger(); + } + }, true).SetLoops(-1); + } + + private void UpdateView() + { + UpdateText(); + UpdateBar(); + } + + public void Pause() + { + if (timer != null) + { + timer.Pause(); + } + } + + public void Resume() + { + if (timer != null) + { + timer.Play(); + } + } + + public void Stop() + { + if (timer != null && timer.IsActive()) + { + timer?.Kill(); + } + } + + public void OnDestroy() + { + Stop(); + leftTime = 0; + + textGComponent = null; + + textComponent = null; + onTriggerEventDict = null; + onCompletedEvent = null; + } + + public void ConsumeTime(int consumeTime) + { + leftTime -= consumeTime; + UpdateView(); + if (leftTime <= 0) + { + Stop(); + OnCompleted(); + } + else + { + OnTrigger(); + } + } + + private void OnTrigger() + { + if (onTriggerEventDict.ContainsKey(leftTime)) + { + onTriggerEventDict[leftTime]?.Invoke(); + } + } + + public void ClearTriggerEvent() + { + onTriggerEventDict.Clear(); + } + + public CountDownKit SetCompletedEvent(Action onCompleted) + { + onCompletedEvent = onCompleted; + return this; + } + + private void OnCompleted() + { + onCompletedEvent?.Invoke(); + } + + private void UpdateText() + { + if (textGComponent != null) + { + textGComponent.text = CommonHelper.TimeFormat(leftTime, countDownType); + } + + if (textComponent != null) + { + textComponent.text = CommonHelper.TimeFormat(leftTime, countDownType); + } + } + + private void UpdateBar() + { + if (barGComponent != null) + { + if (barGComponent.max == 0) + { + barGComponent.max = countDownTime; + } + + barGComponent.TweenValue(leftTime, 1); + } + } + + public int GetLeftTime() + { + return leftTime; + } + + public CountDownKit SetServerTimeDependence(bool _isDependenceServerTime) + { + isDependenceServerTime = _isDependenceServerTime; + return this; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs.meta new file mode 100644 index 0000000..04f3b40 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CountDownKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 34ed4a143324499ab1864f3c64019e16 +timeCreated: 1681804392 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs new file mode 100644 index 0000000..4bc33d0 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public static class CrazyZooConstant + { + public const string croas = "Assets/CrazyZooAssets/"; + public const string setbun = ".assetbundle"; + public static readonly string tbund = $"{Application.dataPath}/../AssetBundle/{undles}"; + public static readonly string fgklpk = "|"; + public const string undles = "AssetBundles"; + public const string nifest = ".manifest"; + public static readonly string lesest = $"{undles}{nifest}"; + public const string zyzootx = "CrazyZooFile.txt"; + public const string nifldg = "[ CrazyZoo ]"; + public const string admsie = "4s2f6ac15sa6ds45"; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs.meta new file mode 100644 index 0000000..890c036 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooConstant.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 73ce1d7d9d7bd5245878994917b71208 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs new file mode 100644 index 0000000..2282b47 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs @@ -0,0 +1,205 @@ +using UnityEngine.Events; + +namespace ScrewsMaster +{ + using System; + using UnityEngine; + using System.Collections.Generic; + + public delegate void onLoaded(AssetBundle param); + + public class CrazyZooInfo + { + public string assetBundleName; + + public List parentABNameList = new(); + + public long assetBundleSize; + + + public AssetBundle assetBundle { get; internal set; } + + public CrazyZooState assetBundleState; + + public onLoaded ONLoaded; + + public long waitUnloadCurrentTime; + + public Action> unloadAction; + + public Action unloadCompletedAction; + + public int waitUnloadTime; + + + public static List StatisticsCacheAssetList = new List(); + + + private static bool isStatisticsCacheAssetList = false; + + + public int ReferencedCount { get; set; } + + + public float LastReferencedTimestamp { get; set; } + + public CrazyZooInfo(string assetBundleName, UnityAction onCompletedLoaded) + { + this.assetBundleName = assetBundleName; + assetBundleState = CrazyZooState.STATE_LOADING; + Referenced(assetBundleName); + LastReferencedTimestamp = Time.realtimeSinceStartup; + if (onCompletedLoaded != null) + { + ONLoaded += a => onCompletedLoaded(a); + } + } + + #region 引用关系 + + public int GetReferenced() + { + return ReferencedCount; + } + + + public void Referenced(string parentAbName) + { + parentAbName = parentAbName.ToLower(); + if (!parentABNameList.Contains(parentAbName)) + { + ReferencedCount++; + parentABNameList.Add(parentAbName); +#if UNITY_EDITOR + +#endif + } + } + + public void UnReferenced(string parentAbName) + { + if (parentABNameList.Contains(parentAbName)) + { + ReferencedCount--; + parentABNameList.Remove(parentAbName); +#if UNITY_EDITOR + +#endif + } + } + + public void CleanReferenced() + { + ReferencedCount = 0; + } + + #endregion + + public void callRes(string parentAbName, UnityAction action) + { + switch (assetBundleState) + { + case CrazyZooState.STATE_NONE: + break; + case CrazyZooState.STATE_LOADING: + ONLoaded += a => { action(a); }; + break; + case CrazyZooState.STATE_LOADED: + Referenced(parentAbName); + action(this.assetBundle); + break; + } + } + + public void onLoaded(string parentAbName, AssetBundle assetBundle) + { + Referenced(parentAbName); + this.assetBundle = assetBundle; + this.assetBundleState = CrazyZooState.STATE_LOADED; + ONLoaded(assetBundle); + ONLoaded = null; + OnAddtStatisticsCacheAssetList(assetBundle.name); + } + + public void Unload(bool isThorough) + { + CleanReferenced(); + if (assetBundle != null) + assetBundle.Unload(isThorough); + assetBundle = null; + } + + + private void OnAddtStatisticsCacheAssetList(string assetBundleName) + { + if (!isStatisticsCacheAssetList) return; + if (!StatisticsCacheAssetList.Contains(assetBundleName)) + { + StatisticsCacheAssetList.Add(assetBundleName); + } + } + + + public static void OnStartStatisticsCacheAssetList() + { + isStatisticsCacheAssetList = true; + StatisticsCacheAssetList.Clear(); + } + + + public static string[] OnStopStatisticsCacheAssetList() + { + isStatisticsCacheAssetList = false; + string[] tempList = StatisticsCacheAssetList.GetRange(0, StatisticsCacheAssetList.Count).ToArray(); + StatisticsCacheAssetList.Clear(); + return tempList; + } + + + public void UpdateWaitUnloadCurrentTime() + { + waitUnloadCurrentTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(); + } + + + public long GetWaitUpdateTimeTD() + { + var tempTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds(); + return tempTime - waitUnloadCurrentTime; + } + + public void SetUnloadAction(Action> action, Action onCompletedAction) + { + this.unloadAction = action; + this.unloadCompletedAction = onCompletedAction; + } + + public void InvokeUnloadAction() + { + unloadAction?.Invoke(unloadCompletedAction); + } + + public void SetWaitUnloadTime(int time) + { + waitUnloadTime = time; + } + + public int GetWaitUnloadTime() + { + return waitUnloadTime; + } + + public void SetAssetBundleSize(long size) + { + if (size > 0) + { + assetBundleSize = size; + } + } + + public long GetSize() + { + return assetBundleSize; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs.meta new file mode 100644 index 0000000..7a1bb05 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f8e1bf1569620a45ba3a117072e9b57 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs new file mode 100644 index 0000000..6967db3 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs @@ -0,0 +1,853 @@ +namespace ScrewsMaster +{ + using System; + using System.IO; + using UnityEngine; + using System.Linq; + using System.Text; + using UnityEngine.Events; + using System.Collections; + using System.Collections.Generic; + using Object = UnityEngine.Object; + using System.Security.Cryptography; + + public class CrazyZooKit : Singleton, ILoadAsset + { + private const bool IsMD5Encrypt = false; + + + private string _assetBundleRootPath = CrazyZooFileKit.GetFilePath(); + + + private static readonly Dictionary _cacheAssetBundleInfoDict = + new Dictionary(); + + + private static readonly Dictionary _cacheDependencyDict = new Dictionary(); + + private static readonly List _waitUnloadList = new List(); + + private static AssetBundleManifest _manifest; + + private static readonly Dictionary decryptAssetBundleDict = new Dictionary(); + + + private const int UnloadWaitTime = 30; + + #region 加载AssetBundle的基础方法 + + public IEnumerator LoadABFromFileAsync(string assetBundlePath, string bundlePassword, + UnityAction onCompleted) + { + yield return LoadDecryptAssetBundle(assetBundlePath, bundlePassword, onCompleted); + } + + private IEnumerator LoadDecryptAssetBundle(string assetBundlePath, string bundlePassword, + UnityAction onCompleted) + { + string decryptPath; + if (decryptAssetBundleDict.TryGetValue(assetBundlePath, out var outPath) && File.Exists(outPath)) + { + decryptPath = outPath; + } + else + { + var cachePath1 = Path.Combine(UnityEngine.Application.persistentDataPath, "Jarvis"); + if (!Directory.Exists(cachePath1)) + { + Directory.CreateDirectory(cachePath1); + } + + var cachePath = Path.Combine(cachePath1, $"decryptedBundle{Guid.NewGuid():N}"); + + + using (Stream stream1 = File.OpenWrite(cachePath)) + { + var decryptedData = AESForFileKit.DecryptToBytes(assetBundlePath, bundlePassword, out var dataSize); + yield return stream1.WriteAsync(decryptedData, 0, dataSize); + } + + decryptPath = cachePath; + decryptAssetBundleDict.TryAdd(assetBundlePath, decryptPath); + } + + var request = AssetBundle.LoadFromFileAsync(decryptPath); + yield return request; + onCompleted?.Invoke(request.assetBundle); + } + + private AssetBundle LoadDecryptAssetBundleSync(string assetBundlePath, string bundlePassword) + { + string decryptPath; + if (decryptAssetBundleDict.TryGetValue(assetBundlePath, out var outPath) && File.Exists(outPath)) + { + decryptPath = outPath; + } + else + { + var decryptedData = AESForFileKit.DecryptToBytes(assetBundlePath, bundlePassword, out var dataSize); + var cachePath1 = Path.Combine(UnityEngine.Application.persistentDataPath, "Jarvis"); + if (!Directory.Exists(cachePath1)) + { + Directory.CreateDirectory(cachePath1); + } + + var cachePath = Path.Combine(cachePath1, $"decryptedBundle{Guid.NewGuid():N}"); + while (File.Exists(cachePath)) + { + File.Delete(cachePath); + cachePath = Path.Combine(cachePath1, $"decryptedBundle{Guid.NewGuid():N}"); + } + + using (Stream stream = File.OpenWrite(cachePath)) + { + stream.Write(decryptedData, 0, dataSize); + stream.Close(); + } + + decryptPath = cachePath; + decryptAssetBundleDict.TryAdd(assetBundlePath, decryptPath); + } + + var assetBundle = AssetBundle.LoadFromFile(decryptPath); + return assetBundle; + } + + private IEnumerator LoadAssetFromAssetBundle(AssetBundle assetBundle, string assetName, + UnityAction onLoadCompleted) where T : Object + { + T resultAsset = null; + + if (typeof(T) == typeof(Sprite)) + { + var texture2D = assetBundle.LoadAsset(assetName); + if (texture2D != null) + { + var sprite = Sprite.Create(texture2D, + new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f)); + + resultAsset = sprite as T; + } + else + { + string[] assetNameArray = assetName.Split('.'); + if (assetNameArray.Length > 1) + { + var resultAsset1 = assetBundle.LoadAssetWithSubAssets(assetNameArray[0]); + resultAsset = Array.Find(resultAsset1, item => item.name == assetNameArray[1]); + } + else + { + } + } + } + else + { + var assetLoadRequest = assetBundle.LoadAssetAsync(assetName); + yield return assetLoadRequest; + var gameObject = assetLoadRequest.asset; + if (gameObject == null) + { + var subAssetLoadRequest = assetBundle.LoadAssetWithSubAssetsAsync(assetName); + yield return subAssetLoadRequest; + resultAsset = subAssetLoadRequest.asset as T; + } + else + { + resultAsset = gameObject as T; + } + } + + onLoadCompleted?.Invoke(resultAsset); + } + + private void LoadAssetInternal(string assetBundleName, UnityAction onCompleted) + { + var assetBundlePath = GenerateAssetBundlePath(assetBundleName); + + GetAssetBundle(assetBundlePath, assetBundleName, onCompleted); + } + + public AssetBundle GetAssetBundle(string assetBundlePath, string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + CrazyAsyKit.StopAction(assetBundleName + "Unload"); + UnWaitUnload(assetBundleName); + if (IsCacheAssetBundle(assetBundleName)) + { + CacheDependency(assetBundleName, new[] { assetBundleName }); + + var CrazyZooInfo = GetCacheAssetBundle(assetBundleName); + return CrazyZooInfo?.assetBundle; + } + else + { + var CrazyZooInfo = new CrazyZooInfo(assetBundleName, null); + CacheAssetBundle(assetBundleName, CrazyZooInfo); + var isFileLoadType = File.Exists(assetBundlePath); + if (isFileLoadType) + { + GetAssetBundleDependency(assetBundleName); + var assetBundle = + LoadDecryptAssetBundleSync(assetBundlePath, CrazyZooConstant.admsie); + CrazyZooInfo.assetBundle = assetBundle; + return assetBundle; + } + } + + return null; + } + + public void GetAssetBundle(string assetBundlePath, string assetBundleName, UnityAction onCompleted) + { + assetBundleName = assetBundleName.ToLower(); + CrazyAsyKit.StopAction(assetBundleName + "Unload"); + UnWaitUnload(assetBundleName); + if (IsCacheAssetBundle(assetBundleName)) + { + CacheDependency(assetBundleName, new[] { assetBundleName }); + + var CrazyZooInfo = GetCacheAssetBundle(assetBundleName); + CrazyZooInfo?.callRes(assetBundleName, onCompleted); + } + else + { + var CrazyZooInfo = new CrazyZooInfo(assetBundleName, onCompleted); + CacheAssetBundle(assetBundleName, CrazyZooInfo); + var isFileLoadType = File.Exists(assetBundlePath); + CrazyAsyKit.StartCoroutine(GetAssetBundleDependency(assetBundleName, delegate + { + if (isFileLoadType) + { + CrazyAsyKit.StartCoroutine(LoadABFromFileAsync(assetBundlePath, + CrazyZooConstant.admsie, bundle => + { + if (bundle == null) + { + Debug.LogError("加载AssetBundle 失败:" + assetBundleName); + UnCacheAssetBundle(assetBundleName); + } + else + { + CrazyZooInfo abInfo = GetCacheAssetBundle(assetBundleName); +#if UNITY_EDITOR + FileInfo file = new FileInfo(assetBundlePath); + + abInfo.SetAssetBundleSize(file.Length); +#endif + abInfo.onLoaded(assetBundleName, bundle); + } + })); + } + else + { + CrazyAsyKit.StartCoroutine(LoadABFromFileAsync(assetBundlePath, + CrazyZooConstant.admsie, delegate (AssetBundle bundle) + { + if (bundle == null) + { + Debug.LogError("加载AssetBundle 失败:" + assetBundleName); + UnCacheAssetBundle(assetBundleName); + } + else + { + var abInfoV = GetCacheAssetBundle(assetBundleName); + var file = new FileInfo(assetBundlePath); + abInfoV.SetAssetBundleSize(file.Length); + abInfoV.onLoaded(assetBundleName, bundle); + } + })); + } + })); + } + } + + #region AssetBundle 包的依赖相关 + + private IEnumerator GetAssetBundleDependency(string assetBundleName, Action action) + { + assetBundleName = assetBundleName.ToLower(); + + var allDependencies = new List() { assetBundleName }; + allDependencies.AddRange(GetABDependency(assetBundleName)); + var index = 0; + CacheDependency(assetBundleName, allDependencies.ToArray()); + var allDepends = allDependencies.Where(dependencyAbName => dependencyAbName != assetBundleName).ToList(); + + foreach (var dependencyAbName in allDepends) + { + yield return LoadDependencyAssetBundle(assetBundleName, dependencyAbName, delegate { index++; }); + } + + while (index != allDepends.Count) + { + yield return new WaitForEndOfFrame(); + } + + action?.Invoke(); + } + + private void GetAssetBundleDependency(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + + var allDependencies = new List() { assetBundleName }; + allDependencies.AddRange(GetABDependency(assetBundleName)); + CacheDependency(assetBundleName, allDependencies.ToArray()); + var allDepends = allDependencies.Where(dependencyAbName => dependencyAbName != assetBundleName).ToList(); + + foreach (var dependencyAbName in allDepends) + { + LoadDependencyAssetBundleSync(assetBundleName, dependencyAbName); + } + } + + private IEnumerator LoadDependencyAssetBundle(string parentAssetBundleName, string assetBundleName, + UnityAction onCompleted) + { + assetBundleName = assetBundleName.ToLower(); + var assetBundlePath = GenerateAssetBundlePath(assetBundleName, IsMD5Encrypt); + + CrazyAsyKit.StopAction(assetBundleName + "Unload"); + UnWaitUnload(assetBundleName); + + if (IsCacheAssetBundle(assetBundleName)) + { + CacheAssetBundle(assetBundleName, null, true); + var CrazyZooInfo = GetCacheAssetBundle(assetBundleName); + CrazyZooInfo?.callRes(parentAssetBundleName, onCompleted); + } + else + { + var CrazyZooInfo = new CrazyZooInfo(assetBundleName, onCompleted); + CacheAssetBundle(assetBundleName, CrazyZooInfo); + if (File.Exists(assetBundlePath)) + { + yield return LoadABFromFileAsync(assetBundlePath, CrazyZooConstant.admsie, + delegate (AssetBundle bundle) + { + if (bundle == null) + { + Debug.LogError("加载AssetBundle 失败:" + assetBundleName); + UnCacheAssetBundle(assetBundleName); + } + else + { + GetCacheAssetBundle(assetBundleName).onLoaded(parentAssetBundleName, bundle); + } + }); + } + else + { + CrazyAsyKit.StartCoroutine(LoadABFromFileAsync(assetBundlePath, + CrazyZooConstant.admsie, delegate (AssetBundle bundle) + { + if (bundle == null) + { + Debug.LogError("加载AssetBundle 失败:" + assetBundleName); + UnCacheAssetBundle(assetBundleName); + } + else + { + GetCacheAssetBundle(assetBundleName).onLoaded(parentAssetBundleName, bundle); + } + })); + } + } + } + + private AssetBundle LoadDependencyAssetBundleSync(string parentAssetBundleName, string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + var assetBundlePath = GenerateAssetBundlePath(assetBundleName, IsMD5Encrypt); + CrazyAsyKit.StopAction(assetBundleName + "Unload"); + UnWaitUnload(assetBundleName); + + if (IsCacheAssetBundle(assetBundleName)) + { + CacheAssetBundle(assetBundleName, null, true); + var assetBundleInfos = GetCacheAssetBundle(assetBundleName); + return assetBundleInfos?.assetBundle; + } + + var CrazyZooInfo = new CrazyZooInfo(assetBundleName, null); + CacheAssetBundle(assetBundleName, CrazyZooInfo); + if (File.Exists(assetBundlePath)) + { + GetAssetBundleDependency(assetBundleName); + var assetBundle = + LoadDecryptAssetBundleSync(assetBundlePath, CrazyZooConstant.admsie); + CrazyZooInfo.assetBundle = assetBundle; + return assetBundle; + } + + return null; + } + + + private string[] GetABDependency(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + return GetManifest().GetDirectDependencies(assetBundleName); + } + + #region 依赖关系相关 + + private bool IsCacheDependency(string assetBundleName) + { + if (_cacheDependencyDict == null || _cacheDependencyDict.Count == 0) return false; + assetBundleName = assetBundleName.ToLower(); + var isDependency = _cacheDependencyDict.ContainsKey(assetBundleName); + + return isDependency; + } + + + private bool IsOtherDependency(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + var isDependency = false; + if (_cacheDependencyDict == null || _cacheDependencyDict.Count == 0) return false; + foreach (var keyValuePair in _cacheDependencyDict) + { + isDependency = keyValuePair.Value.Contains(assetBundleName); + if (isDependency) + { + break; + } + } + + return isDependency; + } + + private void CacheDependency(string assetBundleName, string[] assetBundleNameArray) + { + assetBundleName = assetBundleName.ToLower(); + if (!IsCacheDependency(assetBundleName)) + { + for (int i = 0; i < assetBundleNameArray.Length; i++) + { + assetBundleNameArray[i] = assetBundleNameArray[i].ToLower(); + } + + _cacheDependencyDict.Add(assetBundleName, assetBundleNameArray); + } + } + + + private void UnCacheDependency(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + if (IsCacheDependency(assetBundleName)) + { + _cacheDependencyDict.Remove(assetBundleName); + } + } + + + private string[] GetCacheDependency(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + string[] dependencyList = { }; + if (IsCacheDependency(assetBundleName)) + { + dependencyList = _cacheDependencyDict[assetBundleName]; + } + + return dependencyList; + } + + #endregion + + #endregion + + #region 管理已加载的AssetBundle文件 + + private void CacheAssetBundle(string assetBundleName, CrazyZooInfo assetBundleInfoV, + bool isDependency = false) + { + assetBundleName = assetBundleName.ToLower(); + if (IsCacheAssetBundle(assetBundleName)) + { + if (isDependency) + { + } + else + { + return; + } + } + else + { + _cacheAssetBundleInfoDict.Add(assetBundleName, assetBundleInfoV); + } + } + + + private void UnCacheAssetBundle(string assetBundleName) + { + if (IsCacheAssetBundle(assetBundleName)) + { + _cacheAssetBundleInfoDict.Remove(assetBundleName.ToLower()); + } + else + { + } + } + + + private CrazyZooInfo GetCacheAssetBundle(string assetBundleName) + { + CrazyZooInfo assetBundle = null; + if (IsCacheAssetBundle(assetBundleName)) + { + assetBundle = _cacheAssetBundleInfoDict[assetBundleName.ToLower()]; + } + else + { + } + + return assetBundle; + } + + + private bool IsCacheAssetBundle(string assetBundleName) + { + assetBundleName = assetBundleName.ToLower(); + if (_cacheAssetBundleInfoDict == null) + { + return false; + } + + return _cacheAssetBundleInfoDict.ContainsKey(assetBundleName); + } + + #endregion + + #region 卸载AssetBundle相关 + + #region 卸载AssetBundle相关信息管理 + + private bool WaitUnload(CrazyZooInfo assetBundleInfoV) + { + var isInWait = IsWaitUnload(assetBundleInfoV.assetBundleName); + if (isInWait) return true; + assetBundleInfoV.UpdateWaitUnloadCurrentTime(); + _waitUnloadList.Add(assetBundleInfoV); + return false; + } + + + private bool IsWaitUnloadKey(string assetBundleName) + { + var isWaitUnload = false; + if (_waitUnloadList == null || _waitUnloadList.Count <= 0) return false; + foreach (var bundleInfo in _waitUnloadList) + { + if (bundleInfo == null || !string.IsNullOrEmpty(bundleInfo.assetBundleName)) continue; + if (!bundleInfo.assetBundleName.Equals(assetBundleName)) continue; + isWaitUnload = true; + break; + } + + return isWaitUnload; + } + + + private bool IsWaitUnload(string assetBundleName) + { + var isWaitUnload = false; + if (_waitUnloadList == null || _waitUnloadList.Count == 0) return false; + if (!IsWaitUnloadKey(assetBundleName)) + { + foreach (var waitUnloadAssetBundle in _waitUnloadList) + { + if (waitUnloadAssetBundle == null || + !string.IsNullOrEmpty(waitUnloadAssetBundle.assetBundleName)) continue; + isWaitUnload = GetABDependency(waitUnloadAssetBundle.assetBundleName).Contains(assetBundleName); + if (isWaitUnload) + { + break; + } + } + } + else + { + isWaitUnload = true; + } + + return isWaitUnload; + } + + + private bool UnWaitUnload(string assetBundleName) + { + var isRemove = false; + + foreach (var bundleInfo in _waitUnloadList) + { + if (bundleInfo == null) continue; + if (!bundleInfo.assetBundleName.Equals(assetBundleName)) continue; + isRemove = _waitUnloadList.Remove(bundleInfo); + break; + } + + return isRemove; + } + + #endregion + + + public void UnloadAssetBundle(string assetBundleName, + bool ignoreDependency = false, + int unloadWaitTime = 0, + Action onCompleted = null) + { + if (string.IsNullOrEmpty(assetBundleName)) + { + onCompleted?.Invoke(false); + return; + } + + bool unloadSucceed; + if (IsCacheAssetBundle(assetBundleName)) + { + var abInfo = GetCacheAssetBundle(assetBundleName); + if (abInfo == null) + { + onCompleted?.Invoke(false); + return; + } + + + if (WaitUnload(abInfo) && !ignoreDependency) + { + unloadSucceed = false; + + UnCacheDependency(assetBundleName); + + onCompleted?.Invoke(unloadSucceed); + } + else + { + CrazyAsyKit.StopAction(assetBundleName + "Unload"); + CrazyAsyKit.StartAction(assetBundleName + "Unload", delegate + { + unloadSucceed = IsCacheAssetBundle(assetBundleName) && + UnloadAssetBundleInternal(assetBundleName, ignoreDependency); + + UnWaitUnload(assetBundleName); + +#if UNITY_EDITOR + +#endif + + onCompleted?.Invoke(unloadSucceed); + }, unloadWaitTime); + } + } + else + { + onCompleted?.Invoke(false); + } + } + + + private bool UnloadAssetBundleInternal(string assetBundleName, bool isIgnoreDependency = false, + bool isThorough = false) + { + var CrazyZooInfo = GetCacheAssetBundle(assetBundleName); + if (CrazyZooInfo == null) + { + return false; + } + + + var dependencyArray = GetCacheDependency(assetBundleName); + + + UnCacheDependency(assetBundleName); + + + if (!isIgnoreDependency) + { + if (IsOtherDependency(assetBundleName)) + { + return false; + } + } + + + UnCacheAssetBundle(assetBundleName); + + + CrazyZooInfo.Unload(isThorough); + + + foreach (var dependencyAssetBundleName in dependencyArray) + { + if (dependencyAssetBundleName == assetBundleName) + { + continue; + } + + + if (!IsOtherDependency(dependencyAssetBundleName)) + { + UnloadAssetBundleInternal(dependencyAssetBundleName, false, isThorough); + } + else + { + } + } + + + return true; + } + + #endregion + + #endregion + + #region 封装直接加载资源的方法 + + public T GetAsset(string assetBundleName, string assetName) where T : Object + { + var assetBundlePath = GenerateAssetBundlePath(assetBundleName); + var assetBundle = GetAssetBundle(assetBundlePath, assetBundleName); + + return assetBundle.LoadAsset(assetName); + } + + + public void GetAsset(string assetBundleName, string assetName, UnityAction onCompleted) where T : Object + { + LoadAssetInternal(assetBundleName, delegate (AssetBundle bundle) + { + if (bundle == null) + { + Debug.LogError("加载AssetBundle 失败:" + assetBundleName); + } + else + { + CrazyAsyKit.StartCoroutine(LoadAssetFromAssetBundle(bundle, assetName, onCompleted)); + } + }); + } + + + public void InitManifest(string assetBundleManifestName, UnityAction onCompleted) + { + CrazyAsyKit.StopAction(assetBundleManifestName + "Unload"); + if (UnWaitUnload(assetBundleManifestName)) + { + } + var assetBundles = + AssetBundle.LoadFromFile($"{CrazyZooFileKit.GetFilePath()}{CrazyZooConstant.undles}"); + var manifest = assetBundles.LoadAsset("assetbundlemanifest"); + _manifest = manifest; + onCompleted?.Invoke(manifest != null); + } + + #endregion + + public void RecycleAssetBundle(string assetBundleName, UnityAction onCompleted = null) + { + if (IsCacheAssetBundle(assetBundleName)) + { + var abInfo = GetCacheAssetBundle(assetBundleName); + abInfo.UnReferenced(assetBundleName); + + RecycleAssetBundleDependency(assetBundleName, UnloadWaitTime); + + if (abInfo.GetReferenced() <= 0) + { + UnloadAssetBundle(assetBundleName, false, UnloadWaitTime); + } + } + + onCompleted?.Invoke(); + } + + private void RecycleAssetBundleDependency(string abName, int waitTime) + { + var otherAbName = GetCacheDependency(abName); + if (otherAbName.Length <= 0) return; + foreach (var dependAbName in otherAbName) + { + if (dependAbName == abName) continue; + var dependAbInfo = GetCacheAssetBundle(dependAbName); + if (dependAbInfo == null) continue; + dependAbInfo.UnReferenced(abName); + + + if (dependAbInfo.GetReferenced() <= 0) + { + UnloadAssetBundle(dependAbName, false, waitTime); + } + } + } + + + #region 其他方法 + + private string GenerateAssetBundlePath(string assetBundleName, bool isMD5 = false, bool isManifest = false, + bool isAddABSuffix = true) + { + var fileName = assetBundleName.ToLower(); + if (isMD5) + { + fileName = MD5String(fileName) + ".data"; + } + + var filePath = _assetBundleRootPath.Replace("file:///", "") + assetBundleName.ToLower(); + if (isAddABSuffix) + { + filePath += CrazyZooConstant.setbun; + } + + if (!isManifest) + return filePath; + if (File.Exists(filePath)) + { + return filePath; + } + + return filePath; + } + + private static string MD5String(string str) + { + using var md5 = MD5.Create(); + var hash = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(str)); + var tmp = new StringBuilder(); + foreach (var i in hash) + { + tmp.Append(i.ToString("x2")); + } + + return tmp.ToString(); + } + + #endregion + + public void RecycleAsset(string assetUrl, UnityAction onCompleted) + { + RecycleAssetBundle(assetUrl, onCompleted); + } + + private AssetBundleManifest GetManifest() + { + if (_manifest == null) + { + Debug.LogError("AssetBundleManifest is null"); + var assetBundles = + AssetBundle.LoadFromFile($"{CrazyZooFileKit.GetFilePath()}{CrazyZooConstant.undles}"); + var manifest = assetBundles.LoadAsset("assetbundlemanifest"); + _manifest = manifest; + } + + return _manifest; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs.meta new file mode 100644 index 0000000..5b8d8eb --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0049894e09758c34fb23600e4571504e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs new file mode 100644 index 0000000..9c4b55c --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs @@ -0,0 +1,9 @@ +namespace ScrewsMaster +{ + public enum CrazyZooState + { + STATE_NONE, + STATE_LOADING, + STATE_LOADED, + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs.meta new file mode 100644 index 0000000..9f065c8 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/CrazyZooState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e6f867b844a92f4e8799eeb338a9aa2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs new file mode 100644 index 0000000..b3244fc --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +public class FXPool : IDisposable where T : Enum +{ + private Dictionary> PoolDic; + private Dictionary PollPar; + private List temp; + private Transform objectPoolPar; + public Func NewObjFunc; + public Action RecObjFunc; + public Action GetObjFunc; + + public FXPool(Transform _objectPoolPar = null) + { + objectPoolPar = _objectPoolPar; + if (objectPoolPar == null) + { + objectPoolPar = new GameObject("ObjectPool").transform; + objectPoolPar.localPosition = Vector3.zero; + objectPoolPar.localEulerAngles = Vector3.zero; + } + + PoolDic = new Dictionary>(); + PollPar = new Dictionary(); + temp = new List(); + } + + public Obj GetObject(T key) where Obj : Object + { + Obj obj = null; + if (!PoolDic.ContainsKey(key)) + { + AddKey(key); + } + + if (PoolDic[key].Count > 0) + { + obj = PoolDic[key][0] as Obj; + PoolDic[key].RemoveAt(0); + } + else + { + obj = LoadObject(key); + } + + GetObjFunc?.Invoke(key, obj); + return obj; + } + + private void AddKey(T key) + { + PoolDic.Add(key, new List()); + Transform par = new GameObject(key.ToString()).transform; + par.SetParent(objectPoolPar); + par.localScale = Vector3.one; + par.localPosition = Vector3.zero; + par.localEulerAngles = Vector3.zero; + PollPar.Add(key, par.transform); + } + + private Obj LoadObject(T key) where Obj : UnityEngine.Object + { + Obj obj = NewObjFunc?.Invoke(key) as Obj; + if (obj != null) + { + GameObject go = obj as GameObject ?? (obj as Component).gameObject; + + if (PollPar.TryGetValue(key, out Transform par) && go != null) + { + go.transform.SetParent(par); + } + } + + return obj; + } + + public void RecObject(T key, Object obj) + { + if (obj == null) return; + if (!PoolDic.ContainsKey(key)) + { + PoolDic.Add(key, new List()); + } + + GameObject go = obj as GameObject ?? (obj as Component).gameObject; + if (PollPar.TryGetValue(key, out Transform par)) + { + go.transform.parent = (par); + } + + RecObjFunc?.Invoke(key, obj); + PoolDic[key].Add(obj); + } + + public void RemoveKey(T key) + { + if (PoolDic.ContainsKey(key)) + { + foreach (Object item in PoolDic[key]) + { + if (item != null) + { + GameObject go = item as GameObject; + if (go == null) + { + Component cot = item as Component; + go = cot.gameObject; + } + + GameObject.Destroy(go); + } + } + + PoolDic[key].Clear(); + PoolDic.Remove(key); + } + } + + public void RemoveAll() + { + temp.Clear(); + foreach (var item in PoolDic) + { + temp.Add(item.Key); + } + + foreach (var item in temp) + { + RemoveKey(item); + } + + temp.Clear(); + } + + public void Dispose() + { + RemoveAll(); + PoolDic = null; + PollPar = null; + temp = null; + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs.meta new file mode 100644 index 0000000..49314b4 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/FXPool.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3de141293f3240ffbdc26570a545e96c +timeCreated: 1681806263 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs new file mode 100644 index 0000000..de493bd --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using System.Text; +using System.Security.Cryptography; + +public class MD5Kit +{ + + public static string GetFileMD5(string file) + { + try + { + var fs = new FileStream(file, FileMode.Open); + MD5 md5 = new MD5CryptoServiceProvider(); + var retVal = md5.ComputeHash(fs); + fs.Close(); + + var sb = new StringBuilder(); + foreach (var str in retVal) + { + sb.Append(str.ToString("X2")); + } + + return sb.ToString(); + } + catch (Exception ex) + { + throw new Exception("GetFileMD5 fail error: " + ex.Message); + } + } + + /// + /// 获取字符串的MD5值 + /// + public static string GetStringMD5(string str) + { + if (string.IsNullOrEmpty(str)) + { + return null; + } + + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] bytResult = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); + string strResult = BitConverter.ToString(bytResult); + strResult = strResult.Replace("-", string.Empty); + return strResult; + } + + + public static string MD5String1(string text) + { + var buffer = Encoding.Default.GetBytes(text); + var check = new MD5CryptoServiceProvider(); + var somme = check.ComputeHash(buffer); + var result = new StringBuilder(); + foreach (var a in somme) + { + var value = a.ToString("X"); + if (a < 16) + { + result.Append(0); + result.Append(value); + } + else + { + result.Append(value); + } + } + + return result.ToString().ToLower(); + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs.meta new file mode 100644 index 0000000..77b5bad --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/MD5Kit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5697bf9fd10d9548977711311a96a00 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs new file mode 100644 index 0000000..20fc280 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs @@ -0,0 +1,498 @@ +namespace ScrewsMaster +{ + using System.Text; + using UnityEngine.Events; + using System.Collections; + using UnityEngine.Networking; + using System.Collections.Generic; + using Newtonsoft.Json; + using UnityEngine; + using System; + + public class NetworkKit + { + public static string CDNUrl; + + //打点需要的值-----began---- + public static string trace_id; + public static string channel_id; + public static long userId; + //打点需要的值-----end---- + public static Dictionary statusDic = new Dictionary(); + public static Dictionary> statusDic2 = new Dictionary>(); + + public static string GetCacheToken() + { + string token = null; + if (PlayerPrefsKit.HasKey(PrefsKeyConst.JarvisToken)) + { + token = PlayerPrefsKit.ReadString(PrefsKeyConst.JarvisToken); + } + + return token; + } + + public static void SetCacheToken(string token) + { + PlayerPrefsKit.WriteString(PrefsKeyConst.JarvisToken, token); + } + + private static IEnumerator PostInternal(string url, object requestData, UnityAction onCompleted, + Dictionary header = null) + { + //判断token是否失效 + // ReSetToken(); + + var requestJson = SerializeUtil.ToJsonIndented(requestData); + var url2 = url; +#if JarvisRelease + url2 = Base64Kit.Encode(url); + requestJson = Base64Kit.Encode(requestJson); +#endif + var bytes = Encoding.UTF8.GetBytes(requestJson); + var url1 = NetworkManager.CrazyUrl + url2; + var loginRequest = new UnityWebRequest(url1, UnityWebRequest.kHttpVerbPOST) + { + uploadHandler = new UploadHandlerRaw(bytes), + downloadHandler = new DownloadHandlerBuffer() + }; + + if (header != null) + { + foreach (var keyValuePair in header) + { + loginRequest.SetRequestHeader(keyValuePair.Key, keyValuePair.Value); + } + } + + SetRequestContentType(loginRequest); + Debug.Log($"request url1======= {url1}"); + yield return loginRequest.SendWebRequest(); + Debug.Log($"requestData11111======={url1}=={requestJson}"); + Debug.Log($"requestData22222====={url1}==={JsonConvert.SerializeObject(loginRequest)}"); + if (loginRequest.result is not UnityWebRequest.Result.Success) + { + onCompleted?.Invoke(false, default); + } + else + { + var receiveContent = loginRequest.downloadHandler.text; +#if JarvisRelease + if (!receiveContent.IsNullOrWhiteSpace()) + { + receiveContent = receiveContent.Substring(0, receiveContent.Length - 1); + receiveContent = receiveContent.Substring(1); + receiveContent = Base64Kit.Decode(receiveContent); + } +#endif + Debug.Log(receiveContent); + var response = SerializeUtil.ToObject(receiveContent); + + +#if UNITY_EDITOR + var respJson = JsonConvert.SerializeObject(response); + + // Debug.Log($"requestData======={url1}=={requestJson}"); + // Debug.Log($"response========={url1}=={respJson}"); +#endif + if (response?.code == 0) + { + var responseData = SerializeUtil.ToObject(response.data.ToString()); + onCompleted?.Invoke(true, responseData); + } + else + { + onCompleted?.Invoke(false, default); + } + } + + loginRequest.Dispose(); + } + + public static void SetRequestContentType(UnityWebRequest request) + { + request.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); + } + + public static Coroutine Post(string url, object requestData, UnityAction onCompleted) + { + return CrazyAsyKit.StartCoroutine(PostInternal(url, requestData, onCompleted)); + } + + public static Coroutine PostWithHeader(string url, object requestData = null, + UnityAction onCompleted = null) + { + var headers = new Dictionary { { "x-token", GetCacheToken() } }; + return CrazyAsyKit.StartCoroutine(PostInternal(url, requestData, onCompleted, headers)); + } + + public static void PostWithHeader(string url, UnityAction onCompleted) + { + if (onCompleted != null) + { + PostWithHeader(url, null, (isSuccess, obj) => { onCompleted.Invoke(isSuccess, obj); }); + } + else + { + PostWithHeader(url); + } + } + + public static void PostWithHeader(string url, object requestData = null, UnityAction onCompleted = null) + { + if (onCompleted != null) + { + PostWithHeader(url, requestData, (isSuccess, obj) => { onCompleted?.Invoke(isSuccess); }); + } + else + { + PostWithHeader(url, requestData); + } + } + + public static void PostFunnelLogin(RespLoginFunnelData reqData = null) + { + if (statusDic.TryGetValue(reqData.type, out var status)) + { + if (status) + { + return; + } + } + + + if (reqData.type == "bootstrap") + { + long timestamp = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000; + trace_id = timestamp.ToString(); + } + + var requestData = new RespLoginFunnelData + { + uid = userId, + trace_id = trace_id, + device_id = SystemInfo.deviceUniqueIdentifier, + // pack_name = Application.identifier, + pack_name = NetworkManager.packName, + version = Application.version, + channel = SuperApplication.Instance.attribution, + type = reqData.type, + payload = reqData.payload + }; + + statusDic.Add(reqData.type, true); + Debug.Log($"PostFunnelLogin requestData1111========={reqData.type}"); + Post("event/funnelLogin", requestData, (isSuccess, data) => + { + Debug.Log($"PostFunnelLogin responseData2222========={isSuccess} {reqData.type}"); + }); + } + public static void SendLogToServer(RespDebugData reqData) + { + if (!GameHelper.GetLoginModel().debug_log) return; + + // 如果只需要日期部分,可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化 + System.DateTime currentDate = System.DateTime.Now; + var formattedDate = currentDate.ToString("yyyy_MM_dd_HH_mm"); + + var md5Str = MD5Kit.GetStringMD5(reqData.message + reqData.stacktrace); + + if (!statusDic2.ContainsKey(formattedDate)) + { + statusDic2.Add(formattedDate, new Dictionary()); + } + + if (!statusDic2[formattedDate].ContainsKey(md5Str)) + { + statusDic2[formattedDate].Add(md5Str, false); + } + + // Debug.Log($"SendLogToServer requestData========={formattedDate} \nmd5Str=== {md5Str}"); + if (statusDic2[formattedDate][md5Str]) + { + return; + } + + var requestData = new RespDebugData + { + uid = userId, + device = SystemInfo.deviceModel, + os_ver = SystemInfo.operatingSystem, + network = GetNetworkType(), + device_id = SystemInfo.deviceUniqueIdentifier, + pack_name = NetworkManager.packName, + version = Application.version, + channel = SuperApplication.Instance.attribution, + level = reqData.level, + message = reqData.message, + stacktrace = reqData.stacktrace + }; + + statusDic2[formattedDate][md5Str] = true; + + //Debug.Log($"SendLogToServer requestData1========={JsonConvert.SerializeObject(requestData)}"); + Post("event/cliDebugLog", requestData, (isSuccess, data) => + { + + }); + } + private static string GetNetworkType() + { + string types = "Not Connected"; + switch (Application.internetReachability) + { + case NetworkReachability.ReachableViaCarrierDataNetwork: + types = "Mobile Data"; + break; + case NetworkReachability.ReachableViaLocalAreaNetwork: + types = "Wi-Fi"; + break; + } + return types; + } + + + public static AndroidPointObject androidPointObject = new(); + /* + * 打点 + */ + public static void BuriedPoint(string eventname, string eventproperty, int integer) + { + if (eventname == BuriedPointEvent.Apple_AD_event || eventname == BuriedPointEvent.Apple_pay_event) { + if (GameHelper.IsAdModelOfPay()) + { + eventname = BuriedPointEvent.Apple_AD_event; + } + else + { + eventname = MaxPayManager.isIOSPay? BuriedPointEvent.Apple_ios_pay_event : BuriedPointEvent.Apple_pay_event; + } + } + + androidPointObject.@event = eventname; + androidPointObject.property = eventproperty; + androidPointObject.n = integer; + Debug.Log("打点"+JsonConvert.SerializeObject(androidPointObject)); + PostWithHeader("/event/incrN", androidPointObject, (isSuccess, obj) => + { + }); + } + + private static bool isReqToken = false; + public static void ReSetToken() + { + if (isReqToken) return; + var nowTimes = GameHelper.GetCurrentTimestamp(); + var passtime = GameHelper.GetLoginModel().expires_at; + if (passtime - nowTimes > 3600) return; + isReqToken = true; + var requestLoginData = new RequestLoginData + { +#if !UNITY_EDITOR + device_id = SystemInfo.deviceUniqueIdentifier, +#else + device_id = "test004010", +#endif + // device_id = SystemInfo.deviceUniqueIdentifier, + pack_name = NetworkManager.packName, + app_version = Application.version, + //is debug test-------- + channel = SuperApplication.Instance.attribution, + sim = NetworkManager.haveSimCard + }; + Post("login", requestLoginData, (isSuccess, loginData) => + { + if (isSuccess) + { + var loginModel = GameHelper.GetLoginModel(); + loginModel.token = loginData.token; + loginModel.expires_at = loginData.expires_at; + SetCacheToken(loginData.token); + } + isReqToken = false; + }); + } + + public class AndroidPointObject + { + public string @event; + public string property; + public int n; + } + } + + + public class AndroidPointEvent + { + public static string Google_pay_event = "Google_pay_event"; + + public static string first_pack_show = "first_pack_show"; + public static string first_pack_click = "first_pack_click"; + public static string first_pack_open = "first_pack_open"; + public static string first_pack_success = "first_pack_success"; + + public static string remove_ad_show = "remove_ad_show"; + public static string remove_ad_click = "remove_ad_click"; + public static string remove_ad_open = "remove_ad_open"; + public static string remove_ad_success = "remove_ad_success"; + + public static string pass_show = "pass_show"; + public static string pass_click = "pass_click"; + public static string pass_open = "pass_open"; + public static string pass_success = "pass_success"; + + public static string buyslot_show = "buyslot_show"; + public static string buyslot_click = "buyslot_click"; + public static string buyslot_open = "buyslot_open"; + public static string buyslot_success = "buyslot_success"; + + public static string gold_show = "gold_show"; + public static string gold_click_1 = "gold_click_1"; + public static string gold_click_2 = "gold_click_2"; + public static string gold_click_3 = "gold_click_3"; + public static string gold_click_4 = "gold_click_4"; + public static string gold_open_1 = "gold_open_1"; + public static string gold_open_2 = "gold_open_2"; + public static string gold_open_3 = "gold_open_3"; + public static string gold_open_4 = "gold_open_4"; + public static string gold_success_1 = "gold_success_1"; + public static string gold_success_2 = "gold_success_2"; + public static string gold_success_3 = "gold_success_3"; + public static string gold_success_4 = "gold_success_4"; + } + + public class BuriedPointEvent + { + public static string play_event = "Number_of_people_play"; + public static string play_property = "Number_of_people_playing"; + + public static string playing_event = "Playing_time"; + public static string playing_property = "Room_type"; + + public static string ad_task = "ad_task"; + public static string watch_ad_number = "watch_ad_number"; + public static string finish_ad_number = "finish_ad_number"; + + public static string h5_event = "H5_task"; + public static string h5_event_time = "H5_time"; + public static string h5_event_numbers = "finish_H5_number"; + + public static string withdraw_behavior = "withdraw_behavior"; + public static string withdraw_message = "withdraw_message"; + public static string withdraw_cash1 = "withdraw_cash1"; + public static string withdraw_cash2 = "withdraw_cash2"; + public static string withdraw_cash3 = "withdraw_cash3"; + + public static string Hall_behavior = "Hall_behavior"; + public static string open_hall_number = "open_hall_number"; + //public static string open_hall_people = "open_hall_people"; + public static string collect_fly_number = "collect_fly_number"; + //public static string collect_fly_people = "collect_fly_people"; + public static string fly_ct_number = "fly_ct_number"; + //public static string fly_ct_people = "fly_ct_people"; + public static string annular_finish_number = "annular_finish_number"; + public static string annular_get_number = "annular_get_number"; + public static string annular_ct_number = "annular_ct_number"; + //public static string annular_ct_people = "annular_ct_people"; + + public static string video_behavior = "video_behavior"; + public static string watch_ad_people = "watch_ad_people"; + public static string watch_success_ad_people = "watch_success_ad_people"; + + public static string video_type = "video_type"; + public static string Rewarded_videos_trigger_number = "Rewarded_videos_trigger_number"; + public static string Rewarded_videos_fill_number = "Rewarded_videos_fill_number"; + public static string Rewarded_videos_dinish_number = "Rewarded_videos_dinish_number"; + public static string Interstitial_videos_trigger_number = "Interstitial_videos_trigger_number"; + public static string Interstitial_videos_fill_number = "Interstitial_videos_fill_number"; + public static string Interstitial_videos_dinish_number = "Interstitial_videos_dinish_number"; + + public static string Apple_pay_event = "Pay_Event"; + + public static string first_pack_show = "first_pack_show"; + public static string first_pack_click = "first_pack_click"; + public static string first_pack_open = "first_pack_open"; + public static string first_pack_success = "first_pack_success"; + + public static string remove_ad_show = "remove_ad_show"; + public static string remove_ad_click = "remove_ad_click"; + public static string remove_ad_success = "remove_ad_success"; + + public static string pass_show = "master_pass_show"; + public static string pass_click = "master_pass_click"; + public static string pass_open = "pass_open"; + public static string pass_success = "master_pass_receive"; + + public static string AddBoxShow = "add_block_show"; + public static string AddBoxClick = "add_block_click"; + public static readonly string AddBoxPay = "add_block_receive"; + + public static string buyslot_show = "buyslot_show"; + public static string buyslot_click = "buyslot_click"; + public static string buyslot_open = "buyslot_open"; + public static string buyslot_success = "buyslot_receive"; + + public static string gold_show = "gold_show"; + public static string gold_click = "gold_click"; + // public static string gold_click_2 = "gold_click_2"; + // public static string gold_click_3 = "gold_click_3"; + // public static string gold_click_4 = "gold_click_4"; + // public static string gold_open_1 = "gold_open_1"; + // public static string gold_open_2 = "gold_open_2"; + // public static string gold_open_3 = "gold_open_3"; + // public static string gold_open_4 = "gold_open_4"; + public static string GoldSuccess = "gold_success"; + // public static string gold_success_2 = "gold_success_2"; + // public static string gold_success_3 = "gold_success_3"; + // public static string gold_success_4 = "gold_success_4"; + public static string afterRewardAdShow = "afterRewardAdShow"; + public static string afterRewardAdEnd = "afterRewardAdEnd"; + public static string fail_show = "fail_show"; + public static string fail_click = "fail_click"; + public static string fail_buy_success = "fail_buy_success"; + public static string three_days_gift_show = "three_days_gift_show"; + public static string three_days_gift_click = "three_days_gift_click"; + public static string three_days_gift_buy_success = "three_days_gift_buy_success"; + public static string three_days_gift_open = "three_days_gift_open"; + public static string three_day1_success = "three_day1_success"; + public static string three_day2_success = "three_day2_success"; + public static string three_day3_success = "three_day3_success"; + public static string Three_days_gift_event = "Three_days_gift_event"; + + + + //public static string annular_ct_people = "annular_ct_people"; + + public static string Apple_ios_pay_event = "IOS_Pay_Event"; + public static string Apple_AD_event = "AD_Event"; + + + public static string pack_show = "pack_show"; + public static string pack_click = "pack_click"; + public static string pack_open = "pack_open"; + public static string pack__success = "pack_receive"; + + public static string buy_one_show = "buy_one_show"; + public static string buy_one_click = "buy_one_click"; + public static string buy_one_open = "buy_one_open"; + public static string buy_one_success = "buy_one_success"; + public static string gold_click_1 = "shop_click"; + // public static string gold_click_2 = "gold_click_2"; + // public static string gold_click_3 = "gold_click_3"; + // public static string gold_click_4 = "gold_click_4"; + // public static string gold_open_1 = "gold_open_1"; + // public static string gold_open_2 = "gold_open_2"; + // public static string gold_open_3 = "gold_open_3"; + // public static string gold_open_4 = "gold_open_4"; + public static string gold_success_1 = "shop_receive"; + // public static string gold_success_2 = "gold_success_2"; + // public static string gold_success_3 = "gold_success_3"; + // public static string gold_success_4 = "gold_success_4"; + + public const string remove_ad_open = "remove_ad_open"; + public const string pack_success = "pack_success"; + public static string gold_click_ad = "gold_click_ad"; + public static string fail_open = "fail_open"; + + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs.meta new file mode 100644 index 0000000..1180add --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/NetworkKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e7375397b5a640f4b3d00f86381f7a3a +timeCreated: 1692338896 \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs b/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs new file mode 100644 index 0000000..cef0284 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs @@ -0,0 +1,84 @@ +using UnityEngine; + +namespace ScrewsMaster +{ + public class QuestionBankKit + { + public static GameQuestionData GetQuestionTable(QuestionBank questionBankVo, bool isGuide) + { + if (isGuide) + { + return GetQuestionTableInternal(questionBankVo, 0, "newbie"); + } + + var bankTypeArr = questionBankVo.tableKey; + var nextIndexBankType = Random.Range(0, bankTypeArr.Length); + + if (!GameHelper.IsGiftSwitch() && questionBankVo.type.Contains(2)) + { + for (var i = 0; i < questionBankVo.type.Count; i++) + { + if (questionBankVo.type[i] != 2) + { + continue; + } + + nextIndexBankType = i; + break; + } + } + + var questionType = questionBankVo.type[nextIndexBankType]; + + return GetQuestionTableInternal(questionBankVo, questionType, bankTypeArr[nextIndexBankType]); + } + + private static GameQuestionData GetQuestionTableInternal(QuestionBank questionBankVo, int questionType, + string bankTypeKey) + { + var questionModel = new GameQuestionData + { + questionName = bankTypeKey, + questionType = questionType + }; + + var language = GameHelper.GetDeviceLanguage().ToUpper(); + + var tableKey = bankTypeKey; + if (language.Equals("PT") || language.Equals("ES") || language.Equals("RU")) + { + tableKey = $"{bankTypeKey}_{language}"; + } + + // var questionData = ConfigSystem.GetQuestion(tableKey).GetRandomQuestion(); + // questionModel.questionTitle = questionData.subject; + // questionModel.answer = new[] + // { + // questionData.answer_one, questionData.answer_two, questionData.answer_three, + // questionData.answer_four + // }; + // questionModel.logoId = questionData.Picture_name; + if (language.Equals("PT")) + { + questionModel.desc = questionBankVo.desc_pt; + } + else if (language.Equals("ES")) + { + questionModel.desc = questionBankVo.desc_es; + } + else if (language.Equals("RU")) + { + questionModel.desc = questionBankVo.desc_ru; + } + + // questionModel.questionTableID = questionData.id; + + if (bankTypeKey == "newbie") + { + questionModel.isGuide = true; + } + + return questionModel; + } + } +} \ No newline at end of file diff --git a/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs.meta b/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs.meta new file mode 100644 index 0000000..6d1d4b1 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Logic/ToolKit/QuestionBankKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c88996907c0f7c546baca3ca6fb4e6d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Scripts.meta b/Assets/CrazyZoo/Runtime/Scripts.meta new file mode 100644 index 0000000..663d716 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7c20b1949ec44be49803acd6755b702e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs b/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs new file mode 100644 index 0000000..3f19602 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json; +using UnityEngine; +namespace ScrewsMaster +{ + public class SaveData + { + public static Saveobject saveobject; + public static Saveobject GetSaveobject() + { + if (saveobject == null) + { + if (File.Exists(jsonFilePath)) + { + string jsonstr = File.ReadAllText(jsonFilePath); + saveobject = JsonConvert.DeserializeObject(jsonstr); + return saveobject; + } + else + { + saveobject = new Saveobject(); + return saveobject; + } + } + else return saveobject; + + } + + private static string jsonFilePath = Path.Combine(Application.persistentDataPath, "savedata22.json"); + + public static void saveDataFunc() + { + + if (saveobject == null) return; + string save = JsonConvert.SerializeObject(saveobject); + if (save == null || save == string.Empty) return; + if (File.Exists(jsonFilePath)) File.Delete(jsonFilePath); + File.WriteAllText(jsonFilePath, save); + + } + public static bool battlepassred() + { + + int pass_level = GameHelper.GetBattleLv(); + List freelist = SaveData.GetSaveobject().battle_pass_freelist; + for (int i = 1; i <= ConfigSystem.GetConfig().dataList.Count; i++) + { + if (pass_level >= i) + { + if (!freelist.Contains(i)) + { + return true; + } + } + + } + if (SaveData.GetSaveobject().is_get_battlepass) + { + List paylist = SaveData.GetSaveobject().battle_pass_paylist; + for (int i = 1; i <= ConfigSystem.GetConfig().dataList.Count; i++) + { + if (pass_level >= i) + { + if (!paylist.Contains(i)) + { + return true; + } + } + } + } + return false; + } + + public static bool passtaskred() + { + List list = SaveData.GetSaveobject().pass_task_record; + for (int i = 0; i < ConfigSystem.GetConfig().dataList.Count; i++) + { + if (GameHelper.GetLevel() > ConfigSystem.GetConfig().dataList[i].tol_num) + { + if (!list.Contains(ConfigSystem.GetConfig().dataList[i].id)) return true; + } + } + return false; + } + public static bool timetaskred() + { + List list = SaveData.GetSaveobject().time_task_record; + for (int i = 0; i < ConfigSystem.GetConfig().dataList.Count; i++) + { + if (GameHelper.getGameTime() >= ConfigSystem.GetConfig().dataList[i].tol_num * 60) + { + if (!list.Contains(ConfigSystem.GetConfig().dataList[i].id)) return true; + } + } + return false; + } + public static bool getRed() + { + + return battlepassred() || passtaskred() || timetaskred(); + } + public static float pay_time = 0; + + + } + + public class Saveobject + { + + + public bool is_get_battlepass = false; + public List battle_pass_freelist = new List(); + public List battle_pass_paylist = new List(); + + + public long lastAdRewardExchangeTime; + public int _goldtime0; + public int _goldtime1; + public int _goldtime2; + public int _goldtime3; + public int _goldtime4; + public int _goldtime5; + public int _goldtime6; + public bool have_slot; + public int battle_pass_time; + + + public List pass_task_record = new List(); + public List time_task_record = new List(); + public int login_day; + public int login_hour; + public int cash_people; + public float cash_people_1; + public float cash_people_2; + + public bool is_get_packreward; + + public bool is_get_removead; + public bool is_autopack_show; + public int is_autopack_show_day; + + public long start_time; + public int clear_number; + // public GooglePayClass google_pay_object = null; + // public ApplePayClass apple_pay_object = null; + public int this_time_cardtype; + + public int[] dark_Dayref; + + public RequestStageData StageData; + public List saveingpot_history = new List(); + public float saveingpot_cash; + public float last_saveingpot_cash; + + public long failed_pack_time; + public int three_gift_got_index = 1; + public long last_got_three_gift_time = 0; + public bool is_get_ThreeDaysGift; + public ApplePayClass max_pay_object; + } +} diff --git a/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs.meta b/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs.meta new file mode 100644 index 0000000..9299979 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Scripts/SaveData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a0da9975597a8bc4a9989d80b46a72a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs b/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs new file mode 100644 index 0000000..d96b4ed --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json; +using ScrewsMaster; +using UnityEngine; + +public class SaveingPotClass +{ + + public int tableId; + + + public int id; + + + public string amountStr; + + + public float amount; + + + public long makeupTime; + + + public int videoCount; + + + public int inlineInitNum; + + + public int inlineNum; + + + public string orderID; + + + public SaveingPotTaskStatus status; + + public long order_time = 0; + public int WatchVideoSpeedNum = 0; + public int loginSpeedNum = 0; + public int activeMinute = 0; + public int activeSpeedNum = 0; + + public bool needShowAni = true; + public float H5Time; + + public long clear_time; + public long start_time; + public bool auto_show = false; + public void SetStatus(SaveingPotTaskStatus _status) + { + status = _status; + } + + public string GetAmountStr() + { + // if (amount <= 0) + // { + // return amountStr; + // } + // else + // { + return $"${amount:N}"; + //} + } + + public float cash_number = 0; +} +public enum SaveingPotTaskStatus +{ + None, + Task, + Inline, +} +// var makeupTaskData = new MakeupTaskData(); +// makeupTaskData.tableId = makeupVo.id; +// makeupTaskData.id = PreferencesMgr.Instance.MakeupTaskHistory.Count + 1; +// makeupTaskData.amountStr = $"{GameHelper.Get102Str(makeupVo.item_need)}"; +// makeupTaskData.amount = makeupVo.item_need; +// makeupTaskData.orderID = GameHelper.GetRandomNum(8); + +// PreferencesMgr.Instance.MakeupTaskHistory.Add(makeupTaskData); +// Debug.Log("uuuuuuuuuuuuuuuuuuuu"); +// makeupTaskData.SetStatus(MakeupTaskStatus.None); +public class SaveingPotHelper +{ + + public static void CheckSaveingPot() + { + Debug.Log(SaveData.GetSaveobject()); + if (SaveData.GetSaveobject().saveingpot_history == null || SaveData.GetSaveobject().saveingpot_history.Count == 0) + { + CreatSaveingPotItem(); + } + ResetHistory(); + } + + public static void CreatSaveingPotItem() + { + if (SaveData.GetSaveobject().saveingpot_history.Count >= 3) + { + SaveData.saveDataFunc(); + return; + } + int index = SaveData.GetSaveobject().saveingpot_history.Count; + if (index >= ConfigSystem.GetConfig().dataList.Count) index = ConfigSystem.GetConfig().dataList.Count - 1; + Makeup_2 config = ConfigSystem.GetConfig().dataList[index]; + SaveingPotClass saveingpot = new SaveingPotClass(); + saveingpot.tableId = config.id; + saveingpot.id = SaveData.GetSaveobject().saveingpot_history.Count + 1; + saveingpot.amountStr = $"${config.item_need:N}"; + saveingpot.amount = config.item_need; + saveingpot.orderID = GameHelper.GetRandomNum(8); + saveingpot.SetStatus(SaveingPotTaskStatus.None); + saveingpot.clear_time = GameHelper.GetNowTime() + config.Reset_time * 3600; + saveingpot.start_time = GameHelper.GetNowTime(); + + SaveData.GetSaveobject().saveingpot_history.Add(saveingpot); + SaveData.saveDataFunc(); + Debug.Log("zengjaichenggong"); + } + + public static bool TestingClearTime() + { + Debug.Log(SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].clear_time < GameHelper.GetNowTime()); + Debug.Log(SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].clear_time); + Debug.Log(GameHelper.GetNowTime()); + if (SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].clear_time < GameHelper.GetNowTime() && SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].needShowAni) + { + Debug.Log("qinglisaveingpot"); + int index = SaveData.GetSaveobject().saveingpot_history.Count - 1; + Makeup_2 config = ConfigSystem.GetConfig().dataList[index]; + SaveData.GetSaveobject().saveingpot_cash = 0; + Debug.Log(JsonConvert.SerializeObject(config)); + Debug.Log(config.Reset_time); + SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].clear_time = GameHelper.GetNowTime() + config.Reset_time * 3600; + SaveData.GetSaveobject().saveingpot_history[SaveData.GetSaveobject().saveingpot_history.Count - 1].auto_show = false; + + return true; + + } + return false; + } + public static void ResetHistory() + { + for (int i = 0; i < SaveData.GetSaveobject().saveingpot_history.Count; i++) + { + SaveingPotClass saveingpot = SaveData.GetSaveobject().saveingpot_history[i]; + Makeup_2 config = ConfigSystem.GetConfig().dataList[i]; + saveingpot.amount = config.item_need; + saveingpot.amountStr = $"${config.item_need:N}"; + if (saveingpot.start_time + config.Reset_time * 3600 - saveingpot.clear_time > 100) + { + saveingpot.clear_time = saveingpot.start_time + config.Reset_time * 3600; + } + } + SaveData.saveDataFunc(); + + } + + + + public static string getCashString(float cash) + { + return $"${cash:N}"; + } + public static string getCashNumber(float cash) + { + return $"{cash:N}"; + } + +} + diff --git a/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs.meta b/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs.meta new file mode 100644 index 0000000..9c33b93 --- /dev/null +++ b/Assets/CrazyZoo/Runtime/Scripts/SaveingPotClass.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 329120cf0ad8a4b6a9e4c56b36c62520 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Scene.meta b/Assets/CrazyZoo/Scene.meta new file mode 100644 index 0000000..24a256c --- /dev/null +++ b/Assets/CrazyZoo/Scene.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 69fad7dc034e17c46a4c250e2ca08519 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CrazyZoo/Scene/MainScene.unity b/Assets/CrazyZoo/Scene/MainScene.unity new file mode 100644 index 0000000..badddff --- /dev/null +++ b/Assets/CrazyZoo/Scene/MainScene.unity @@ -0,0 +1,1028 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.3708708, g: 0.37838137, b: 0.35725543, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 12 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 0} + m_LightingSettings: {fileID: 0} +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 3 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + buildHeightMesh: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &48343771 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 48343773} + - component: {fileID: 48343772} + m_Layer: 0 + m_Name: WebviewManager + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &48343772 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 48343771} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1eb2bc549fe045758bca6f69676b6bf4, type: 3} + m_Name: + m_EditorClassIdentifier: + orthoCamera: {fileID: 0} +--- !u!4 &48343773 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 48343771} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 10005.4, y: 9989.2, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &102266212 +GameObject: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 102266214} + - component: {fileID: 102266213} + m_Layer: 0 + m_Name: '[FairyGUI.Timers]' + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &102266213 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 102266212} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1323764443} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &102266214 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 102266212} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!115 &221239770 +MonoScript: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 7 + m_DefaultReferences: {} + m_Icon: {fileID: 0} + m_Type: 2 + m_ExecutionOrder: 0 + m_ClassName: TimersEngine + m_Namespace: FairyGUI + m_AssemblyName: +--- !u!1 &238520302 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 238520303} + - component: {fileID: 238520305} + - component: {fileID: 238520306} + m_Layer: 0 + m_Name: CrazyZooScene + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &238520303 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 238520302} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &238520305 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 238520302} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 958cbcd088fb3bc4c826840c9648b64e, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!114 &238520306 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 238520302} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 03245a515d1e47a8ab5720b508bef85b, type: 3} + m_Name: + m_EditorClassIdentifier: + appID: + is_init: 0 +--- !u!1 &263133450 stripped +GameObject: + m_CorrespondingSourceObject: {fileID: 7817730197660402642, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + m_PrefabInstance: {fileID: 316038031} + m_PrefabAsset: {fileID: 0} +--- !u!1001 &316038031 +PrefabInstance: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Modification: + serializedVersion: 3 + m_TransformParent: {fileID: 0} + m_Modifications: + - target: {fileID: 852585681329446234, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 1447382009268431134, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 1541262845088554733, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 4918018645639592118, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795707, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_Name + value: GameStage + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795707, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795708, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_Camera + value: + objectReference: {fileID: 1366607520} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_Pivot.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_Pivot.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchorMax.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchorMax.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchorMin.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchorMin.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_SizeDelta.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_SizeDelta.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalPosition.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalPosition.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalPosition.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalRotation.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalRotation.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalRotation.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchoredPosition.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_AnchoredPosition.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalEulerAnglesHint.x + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalEulerAnglesHint.y + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197064795711, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_LocalEulerAnglesHint.z + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 7817730197660402642, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 7817730197660402644, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_Color.a + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 8491034104586029046, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + propertyPath: m_IsActive + value: 1 + objectReference: {fileID: 0} + m_RemovedComponents: [] + m_RemovedGameObjects: [] + m_AddedGameObjects: [] + m_AddedComponents: [] + m_SourcePrefab: {fileID: 100100000, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} +--- !u!1 &394958074 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 394958076} + - component: {fileID: 394958075} + m_Layer: 0 + m_Name: InitObj + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &394958075 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 394958074} + m_Enabled: 0 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 1b88f4352f192a34ca4217a9f96f870e, type: 3} + m_Name: + m_EditorClassIdentifier: + environment: production +--- !u!4 &394958076 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 394958074} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 9997.392, y: 9999.445, z: -0.10103888} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &436127299 +GameObject: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 436127301} + - component: {fileID: 436127300} + m_Layer: 0 + m_Name: '[FairyGUI.Timers]' + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &436127300 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 436127299} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 951709596} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &436127301 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 436127299} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &764984840 +GameObject: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 764984842} + - component: {fileID: 764984841} + m_Layer: 0 + m_Name: '[FairyGUI.Timers]' + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &764984841 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 764984840} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1545485725} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &764984842 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 764984840} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &791793719 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 791793722} + - component: {fileID: 791793721} + - component: {fileID: 791793720} + m_Layer: 0 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &791793720 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 791793719} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} + m_Name: + m_EditorClassIdentifier: + m_SendPointerHoverToParent: 1 + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &791793721 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 791793719} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!4 &791793722 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 791793719} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!115 &951709596 +MonoScript: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 7 + m_DefaultReferences: {} + m_Icon: {fileID: 0} + m_Type: 0 + m_ExecutionOrder: 0 + m_ClassName: TimersEngine + m_Namespace: FairyGUI + m_AssemblyName: Assembly-CSharp +--- !u!1 &1106519846 +GameObject: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1106519848} + - component: {fileID: 1106519847} + m_Layer: 0 + m_Name: '[FairyGUI.Timers]' + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1106519847 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1106519846} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 221239770} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &1106519848 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1106519846} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!115 &1323764443 +MonoScript: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 7 + m_DefaultReferences: {} + m_Icon: {fileID: 0} + m_Type: 0 + m_ExecutionOrder: 0 + m_ClassName: TimersEngine + m_Namespace: FairyGUI + m_AssemblyName: Assembly-CSharp +--- !u!1 &1342349628 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1342349630} + - component: {fileID: 1342349629} + - component: {fileID: 1342349631} + m_Layer: 0 + m_Name: UIScreenTapTrigger + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1342349629 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1342349628} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0c397f9da8994cf49aa030a19853a442, type: 3} + m_Name: + m_EditorClassIdentifier: + canvas: {fileID: 1571831605} +--- !u!4 &1342349630 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1342349628} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 10005.4, y: 9989.2, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1342349631 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1342349628} + m_Enabled: 0 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 28853f4e040a81b4ca3663e53bff0fd4, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1366607518 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1366607521} + - component: {fileID: 1366607520} + m_Layer: 0 + m_Name: Camera + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!20 &1366607520 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1366607518} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 + m_Iso: 200 + m_ShutterSpeed: 0.005 + m_Aperture: 16 + m_FocusDistance: 10 + m_FocalLength: 50 + m_BladeCount: 5 + m_Curvature: {x: 2, y: 11} + m_BarrelClipping: 0.25 + m_Anamorphism: 0 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 410 + field of view: 60 + orthographic: 1 + orthographic size: 50 + m_Depth: 1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1366607521 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1366607518} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 100} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!115 &1545485725 +MonoScript: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 7 + m_DefaultReferences: {} + m_Icon: {fileID: 0} + m_Type: 0 + m_ExecutionOrder: 0 + m_ClassName: TimersEngine + m_Namespace: FairyGUI + m_AssemblyName: Assembly-CSharp +--- !u!223 &1571831605 stripped +Canvas: + m_CorrespondingSourceObject: {fileID: 7817730197064795708, guid: 96d1bffd106d2c447b20e183018429ad, type: 3} + m_PrefabInstance: {fileID: 316038031} + m_PrefabAsset: {fileID: 0} +--- !u!1 &1671102880 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1671102881} + - component: {fileID: 1671102882} + m_Layer: 0 + m_Name: ErrorLoggerObj + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1671102881 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1671102880} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 9997.392, y: 9999.445, z: -0.10103888} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1671102882 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1671102880} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5a9adb6383d4d1846a5c1efee1e943ac, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!115 &1676823177 +MonoScript: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: + serializedVersion: 7 + m_DefaultReferences: {} + m_Icon: {fileID: 0} + m_Type: 0 + m_ExecutionOrder: 0 + m_ClassName: TimersEngine + m_Namespace: FairyGUI + m_AssemblyName: Assembly-CSharp +--- !u!1 &2014148567 +GameObject: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2014148569} + - component: {fileID: 2014148568} + m_Layer: 0 + m_Name: '[FairyGUI.Timers]' + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &2014148568 +MonoBehaviour: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2014148567} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1676823177} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &2014148569 +Transform: + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2014148567} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &2030319309 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2030319311} + - component: {fileID: 2030319310} + m_Layer: 0 + m_Name: TwistNode + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &2030319310 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2030319309} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f342bfdaac9ae4d729e7eb83b84641cf, type: 3} + m_Name: + m_EditorClassIdentifier: + bg: {fileID: 263133450} +--- !u!4 &2030319311 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2030319309} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 10005.4, y: 9990.4, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1660057539 &9223372036854775807 +SceneRoots: + m_ObjectHideFlags: 0 + m_Roots: + - {fileID: 1106519848} + - {fileID: 1366607521} + - {fileID: 394958076} + - {fileID: 238520303} + - {fileID: 1671102881} + - {fileID: 316038031} + - {fileID: 791793722} + - {fileID: 102266214} + - {fileID: 2014148569} + - {fileID: 436127301} + - {fileID: 764984842} + - {fileID: 48343773} + - {fileID: 1342349630} + - {fileID: 2030319311} diff --git a/Assets/CrazyZoo/Scene/MainScene.unity.meta b/Assets/CrazyZoo/Scene/MainScene.unity.meta new file mode 100644 index 0000000..9e3c97a --- /dev/null +++ b/Assets/CrazyZoo/Scene/MainScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4d8c34fd44eebfc448695c81f0662e75 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor.meta b/Assets/Editor.meta new file mode 100644 index 0000000..19d3ab4 --- /dev/null +++ b/Assets/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a36e5eb7b0b859e4ba76abeef0cf6e0b +folderAsset: yes +timeCreated: 1456430305 +licenseType: Store +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/PostProcessBuild.cs b/Assets/Editor/PostProcessBuild.cs new file mode 100644 index 0000000..7ad2ba0 --- /dev/null +++ b/Assets/Editor/PostProcessBuild.cs @@ -0,0 +1,87 @@ +// using UnityEditor; +// using UnityEditor.Callbacks; +// using UnityEditor.iOS.Xcode; +// using System.IO; +// using UnityEditor.Build; +// using UnityEngine; + +// public class PostProcessBuild : IPostprocessBuildWithReport +// { +// public int callbackOrder => 1; + +// public void OnPostprocessBuild(UnityEditor.Build.Reporting.BuildReport report) +// { +// // 检查是否为 iOS 平台构建 +// if (report.summary.platform == BuildTarget.iOS) +// { + +// string projectPath = report.summary.outputPath; +// string customControllerPath = "Assets/Editor/UnityAppController.mm"; // 自定义文件的路径 +// string destinationPath = Path.Combine(projectPath, "Classes/UnityAppController.mm"); + +// if (File.Exists(customControllerPath)) +// { +// // 复制文件到 Xcode 项目中 +// File.Copy(customControllerPath, destinationPath, overwrite: true); +// Debug.Log("Custom UnityAppController.mm has been copied to Xcode project."); +// } +// else +// { +// Debug.LogError("Custom UnityAppController.mm file not found at " + customControllerPath); +// } +// } +// } + +// // 这是一个 PostProcessBuild 脚本,在 Unity 构建完成后自动执行 +// [PostProcessBuild] +// public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject) +// { +// // 仅对 iOS 构建进行处理 +// if (buildTarget == BuildTarget.iOS) +// { +// AddImagesToXcodeProject(pathToBuiltProject); +// } +// } + +// // 将 PNG 文件添加到 Xcode 项目中的 Images.xcassets +// private static void AddImagesToXcodeProject(string xcodeProjectPath) +// { +// string sourceImageFolder = "Assets/Plugins/iOS/"; // 你要打包的 PNG 文件所在文件夹 +// string destinationAssetsFolder = Path.Combine(xcodeProjectPath, "Images.xcassets"); + +// if (!Directory.Exists(sourceImageFolder)) +// { +// Debug.LogError("Image folder does not exist: " + sourceImageFolder); +// return; +// } + +// // 确保 Images.xcassets 文件夹存在 +// if (!Directory.Exists(destinationAssetsFolder)) +// { +// Directory.CreateDirectory(destinationAssetsFolder); +// } + +// // 遍历 Plugins/iOS 文件夹中的所有 PNG 文件 +// string[] pngFiles = Directory.GetFiles(sourceImageFolder, "*.png"); + +// foreach (var file in pngFiles) +// { +// // 获取文件名 +// string fileName = Path.GetFileName(file); + +// // 确保文件被添加到 xcassets 中 +// string destinationFilePath = Path.Combine(destinationAssetsFolder, fileName); + +// // 将文件复制到 xcassets 目录 +// if (!File.Exists(destinationFilePath)) +// { +// File.Copy(file, destinationFilePath); +// Debug.Log("Added " + fileName + " to " + destinationAssetsFolder); +// } +// else +// { +// Debug.LogWarning(fileName + " already exists in the destination."); +// } +// } +// } +// } \ No newline at end of file diff --git a/Assets/Editor/PostProcessBuild.cs.meta b/Assets/Editor/PostProcessBuild.cs.meta new file mode 100644 index 0000000..1633403 --- /dev/null +++ b/Assets/Editor/PostProcessBuild.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c63f69f4234bbc4dba0591f050d264f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/com.unity.mobile.notifications.meta b/Assets/Editor/com.unity.mobile.notifications.meta new file mode 100644 index 0000000..ba14f96 --- /dev/null +++ b/Assets/Editor/com.unity.mobile.notifications.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8d94ea3741ad8d344a76cca0aa62f67e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset b/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset new file mode 100644 index 0000000..655d006 --- /dev/null +++ b/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset @@ -0,0 +1,42 @@ +%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: 0863bf92b4fcc45b0b9267325249bf0f, type: 3} + m_Name: NotificationSettings + m_EditorClassIdentifier: + toolbarInt: 0 + iOSNotificationEditorSettingsValues: + keys: + - UnityNotificationRequestAuthorizationOnAppLaunch + - UnityNotificationDefaultAuthorizationOptions + - UnityAddRemoteNotificationCapability + - UnityNotificationRequestAuthorizationForRemoteNotificationsOnAppLaunch + - UnityRemoteNotificationForegroundPresentationOptions + - UnityUseAPSReleaseEnvironment + - UnityUseLocationNotificationTrigger + values: + - True + - 7 + - False + - False + - -1 + - False + - False + AndroidNotificationEditorSettingsValues: + keys: + - UnityNotificationAndroidRescheduleOnDeviceRestart + - UnityNotificationAndroidUseCustomActivity + - UnityNotificationAndroidCustomActivityString + values: + - False + - False + - com.unity3d.player.UnityPlayerActivity + TrackedResourceAssets: [] diff --git a/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset.meta b/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset.meta new file mode 100644 index 0000000..0d0e7d9 --- /dev/null +++ b/Assets/Editor/com.unity.mobile.notifications/NotificationSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4cee8bca36f2ab74b8feb832747fa6f4 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ExternalDependencyManager.meta b/Assets/ExternalDependencyManager.meta new file mode 100644 index 0000000..183d756 --- /dev/null +++ b/Assets/ExternalDependencyManager.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3e6ffef6e4c2c624d80f2dfc5bcfe9ff +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Icon.png b/Assets/Icon.png new file mode 100644 index 0000000..49e9e80 Binary files /dev/null and b/Assets/Icon.png differ diff --git a/Assets/Icon.png.meta b/Assets/Icon.png.meta new file mode 100644 index 0000000..54c93a2 --- /dev/null +++ b/Assets/Icon.png.meta @@ -0,0 +1,140 @@ +fileFormatVersion: 2 +guid: 9a3819e3b9b6fa14a9698a88ec963f1c +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 13 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + flipGreenChannel: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + ignoreMipmapLimit: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: 1 + aniso: 1 + mipBias: 0 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + swizzle: 50462976 + cookieLightType: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: iPhone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + - serializedVersion: 3 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + ignorePlatformSupport: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 5e97eb03825dee720800000000000000 + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + nameFileIdTable: {} + mipmapLimitGroupName: + pSDRemoveMatte: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk.meta b/Assets/MaxSdk.meta new file mode 100644 index 0000000..bfb6a84 --- /dev/null +++ b/Assets/MaxSdk.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 83032c3848cc4257b81f3ff456c223a6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin.meta b/Assets/MaxSdk/AppLovin.meta new file mode 100644 index 0000000..1eeb501 --- /dev/null +++ b/Assets/MaxSdk/AppLovin.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c1b72868379c47e09b166532c8315b9 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Editor.meta b/Assets/MaxSdk/AppLovin/Editor.meta new file mode 100644 index 0000000..5293e1f --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fe11ee64f53a3444488df87d514453f2 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml b/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml new file mode 100644 index 0000000..2d7a1d3 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml.meta b/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..3360fd3 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 746da98302dc0402aaa37e8f7bd97e77 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins.meta b/Assets/MaxSdk/AppLovin/Plugins.meta new file mode 100644 index 0000000..9423aa8 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 84b29ec0b0445458887cdfd8bce90a6a +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/Android.meta b/Assets/MaxSdk/AppLovin/Plugins/Android.meta new file mode 100644 index 0000000..915ba0f --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/Android.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae93186e4e8904966bd5a83eae513594 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/Android +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar b/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar new file mode 100644 index 0000000..60a443b Binary files /dev/null and b/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar differ diff --git a/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar.meta b/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar.meta new file mode 100644 index 0000000..224076a --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar.meta @@ -0,0 +1,35 @@ +fileFormatVersion: 2 +guid: 1db980bd612824d2097f78fd779e6051 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/Android/applovin-max-unity-plugin.aar +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS.meta b/Assets/MaxSdk/AppLovin/Plugins/iOS.meta new file mode 100644 index 0000000..fb615c7 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35602bb97c21644338be36a4331c3874 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/iOS +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h new file mode 100644 index 0000000..debdd3c --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h @@ -0,0 +1,106 @@ +// +// MAUnityAdManager.h +// AppLovin MAX Unity Plugin +// + +#import +#import + +NS_ASSUME_NONNULL_BEGIN +typedef const void *MAUnityRef; +typedef void (*ALUnityBackgroundCallback)(const char* args); + +@interface MAUnityAdManager : NSObject + +- (void)initializeSdkWithConfiguration:(ALSdkInitializationConfiguration *)initConfig andCompletionHandler:(ALSdkInitializationCompletionHandler)completionHandler; + +- (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)bannerPosition; +- (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset; +- (void)loadBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)setBannerBackgroundColorForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier hexColorCode:(nullable NSString *)hexColorCode; +- (void)setBannerPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)startBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)stopBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)setBannerExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setBannerLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; +- (void)setBannerCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)setBannerWidth:(CGFloat)width forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)updateBannerPosition:(nullable NSString *)bannerPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)updateBannerPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)destroyBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)hideBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (NSString *)bannerLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; ++ (CGFloat)adaptiveBannerHeightForWidth:(CGFloat)width; + +- (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)mrecPosition; +- (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset; +- (void)loadMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)setMRecPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)startMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)stopMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifer; +- (void)setMRecExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setMRecLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; +- (void)setMRecCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)destroyMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)hideMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)updateMRecPosition:(nullable NSString *)mrecPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)updateMRecPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (NSString *)mrecLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; + +- (void)loadInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (BOOL)isInterstitialReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData; +- (void)setInterstitialExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setInterstitialLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; + +- (void)loadAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (BOOL)isAppOpenAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData; +- (void)setAppOpenAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setAppOpenAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; + +- (void)loadRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (BOOL)isRewardedAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData; +- (void)setRewardedAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setRewardedAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; + +- (void)loadRewardedInterstitialAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (BOOL)isRewardedInterstitialAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +- (void)showRewardedInterstitialAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData; +- (void)setRewardedInterstitialAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value; +- (void)setRewardedInterstitialAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; + +// Event Tracking +- (void)trackEvent:(nullable NSString *)event parameters:(nullable NSString *)parameters; + +// Ad Info +- (NSString *)adInfoForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; + +// Ad Value +- (NSString *)adValueForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier withKey:(nullable NSString *)key; + +// User Service +- (void)didDismissUserConsentDialog; + +// CMP Service +- (void)showCMPForExistingUser; + +// Utils ++ (NSString *)serializeParameters:(NSDictionary *)dict; ++ (NSDictionary *)deserializeParameters:(nullable NSString *)serialized; + ++ (void)setUnityBackgroundCallback:(ALUnityBackgroundCallback)unityBackgroundCallback; + +/** + * Creates an instance of @c MAUnityAdManager if needed and returns the singleton instance. + */ ++ (instancetype)shared; + +- (instancetype)init NS_UNAVAILABLE; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h.meta b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h.meta new file mode 100644 index 0000000..aef1db5 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h.meta @@ -0,0 +1,115 @@ +fileFormatVersion: 2 +guid: 4209563f82b8a4f7dabf03705ab761c6 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.h +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 0 + Exclude tvOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 1 + settings: + CompileFlags: + FrameworkDependencies: + - first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m new file mode 100644 index 0000000..e724123 --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m @@ -0,0 +1,2090 @@ +// +// MAUnityAdManager.m +// AppLovin MAX Unity Plugin +// + +#import "MAUnityAdManager.h" + +#define KEY_WINDOW [UIApplication sharedApplication].keyWindow +#define DEVICE_SPECIFIC_ADVIEW_AD_FORMAT ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) ? MAAdFormat.leader : MAAdFormat.banner +#define IS_VERTICAL_BANNER_POSITION(_POS) ( [@"center_left" isEqual: adViewPosition] || [@"center_right" isEqual: adViewPosition] ) +#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI) + +#ifdef __cplusplus +extern "C" { +#endif + + extern bool max_unity_should_disable_all_logs(void); // Forward declaration + + // UnityAppController.mm + UIViewController* UnityGetGLViewController(void); + UIWindow* UnityGetMainWindow(void); + + // life cycle management + int UnityIsPaused(void); + void UnityPause(int pause); + + void max_unity_dispatch_on_main_thread(dispatch_block_t block) + { + if ( block ) + { + if ( [NSThread isMainThread] ) + { + block(); + } + else + { + dispatch_async(dispatch_get_main_queue(), block); + } + } + } +#ifdef __cplusplus +} +#endif + +@interface MAUnityAdManager() + +// Parent Fields +@property (nonatomic, weak) ALSdk *sdk; + +// Fullscreen Ad Fields +@property (nonatomic, strong) NSMutableDictionary *interstitials; +@property (nonatomic, strong) NSMutableDictionary *appOpenAds; +@property (nonatomic, strong) NSMutableDictionary *rewardedAds; +@property (nonatomic, strong) NSMutableDictionary *rewardedInterstitialAds; + +// AdView Fields +@property (nonatomic, strong) NSMutableDictionary *adViews; +@property (nonatomic, strong) NSMutableDictionary *adViewAdFormats; +@property (nonatomic, strong) NSMutableDictionary *adViewPositions; +@property (nonatomic, strong) NSMutableDictionary *adViewOffsets; +@property (nonatomic, strong) NSMutableDictionary *adViewWidths; +@property (nonatomic, strong) NSMutableDictionary *verticalAdViewFormats; +@property (nonatomic, strong) NSMutableDictionary *> *adViewConstraints; +@property (nonatomic, strong) NSMutableDictionary *> *adViewExtraParametersToSetAfterCreate; +@property (nonatomic, strong) NSMutableDictionary *> *adViewLocalExtraParametersToSetAfterCreate; +@property (nonatomic, strong) NSMutableDictionary *adViewCustomDataToSetAfterCreate; +@property (nonatomic, strong) NSMutableArray *adUnitIdentifiersToShowAfterCreate; +@property (nonatomic, strong) NSMutableSet *disabledAdaptiveBannerAdUnitIdentifiers; +@property (nonatomic, strong) NSMutableSet *disabledAutoRefreshAdViewAdUnitIdentifiers; +@property (nonatomic, strong) UIView *safeAreaBackground; +@property (nonatomic, strong, nullable) UIColor *publisherBannerBackgroundColor; + +@property (nonatomic, strong) NSMutableDictionary *adInfoDict; +@property (nonatomic, strong) NSObject *adInfoDictLock; + +@property (nonatomic, strong) NSOperationQueue *backgroundCallbackEventsQueue; +@property (nonatomic, assign) BOOL resumeUnityAfterApplicationBecomesActive; + +@end + +// Internal +@interface UIColor (ALUtils) ++ (nullable UIColor *)al_colorWithHexString:(NSString *)hexString; +@end + +@interface NSNumber (ALUtils) ++ (NSNumber *)al_numberWithString:(NSString *)string; +@end + +@interface NSString (ALUtils) +@property (assign, readonly, getter=al_isValidString) BOOL al_validString; +@end + +@interface MAAdFormat (ALUtils) +@property (nonatomic, assign, readonly, getter=isFullscreenAd) BOOL fullscreenAd; +@property (nonatomic, assign, readonly, getter=isAdViewAd) BOOL adViewAd; +@end + +@implementation MAUnityAdManager +static NSString *const SDK_TAG = @"AppLovinSdk"; +static NSString *const TAG = @"MAUnityAdManager"; +static NSString *const DEFAULT_AD_VIEW_POSITION = @"top_left"; +static ALUnityBackgroundCallback backgroundCallback; + +#pragma mark - Initialization + +- (instancetype)init +{ + self = [super init]; + if ( self ) + { + self.interstitials = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.appOpenAds = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.rewardedAds = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.rewardedInterstitialAds = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViews = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewAdFormats = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewPositions = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewOffsets = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewWidths = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.verticalAdViewFormats = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewConstraints = [NSMutableDictionary dictionaryWithCapacity: 2]; + self.adViewExtraParametersToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1]; + self.adViewLocalExtraParametersToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1]; + self.adViewCustomDataToSetAfterCreate = [NSMutableDictionary dictionaryWithCapacity: 1]; + self.adUnitIdentifiersToShowAfterCreate = [NSMutableArray arrayWithCapacity: 2]; + self.disabledAdaptiveBannerAdUnitIdentifiers = [NSMutableSet setWithCapacity: 2]; + self.disabledAutoRefreshAdViewAdUnitIdentifiers = [NSMutableSet setWithCapacity: 2]; + self.adInfoDict = [NSMutableDictionary dictionary]; + self.adInfoDictLock = [[NSObject alloc] init]; + + self.backgroundCallbackEventsQueue = [[NSOperationQueue alloc] init]; + self.backgroundCallbackEventsQueue.maxConcurrentOperationCount = 1; + + max_unity_dispatch_on_main_thread(^{ + self.safeAreaBackground = [[UIView alloc] init]; + self.safeAreaBackground.hidden = YES; + self.safeAreaBackground.backgroundColor = UIColor.clearColor; + self.safeAreaBackground.translatesAutoresizingMaskIntoConstraints = NO; + self.safeAreaBackground.userInteractionEnabled = NO; + + UIViewController *rootViewController = [self unityViewController]; + [rootViewController.view addSubview: self.safeAreaBackground]; + }); + + // Enable orientation change listener, so that the position can be updated for vertical banners. + [[NSNotificationCenter defaultCenter] addObserverForName: UIDeviceOrientationDidChangeNotification + object: nil + queue: [NSOperationQueue mainQueue] + usingBlock:^(NSNotification *notification) { + + for ( NSString *adUnitIdentifier in self.verticalAdViewFormats ) + { + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: self.verticalAdViewFormats[adUnitIdentifier]]; + } + }]; + + [[NSNotificationCenter defaultCenter] addObserver: self + selector: @selector(applicationPaused:) + name: UIApplicationDidEnterBackgroundNotification + object: nil]; + + [[NSNotificationCenter defaultCenter] addObserver: self + selector: @selector(applicationResumed:) + name: UIApplicationDidBecomeActiveNotification + object: nil]; + + [[NSNotificationCenter defaultCenter] addObserverForName: UIApplicationDidBecomeActiveNotification + object: nil + queue: [NSOperationQueue mainQueue] + usingBlock:^(NSNotification *notification) { + +#if !IS_TEST_APP + if ( self.resumeUnityAfterApplicationBecomesActive && UnityIsPaused() ) + { + UnityPause(NO); + } +#endif + + self.backgroundCallbackEventsQueue.suspended = NO; + }]; + } + return self; +} + ++ (MAUnityAdManager *)shared +{ + static dispatch_once_t token; + static MAUnityAdManager *shared; + dispatch_once(&token, ^{ + shared = [[MAUnityAdManager alloc] init]; + }); + return shared; +} + ++ (void)setUnityBackgroundCallback:(ALUnityBackgroundCallback)unityBackgroundCallback +{ + backgroundCallback = unityBackgroundCallback; +} + +#pragma mark - Plugin Initialization + +- (void)initializeSdkWithConfiguration:(ALSdkInitializationConfiguration *)initConfig andCompletionHandler:(ALSdkInitializationCompletionHandler)completionHandler; +{ + self.sdk = [ALSdk shared]; + [self.sdk initializeWithConfiguration: initConfig completionHandler:^(ALSdkConfiguration *configuration) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + // Note: internal state should be updated first + completionHandler( configuration ); + + NSString *consentFlowUserGeographyStr = @(configuration.consentFlowUserGeography).stringValue; + NSString *consentDialogStateStr = @(configuration.consentDialogState).stringValue; + NSString *appTrackingStatus = @(configuration.appTrackingTransparencyStatus).stringValue; // Deliberately name it `appTrackingStatus` to be a bit more generic (in case Android introduces a similar concept) + [self forwardUnityEventWithArgs: @{@"name" : @"OnSdkInitializedEvent", + @"consentFlowUserGeography" : consentFlowUserGeographyStr, + @"consentDialogState" : consentDialogStateStr, + @"countryCode" : configuration.countryCode, + @"appTrackingStatus" : appTrackingStatus, + @"isSuccessfullyInitialized" : @([self.sdk isInitialized]), + @"isTestModeEnabled" : @([configuration isTestModeEnabled])}]; + }); + }]; +} + +#pragma mark - Banners + +- (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)bannerPosition +{ + [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] atPosition: bannerPosition withOffset: CGPointZero]; +} + +- (void)createBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset +{ + [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] atPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset)]; +} + +- (void)loadBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self loadAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)setBannerBackgroundColorForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier hexColorCode:(nullable NSString *)hexColorCode +{ + [self setAdViewBackgroundColorForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] hexColorCode: hexColorCode]; +} + +- (void)setBannerPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self setAdViewPlacement: placement forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)startBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self startAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)stopBannerAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self stopAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)setBannerWidth:(CGFloat)width forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self setAdViewWidth: width forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)updateBannerPosition:(nullable NSString *)bannerPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self updateAdViewPosition: bannerPosition withOffset: CGPointZero forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)updateBannerPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self updateAdViewPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)setBannerExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + [self setAdViewExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] key: key value: value]; +} + +- (void)setBannerLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + [self setAdViewLocalExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier] key: key value: value]; +} + +- (void)setBannerCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self setAdViewCustomData: customData forAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)showBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)hideBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self hideAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (NSString *)bannerLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + return [self adViewLayoutForAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + +- (void)destroyBannerWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self destroyAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: [self adViewAdFormatForAdUnitIdentifier: adUnitIdentifier]]; +} + ++ (CGFloat)adaptiveBannerHeightForWidth:(CGFloat)width +{ + return [DEVICE_SPECIFIC_ADVIEW_AD_FORMAT adaptiveSizeForWidth: width].height; +} + +#pragma mark - MRECs + +- (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier atPosition:(nullable NSString *)mrecPosition +{ + [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec atPosition: mrecPosition withOffset: CGPointZero]; +} + +- (void)createMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier x:(CGFloat)xOffset y:(CGFloat)yOffset +{ + [self createAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec atPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset)]; +} + +- (void)loadMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self loadAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)setMRecPlacement:(nullable NSString *)placement forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self setAdViewPlacement: placement forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)startMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self startAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)stopMRecAutoRefreshForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self stopAdViewAutoRefreshForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)updateMRecPosition:(nullable NSString *)mrecPosition forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self updateAdViewPosition: mrecPosition withOffset: CGPointZero forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)updateMRecPosition:(CGFloat)xOffset y:(CGFloat)yOffset forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self updateAdViewPosition: DEFAULT_AD_VIEW_POSITION withOffset: CGPointMake(xOffset, yOffset) forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)setMRecExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + [self setAdViewExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec key: key value: value]; +} + +- (void)setMRecLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + [self setAdViewLocalExtraParameterForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec key: key value: value]; +} + +- (void)setMRecCustomData:(nullable NSString *)customData forAdUnitIdentifier:(nullable NSString *)adUnitIdentifier; +{ + [self setAdViewCustomData: customData forAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)showMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)destroyMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self destroyAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (void)hideMRecWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + [self hideAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +- (NSString *)mrecLayoutForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + return [self adViewLayoutForAdUnitIdentifier: adUnitIdentifier adFormat: MAAdFormat.mrec]; +} + +#pragma mark - Interstitials + +- (void)loadInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier]; + [interstitial loadAd]; +} + +- (BOOL)isInterstitialReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier]; + return [interstitial isReady]; +} + +- (void)showInterstitialWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData +{ + MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier]; + [interstitial showAdForPlacement: placement customData: customData]; +} + +- (void)setInterstitialExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier]; + [interstitial setExtraParameterForKey: key value: value]; +} + +- (void)setInterstitialLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + MAInterstitialAd *interstitial = [self retrieveInterstitialForAdUnitIdentifier: adUnitIdentifier]; + [interstitial setLocalExtraParameterForKey: key value: value]; +} + +#pragma mark - App Open Ads + +- (void)loadAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier]; + [appOpenAd loadAd]; +} + +- (BOOL)isAppOpenAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier]; + return [appOpenAd isReady]; +} + +- (void)showAppOpenAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData +{ + MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier]; + [appOpenAd showAdForPlacement: placement customData: customData]; +} + +- (void)setAppOpenAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier]; + [appOpenAd setExtraParameterForKey: key value: value]; +} + +- (void)setAppOpenAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + MAAppOpenAd *appOpenAd = [self retrieveAppOpenAdForAdUnitIdentifier: adUnitIdentifier]; + [appOpenAd setLocalExtraParameterForKey: key value: value]; +} + +#pragma mark - Rewarded + +- (void)loadRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedAd loadAd]; +} + +- (BOOL)isRewardedAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier]; + return [rewardedAd isReady]; +} + +- (void)showRewardedAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData +{ + MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedAd showAdForPlacement: placement customData: customData]; +} + +- (void)setRewardedAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedAd setExtraParameterForKey: key value: value]; +} + +- (void)setRewardedAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value; +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + MARewardedAd *rewardedAd = [self retrieveRewardedAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedAd setLocalExtraParameterForKey: key value: value]; +} + +#pragma mark - Rewarded Interstitials + +- (void)loadRewardedInterstitialAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MARewardedInterstitialAd *rewardedInterstitialAd = [self retrieveRewardedInterstitialAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedInterstitialAd loadAd]; +} + +- (BOOL)isRewardedInterstitialAdReadyWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + MARewardedInterstitialAd *rewardedInterstitialAd = [self retrieveRewardedInterstitialAdForAdUnitIdentifier: adUnitIdentifier]; + return [rewardedInterstitialAd isReady]; +} + +- (void)showRewardedInterstitialAdWithAdUnitIdentifier:(nullable NSString *)adUnitIdentifier placement:(nullable NSString *)placement customData:(nullable NSString *)customData +{ + MARewardedInterstitialAd *rewardedInterstitialAd = [self retrieveRewardedInterstitialAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedInterstitialAd showAdForPlacement: placement customData: customData]; +} + +- (void)setRewardedInterstitialAdExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable NSString *)value +{ + MARewardedInterstitialAd *rewardedInterstitialAd = [self retrieveRewardedInterstitialAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedInterstitialAd setExtraParameterForKey: key value: value]; +} + +- (void)setRewardedInterstitialAdLocalExtraParameterForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier key:(nullable NSString *)key value:(nullable id)value +{ + if ( !key ) + { + [self log: @"Failed to set local extra parameter: No key specified"]; + return; + } + + MARewardedInterstitialAd *rewardedInterstitialAd = [self retrieveRewardedInterstitialAdForAdUnitIdentifier: adUnitIdentifier]; + [rewardedInterstitialAd setLocalExtraParameterForKey: key value: value]; +} + +#pragma mark - Event Tracking + +- (void)trackEvent:(nullable NSString *)event parameters:(nullable NSString *)parameters +{ + NSDictionary *deserializedParameters = [MAUnityAdManager deserializeParameters: parameters]; + [self.sdk.eventService trackEvent: event parameters: deserializedParameters]; +} + +#pragma mark - Ad Info + +- (NSString *)adInfoForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier +{ + if ( ![adUnitIdentifier al_isValidString] ) return @""; + + MAAd *ad = [self adWithAdUnitIdentifier: adUnitIdentifier]; + if ( !ad ) return @""; + + return [MAUnityAdManager serializeParameters: [self adInfoForAd: ad]]; +} + +- (NSDictionary *)adInfoForAd:(MAAd *)ad +{ + return @{@"adUnitId" : ad.adUnitIdentifier, + @"adFormat" : ad.format.label, + @"networkName" : ad.networkName, + @"networkPlacement" : ad.networkPlacement, + @"creativeId" : ad.creativeIdentifier ?: @"", + @"placement" : ad.placement ?: @"", + @"revenue" : [@(ad.revenue) stringValue], + @"revenuePrecision" : ad.revenuePrecision, + @"waterfallInfo" : [self createAdWaterfallInfo: ad.waterfall], + @"latencyMillis" : [self requestLatencyMillisFromRequestLatency: ad.requestLatency], + @"dspName" : ad.DSPName ?: @""}; +} + +#pragma mark - Waterfall Information + +- (NSDictionary *)createAdWaterfallInfo:(MAAdWaterfallInfo *)waterfallInfo +{ + NSMutableDictionary *waterfallInfoDict = [NSMutableDictionary dictionary]; + if ( !waterfallInfo ) return waterfallInfoDict; + + waterfallInfoDict[@"name"] = waterfallInfo.name; + waterfallInfoDict[@"testName"] = waterfallInfo.testName; + + NSMutableArray *> *networkResponsesArray = [NSMutableArray arrayWithCapacity: waterfallInfo.networkResponses.count]; + for ( MANetworkResponseInfo *response in waterfallInfo.networkResponses ) + { + [networkResponsesArray addObject: [self createNetworkResponseInfo: response]]; + } + + waterfallInfoDict[@"networkResponses"] = networkResponsesArray; + waterfallInfoDict[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: waterfallInfo.latency]; + + return waterfallInfoDict; +} + +- (NSDictionary *)createNetworkResponseInfo:(MANetworkResponseInfo *)response +{ + NSMutableDictionary *networkResponseDict = [NSMutableDictionary dictionary]; + + networkResponseDict[@"adLoadState"] = @(response.adLoadState).stringValue; + + MAMediatedNetworkInfo *mediatedNetworkInfo = response.mediatedNetwork; + if ( mediatedNetworkInfo ) + { + NSMutableDictionary *networkInfoObject = [NSMutableDictionary dictionary]; + networkInfoObject[@"name"] = response.mediatedNetwork.name; + networkInfoObject[@"adapterClassName"] = response.mediatedNetwork.adapterClassName; + networkInfoObject[@"adapterVersion"] = response.mediatedNetwork.adapterVersion; + networkInfoObject[@"sdkVersion"] = response.mediatedNetwork.sdkVersion; + + networkResponseDict[@"mediatedNetwork"] = networkInfoObject; + } + + networkResponseDict[@"credentials"] = response.credentials; + networkResponseDict[@"isBidding"] = @([response isBidding]); + + MAError *error = response.error; + if ( error ) + { + NSMutableDictionary *errorObject = [NSMutableDictionary dictionary]; + errorObject[@"errorMessage"] = error.message; + errorObject[@"adLoadFailure"] = error.adLoadFailureInfo; + errorObject[@"errorCode"] = @(error.code).stringValue; + errorObject[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: error.requestLatency]; + + networkResponseDict[@"error"] = errorObject; + } + + networkResponseDict[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: response.latency]; + + return networkResponseDict; +} + +#pragma mark - Ad Value + +- (NSString *)adValueForAdUnitIdentifier:(nullable NSString *)adUnitIdentifier withKey:(nullable NSString *)key +{ + if ( adUnitIdentifier == nil || adUnitIdentifier.length == 0 ) return @""; + if ( key == nil || key.length == 0 ) return @""; + + MAAd *ad = [self adWithAdUnitIdentifier: adUnitIdentifier]; + if ( !ad ) return @""; + + return [ad adValueForKey: key]; +} + +#pragma mark - Ad Callbacks + +- (void)didLoadAd:(MAAd *)ad +{ + NSString *name; + MAAdFormat *adFormat = ad.format; + if ( [adFormat isAdViewAd] ) + { + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: ad.adUnitIdentifier adFormat: adFormat]; + // An ad is now being shown, enable user interaction. + adView.userInteractionEnabled = YES; + + if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdLoadedEvent"; + } + else + { + name = @"OnBannerAdLoadedEvent"; + } + [self positionAdViewForAd: ad]; + + // Do not auto-refresh by default if the ad view is not showing yet (e.g. first load during app launch and publisher does not automatically show banner upon load success) + // We will resume auto-refresh in -[MAUnityAdManager showBannerWithAdUnitIdentifier:]. + if ( adView && [adView isHidden] ) + { + [adView stopAutoRefresh]; + } + } + else if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialLoadedEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdLoadedEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdLoadedEvent"; + } + else if ( MAAdFormat.rewardedInterstitial == adFormat ) + { + name = @"OnRewardedInterstitialAdLoadedEvent"; + } + else + { + [self logInvalidAdFormat: adFormat]; + return; + } + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + @synchronized ( self.adInfoDictLock ) + { + self.adInfoDict[ad.adUnitIdentifier] = ad; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + if ( !adUnitIdentifier ) + { + [self log: @"adUnitIdentifier cannot be nil from %@", [NSThread callStackSymbols]]; + return; + } + + NSString *name; + if ( self.adViews[adUnitIdentifier] ) + { + MAAdFormat *adFormat = self.adViewAdFormats[adUnitIdentifier]; + if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdLoadFailedEvent"; + } + else + { + name = @"OnBannerAdLoadFailedEvent"; + } + } + else if ( self.interstitials[adUnitIdentifier] ) + { + name = @"OnInterstitialLoadFailedEvent"; + } + else if ( self.appOpenAds[adUnitIdentifier] ) + { + name = @"OnAppOpenAdLoadFailedEvent"; + } + else if ( self.rewardedAds[adUnitIdentifier] ) + { + name = @"OnRewardedAdLoadFailedEvent"; + } + else if ( self.rewardedInterstitialAds[adUnitIdentifier] ) + { + name = @"OnRewardedInterstitialAdLoadFailedEvent"; + } + else + { + [self log: @"invalid adUnitId from %@", [NSThread callStackSymbols]]; + return; + } + + @synchronized ( self.adInfoDictLock ) + { + [self.adInfoDict removeObjectForKey: adUnitIdentifier]; + } + + [self forwardUnityEventWithArgs: @{@"name" : name, + @"adUnitId" : adUnitIdentifier, + @"errorCode" : [@(error.code) stringValue], + @"errorMessage" : error.message, + @"waterfallInfo" : [self createAdWaterfallInfo: error.waterfall], + @"adLoadFailureInfo" : error.adLoadFailureInfo ?: @"", + @"latencyMillis" : [self requestLatencyMillisFromRequestLatency: error.requestLatency]}]; + }); +} + +- (void)didClickAd:(MAAd *)ad +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + MAAdFormat *adFormat = ad.format; + if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat ) + { + name = @"OnBannerAdClickedEvent"; + } + else if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdClickedEvent"; + } + else if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialClickedEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdClickedEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdClickedEvent"; + } + else if ( MAAdFormat.rewardedInterstitial == adFormat ) + { + name = @"OnRewardedInterstitialAdClickedEvent"; + } + else + { + [self logInvalidAdFormat: adFormat]; + return; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didDisplayAd:(MAAd *)ad +{ + // BMLs do not support [DISPLAY] events in Unity + MAAdFormat *adFormat = ad.format; + if ( ![adFormat isFullscreenAd] ) return; + +#if !IS_TEST_APP + // UnityPause needs to be called on the main thread. + UnityPause(YES); +#endif + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialDisplayedEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdDisplayedEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdDisplayedEvent"; + } + else // rewarded inters + { + name = @"OnRewardedInterstitialAdDisplayedEvent"; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + // BMLs do not support [DISPLAY] events in Unity + MAAdFormat *adFormat = ad.format; + if ( ![adFormat isFullscreenAd] ) return; + + NSString *name; + if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialAdFailedToDisplayEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdFailedToDisplayEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdFailedToDisplayEvent"; + } + else // rewarded inters + { + name = @"OnRewardedInterstitialAdFailedToDisplayEvent"; + } + + NSMutableDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + args[@"errorCode"] = [@(error.code) stringValue]; + args[@"errorMessage"] = error.message; + args[@"mediatedNetworkErrorCode"] = [@(error.mediatedNetworkErrorCode) stringValue]; + args[@"mediatedNetworkErrorMessage"] = error.mediatedNetworkErrorMessage; + args[@"waterfallInfo"] = [self createAdWaterfallInfo: error.waterfall]; + args[@"latencyMillis"] = [self requestLatencyMillisFromRequestLatency: error.requestLatency]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didHideAd:(MAAd *)ad +{ + // BMLs do not support [HIDDEN] events in Unity + MAAdFormat *adFormat = ad.format; + if ( ![adFormat isFullscreenAd] ) return; + +#if !IS_TEST_APP + extern bool _didResignActive; + if ( _didResignActive ) + { + // If the application is not active, we should wait until application becomes active to resume unity. + self.resumeUnityAfterApplicationBecomesActive = YES; + } + else + { + // UnityPause needs to be called on the main thread. + UnityPause(NO); + } +#endif + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialHiddenEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdHiddenEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdHiddenEvent"; + } + else // rewarded inters + { + name = @"OnRewardedInterstitialAdHiddenEvent"; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didExpandAd:(MAAd *)ad +{ + MAAdFormat *adFormat = ad.format; + if ( ![adFormat isAdViewAd] ) + { + [self logInvalidAdFormat: adFormat]; + return; + } + +#if !IS_TEST_APP + // UnityPause needs to be called on the main thread. + UnityPause(YES); +#endif + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdExpandedEvent"; + } + else + { + name = @"OnBannerAdExpandedEvent"; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didCollapseAd:(MAAd *)ad +{ + MAAdFormat *adFormat = ad.format; + if ( ![adFormat isAdViewAd] ) + { + [self logInvalidAdFormat: adFormat]; + return; + } + +#if !IS_TEST_APP + extern bool _didResignActive; + if ( _didResignActive ) + { + // If the application is not active, we should wait until application becomes active to resume unity. + self.resumeUnityAfterApplicationBecomesActive = YES; + } + else + { + // UnityPause needs to be called on the main thread. + UnityPause(NO); + } +#endif + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdCollapsedEvent"; + } + else + { + name = @"OnBannerAdCollapsedEvent"; + } + + NSDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + MAAdFormat *adFormat = ad.format; + if ( adFormat != MAAdFormat.rewarded && adFormat != MAAdFormat.rewardedInterstitial ) + { + [self logInvalidAdFormat: adFormat]; + return; + } + + NSString *rewardLabel = reward ? reward.label : @""; + NSInteger rewardAmountInt = reward ? reward.amount : 0; + NSString *rewardAmount = [@(rewardAmountInt) stringValue]; + + NSString *name = (adFormat == MAAdFormat.rewarded) ? @"OnRewardedAdReceivedRewardEvent" : @"OnRewardedInterstitialAdReceivedRewardEvent"; + + + NSMutableDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + args[@"rewardLabel"] = rewardLabel; + args[@"rewardAmount"] = rewardAmount; + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didPayRevenueForAd:(MAAd *)ad +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + MAAdFormat *adFormat = ad.format; + if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat ) + { + name = @"OnBannerAdRevenuePaidEvent"; + } + else if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdRevenuePaidEvent"; + } + else if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialAdRevenuePaidEvent"; + } + else if ( MAAdFormat.appOpen == adFormat ) + { + name = @"OnAppOpenAdRevenuePaidEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdRevenuePaidEvent"; + } + else if ( MAAdFormat.rewardedInterstitial == adFormat ) + { + name = @"OnRewardedInterstitialAdRevenuePaidEvent"; + } + else + { + [self logInvalidAdFormat: adFormat]; + return; + } + + NSMutableDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + args[@"keepInBackground"] = @([adFormat isFullscreenAd]); + [self forwardUnityEventWithArgs: args]; + }); +} + +- (void)didGenerateCreativeIdentifier:(NSString *)creativeIdentifier forAd:(MAAd *)ad +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + NSString *name; + MAAdFormat *adFormat = ad.format; + if ( MAAdFormat.banner == adFormat || MAAdFormat.leader == adFormat ) + { + name = @"OnBannerAdReviewCreativeIdGeneratedEvent"; + } + else if ( MAAdFormat.mrec == adFormat ) + { + name = @"OnMRecAdReviewCreativeIdGeneratedEvent"; + } + else if ( MAAdFormat.interstitial == adFormat ) + { + name = @"OnInterstitialAdReviewCreativeIdGeneratedEvent"; + } + else if ( MAAdFormat.rewarded == adFormat ) + { + name = @"OnRewardedAdReviewCreativeIdGeneratedEvent"; + } + else if ( MAAdFormat.rewardedInterstitial == adFormat ) + { + name = @"OnRewardedInterstitialAdReviewCreativeIdGeneratedEvent"; + } + else + { + [self logInvalidAdFormat: adFormat]; + return; + } + + NSMutableDictionary *args = [self defaultAdEventParametersForName: name withAd: ad]; + args[@"adReviewCreativeId"] = creativeIdentifier; + args[@"keepInBackground"] = @([adFormat isFullscreenAd]); + + // Forward the event in background for fullscreen ads so that the user gets the callback even while the ad is playing. + [self forwardUnityEventWithArgs: args]; + }); +} + +- (NSMutableDictionary *)defaultAdEventParametersForName:(NSString *)name withAd:(MAAd *)ad +{ + NSMutableDictionary *args = [[self adInfoForAd: ad] mutableCopy]; + args[@"name"] = name; + + return args; +} + +#pragma mark - Internal Methods + +- (void)createAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat atPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Creating %@ with ad unit identifier \"%@\" and position: \"%@\"", adFormat, adUnitIdentifier, adViewPosition]; + + if ( self.adViews[adUnitIdentifier] ) + { + [self log: @"Trying to create a %@ that was already created. This will cause the current ad to be hidden.", adFormat.label]; + } + + // Retrieve ad view from the map + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat atPosition: adViewPosition withOffset: offset]; + adView.hidden = YES; + self.safeAreaBackground.hidden = YES; + + // Position ad view immediately so if publisher sets color before ad loads, it will not be the size of the screen + self.adViewAdFormats[adUnitIdentifier] = adFormat; + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + + NSDictionary *extraParameters = self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier]; + + // Enable adaptive banners by default for banners and leaders. + if ( [adFormat isBannerOrLeaderAd] ) + { + // Check if there is already a pending setting for adaptive banners. If not, enable them. + if ( !extraParameters[@"adaptive_banner"] ) + { + [adView setExtraParameterForKey: @"adaptive_banner" value: @"true"]; + } + } + + // Handle initial extra parameters if publisher sets it before creating ad view + if ( extraParameters ) + { + for ( NSString *key in extraParameters ) + { + [adView setExtraParameterForKey: key value: extraParameters[key]]; + + [self handleExtraParameterChangesIfNeededForAdUnitIdentifier: adUnitIdentifier + adFormat: adFormat + key: key + value: extraParameters[key]]; + } + + [self.adViewExtraParametersToSetAfterCreate removeObjectForKey: adUnitIdentifier]; + } + + // Handle initial local extra parameters if publisher sets it before creating ad view + if ( self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier] ) + { + NSDictionary *localExtraParameters = self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier]; + for ( NSString *key in localExtraParameters ) + { + [adView setLocalExtraParameterForKey: key value: localExtraParameters[key]]; + } + + [self.adViewLocalExtraParametersToSetAfterCreate removeObjectForKey: adUnitIdentifier]; + } + + // Handle initial custom data if publisher sets it before creating ad view + if ( self.adViewCustomDataToSetAfterCreate[adUnitIdentifier] ) + { + NSString *customData = self.adViewCustomDataToSetAfterCreate[adUnitIdentifier]; + adView.customData = customData; + + [self.adViewCustomDataToSetAfterCreate removeObjectForKey: adUnitIdentifier]; + } + + [adView loadAd]; + + // Disable auto-refresh if publisher sets it before creating the ad view. + if ( [self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] ) + { + [adView stopAutoRefresh]; + } + + // The publisher may have requested to show the banner before it was created. Now that the banner is created, show it. + if ( [self.adUnitIdentifiersToShowAfterCreate containsObject: adUnitIdentifier] ) + { + [self showAdViewWithAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + [self.adUnitIdentifiersToShowAfterCreate removeObject: adUnitIdentifier]; + } + }); +} + +- (void)loadAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( !adView ) + { + [self log: @"%@ does not exist for ad unit identifier \"%@\".", adFormat.label, adUnitIdentifier]; + return; + } + + if ( ![self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] ) + { + if ( [adView isHidden] ) + { + [self log: @"Auto-refresh will resume when the %@ ad is shown. You should only call LoadBanner() or LoadMRec() if you explicitly pause auto-refresh and want to manually load an ad.", adFormat.label]; + return; + } + + [self log: @"You must stop auto-refresh if you want to manually load %@ ads.", adFormat.label]; + return; + } + + [adView loadAd]; + }); +} + +- (void)setAdViewBackgroundColorForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat hexColorCode:(NSString *)hexColorCode +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Setting %@ with ad unit identifier \"%@\" to color: \"%@\"", adFormat, adUnitIdentifier, hexColorCode]; + + // In some cases, black color may get redrawn on each frame update, resulting in an undesired flicker + NSString *hexColorCodeToUse = [hexColorCode containsString: @"FF000000"] ? @"FF000001" : hexColorCode; + UIColor *convertedColor = [UIColor al_colorWithHexString: hexColorCodeToUse]; + + MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + self.publisherBannerBackgroundColor = convertedColor; + self.safeAreaBackground.backgroundColor = view.backgroundColor = convertedColor; + + // Position adView to ensure logic that depends on background color is properly run + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + }); +} + +- (void)setAdViewPlacement:(nullable NSString *)placement forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Setting placement \"%@\" for \"%@\" with ad unit identifier \"%@\"", placement, adFormat, adUnitIdentifier]; + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + adView.placement = placement; + }); +} + +- (void)startAdViewAutoRefreshForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Starting %@ auto refresh for ad unit identifier \"%@\"", adFormat.label, adUnitIdentifier]; + + [self.disabledAutoRefreshAdViewAdUnitIdentifiers removeObject: adUnitIdentifier]; + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( !adView ) + { + [self log: @"%@ does not exist for ad unit identifier %@.", adFormat.label, adUnitIdentifier]; + return; + } + + [adView startAutoRefresh]; + }); +} + +- (void)stopAdViewAutoRefreshForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Stopping %@ auto refresh for ad unit identifier \"%@\"", adFormat.label, adUnitIdentifier]; + + [self.disabledAutoRefreshAdViewAdUnitIdentifiers addObject: adUnitIdentifier]; + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( !adView ) + { + [self log: @"%@ does not exist for ad unit identifier %@.", adFormat.label, adUnitIdentifier]; + return; + } + + [adView stopAutoRefresh]; + }); +} + +- (void)setAdViewWidth:(CGFloat)width forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Setting width %f for \"%@\" with ad unit identifier \"%@\"", width, adFormat, adUnitIdentifier]; + + BOOL isBannerOrLeader = adFormat.isBannerOrLeaderAd; + + // Banners and leaders need to be at least 320pts wide. + CGFloat minWidth = isBannerOrLeader ? MAAdFormat.banner.size.width : adFormat.size.width; + if ( width < minWidth ) + { + [self log: @"The provided width: %f is smaller than the minimum required width: %f for ad format: %@. Automatically setting width to %f.", width, minWidth, adFormat, minWidth]; + } + + CGFloat widthToSet = MAX( minWidth, width ); + self.adViewWidths[adUnitIdentifier] = @(widthToSet); + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + }); +} + +- (void)updateAdViewPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + self.adViewPositions[adUnitIdentifier] = adViewPosition; + self.adViewOffsets[adUnitIdentifier] = [NSValue valueWithCGPoint: offset]; + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + }); +} + +- (void)setAdViewExtraParameterForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable NSString *)value +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Setting %@ extra with key: \"%@\" value: \"%@\"", adFormat, key, value]; + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( adView ) + { + [adView setExtraParameterForKey: key value: value]; + } + else + { + [self log: @"%@ does not exist for ad unit identifier \"%@\". Saving extra parameter to be set when it is created.", adFormat, adUnitIdentifier]; + + // The adView has not yet been created. Store the extra parameters, so that they can be added once the banner has been created. + NSMutableDictionary *extraParameters = self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier]; + if ( !extraParameters ) + { + extraParameters = [NSMutableDictionary dictionaryWithCapacity: 1]; + self.adViewExtraParametersToSetAfterCreate[adUnitIdentifier] = extraParameters; + } + + extraParameters[key] = value; + } + + // Certain extra parameters need to be handled immediately + [self handleExtraParameterChangesIfNeededForAdUnitIdentifier: adUnitIdentifier + adFormat: adFormat + key: key + value: value]; + }); +} + +- (void)setAdViewLocalExtraParameterForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable id)value +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Setting %@ local extra with key: \"%@\" value: \"%@\"", adFormat, key, value]; + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( adView ) + { + [adView setLocalExtraParameterForKey: key value: value]; + } + else + { + [self log: @"%@ does not exist for ad unit identifier \"%@\". Saving local extra parameter to be set when it is created.", adFormat, adUnitIdentifier]; + + // The adView has not yet been created. Store the loca extra parameters, so that they can be added once the adview has been created. + NSMutableDictionary *localExtraParameters = self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier]; + if ( !localExtraParameters ) + { + localExtraParameters = [NSMutableDictionary dictionaryWithCapacity: 1]; + self.adViewLocalExtraParametersToSetAfterCreate[adUnitIdentifier] = localExtraParameters; + } + + localExtraParameters[key] = value; + } + }); +} + +- (void)setAdViewCustomData:(nullable NSString *)customData forAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( adView ) + { + adView.customData = customData; + } + else + { + [self log: @"%@ does not exist for ad unit identifier %@. Saving custom data to be set when it is created.", adFormat, adUnitIdentifier]; + + // The adView has not yet been created. Store the custom data, so that they can be added once the AdView has been created. + self.adViewCustomDataToSetAfterCreate[adUnitIdentifier] = customData; + } + }); +} + +- (void)handleExtraParameterChangesIfNeededForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat key:(NSString *)key value:(nullable NSString *)value +{ + if ( MAAdFormat.mrec != adFormat ) + { + if ( [@"force_banner" isEqualToString: key] ) + { + BOOL shouldForceBanner = [NSNumber al_numberWithString: value].boolValue; + MAAdFormat *forcedAdFormat = shouldForceBanner ? MAAdFormat.banner : DEVICE_SPECIFIC_ADVIEW_AD_FORMAT; + + self.adViewAdFormats[adUnitIdentifier] = forcedAdFormat; + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: forcedAdFormat]; + } + else if ( [@"adaptive_banner" isEqualToString: key] ) + { + BOOL shouldUseAdaptiveBanner = [NSNumber al_numberWithString: value].boolValue; + if ( shouldUseAdaptiveBanner ) + { + [self.disabledAdaptiveBannerAdUnitIdentifiers removeObject: adUnitIdentifier]; + } + else + { + [self.disabledAdaptiveBannerAdUnitIdentifiers addObject: adUnitIdentifier]; + } + + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + } + } +} + +- (void)showAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Showing %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier]; + + MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( !view ) + { + [self log: @"%@ does not exist for ad unit identifier %@.", adFormat, adUnitIdentifier]; + + // The adView has not yet been created. Store the ad unit ID, so that it can be displayed once the banner has been created. + [self.adUnitIdentifiersToShowAfterCreate addObject: adUnitIdentifier]; + } + else + { + // Check edge case where ad may be detatched from view controller + if ( !view.window.rootViewController ) + { + [self log: @"%@ missing view controller - re-attaching to %@...", adFormat, [self unityViewController]]; + + UIViewController *rootViewController = [self unityViewController]; + [rootViewController.view addSubview: view]; + + [self positionAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + } + } + + self.safeAreaBackground.hidden = NO; + view.hidden = NO; + + if ( ![self.disabledAutoRefreshAdViewAdUnitIdentifiers containsObject: adUnitIdentifier] ) + { + [view startAutoRefresh]; + } + }); +} + +- (void)hideAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Hiding %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier]; + [self.adUnitIdentifiersToShowAfterCreate removeObject: adUnitIdentifier]; + + MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + view.hidden = YES; + self.safeAreaBackground.hidden = YES; + + [view stopAutoRefresh]; + }); +} + +- (NSString *)adViewLayoutForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + [self log: @"Getting %@ position with ad unit identifier \"%@\"", adFormat, adUnitIdentifier]; + + MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + if ( !view ) + { + [self log: @"%@ does not exist for ad unit identifier %@", adFormat, adUnitIdentifier]; + + return @""; + } + + CGRect adViewFrame = view.frame; + return [MAUnityAdManager serializeParameters: @{@"origin_x" : [NSString stringWithFormat: @"%f", adViewFrame.origin.x], + @"origin_y" : [NSString stringWithFormat: @"%f", adViewFrame.origin.y], + @"width" : [NSString stringWithFormat: @"%f", CGRectGetWidth(adViewFrame)], + @"height" : [NSString stringWithFormat: @"%f", CGRectGetHeight(adViewFrame)]}]; +} + +- (void)destroyAdViewWithAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + [self log: @"Destroying %@ with ad unit identifier \"%@\"", adFormat, adUnitIdentifier]; + + MAAdView *view = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + view.delegate = nil; + view.revenueDelegate = nil; + view.adReviewDelegate = nil; + + [view removeFromSuperview]; + + [self.adViews removeObjectForKey: adUnitIdentifier]; + [self.adViewAdFormats removeObjectForKey: adUnitIdentifier]; + [self.adViewPositions removeObjectForKey: adUnitIdentifier]; + [self.adViewOffsets removeObjectForKey: adUnitIdentifier]; + [self.adViewWidths removeObjectForKey: adUnitIdentifier]; + [self.verticalAdViewFormats removeObjectForKey: adUnitIdentifier]; + [self.disabledAdaptiveBannerAdUnitIdentifiers removeObject: adUnitIdentifier]; + }); +} + +- (void)logInvalidAdFormat:(MAAdFormat *)adFormat +{ + [self log: @"invalid ad format: %@, from %@", adFormat, [NSThread callStackSymbols]]; +} + +- (void)log:(NSString *)format, ... +{ + if (max_unity_should_disable_all_logs()) return; + + va_list valist; + va_start(valist, format); + NSString *message = [[NSString alloc] initWithFormat: format arguments: valist]; + va_end(valist); + + NSLog(@"[%@] [%@] %@", SDK_TAG, TAG, message); +} + ++ (void)log:(NSString *)format, ... +{ + if (max_unity_should_disable_all_logs()) return; + + va_list valist; + va_start(valist, format); + NSString *message = [[NSString alloc] initWithFormat: format arguments: valist]; + va_end(valist); + + NSLog(@"[%@] [%@] %@", SDK_TAG, TAG, message); +} + +- (MAInterstitialAd *)retrieveInterstitialForAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + MAInterstitialAd *result = self.interstitials[adUnitIdentifier]; + if ( !result ) + { + result = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: adUnitIdentifier sdk: self.sdk]; + result.delegate = self; + result.revenueDelegate = self; + result.adReviewDelegate = self; + + self.interstitials[adUnitIdentifier] = result; + } + + return result; +} + +- (MAAppOpenAd *)retrieveAppOpenAdForAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + MAAppOpenAd *result = self.appOpenAds[adUnitIdentifier]; + if ( !result ) + { + result = [[MAAppOpenAd alloc] initWithAdUnitIdentifier: adUnitIdentifier sdk: self.sdk]; + result.delegate = self; + result.revenueDelegate = self; + + self.appOpenAds[adUnitIdentifier] = result; + } + + return result; +} + +- (MARewardedAd *)retrieveRewardedAdForAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + MARewardedAd *result = self.rewardedAds[adUnitIdentifier]; + if ( !result ) + { + result = [MARewardedAd sharedWithAdUnitIdentifier: adUnitIdentifier sdk: self.sdk]; + result.delegate = self; + result.revenueDelegate = self; + result.adReviewDelegate = self; + + self.rewardedAds[adUnitIdentifier] = result; + } + + return result; +} + +- (MARewardedInterstitialAd *)retrieveRewardedInterstitialAdForAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + MARewardedInterstitialAd *result = self.rewardedInterstitialAds[adUnitIdentifier]; + if ( !result ) + { + result = [[MARewardedInterstitialAd alloc] initWithAdUnitIdentifier: adUnitIdentifier sdk: self.sdk]; + result.delegate = self; + result.revenueDelegate = self; + result.adReviewDelegate = self; + + self.rewardedInterstitialAds[adUnitIdentifier] = result; + } + + return result; +} + +- (MAAdView *)retrieveAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + return [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat atPosition: nil withOffset: CGPointZero]; +} + +- (MAAdView *)retrieveAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat atPosition:(NSString *)adViewPosition withOffset:(CGPoint)offset +{ + MAAdView *result = self.adViews[adUnitIdentifier]; + if ( !result && adViewPosition ) + { + result = [[MAAdView alloc] initWithAdUnitIdentifier: adUnitIdentifier adFormat: adFormat sdk: self.sdk]; + // There is a Unity bug where if an empty UIView is on screen with user interaction enabled, and a user interacts with it, it just passes the events to random parts of the screen. + result.userInteractionEnabled = NO; + result.translatesAutoresizingMaskIntoConstraints = NO; + result.delegate = self; + result.revenueDelegate = self; + result.adReviewDelegate = self; + + self.adViews[adUnitIdentifier] = result; + self.adViewPositions[adUnitIdentifier] = adViewPosition; + self.adViewOffsets[adUnitIdentifier] = [NSValue valueWithCGPoint: offset]; + + UIViewController *rootViewController = [self unityViewController]; + [rootViewController.view addSubview: result]; + + // Allow pubs to pause auto-refresh immediately, by default. + [result setExtraParameterForKey: @"allow_pause_auto_refresh_immediately" value: @"true"]; + } + + return result; +} + +- (void)positionAdViewForAd:(MAAd *)ad +{ + [self positionAdViewForAdUnitIdentifier: ad.adUnitIdentifier adFormat: ad.format]; +} + +- (void)positionAdViewForAdUnitIdentifier:(NSString *)adUnitIdentifier adFormat:(MAAdFormat *)adFormat +{ + max_unity_dispatch_on_main_thread(^{ + MAAdView *adView = [self retrieveAdViewForAdUnitIdentifier: adUnitIdentifier adFormat: adFormat]; + NSString *adViewPosition = self.adViewPositions[adUnitIdentifier]; + NSValue *adViewPositionValue = self.adViewOffsets[adUnitIdentifier]; + CGPoint adViewOffset = [adViewPositionValue CGPointValue]; + BOOL isAdaptiveBannerDisabled = [self.disabledAdaptiveBannerAdUnitIdentifiers containsObject: adUnitIdentifier]; + BOOL isWidthPtsOverridden = self.adViewWidths[adUnitIdentifier] != nil; + + UIView *superview = adView.superview; + if ( !superview ) return; + + // Deactivate any previous constraints and reset rotation so that the banner can be positioned again. + NSArray *activeConstraints = self.adViewConstraints[adUnitIdentifier]; + [NSLayoutConstraint deactivateConstraints: activeConstraints]; + adView.transform = CGAffineTransformIdentity; + [self.verticalAdViewFormats removeObjectForKey: adUnitIdentifier]; + + // Ensure superview contains the safe area background. + if ( ![superview.subviews containsObject: self.safeAreaBackground] ) + { + [self.safeAreaBackground removeFromSuperview]; + [superview insertSubview: self.safeAreaBackground belowSubview: adView]; + } + + // Deactivate any previous constraints and reset visibility state so that the safe area background can be positioned again. + [NSLayoutConstraint deactivateConstraints: self.safeAreaBackground.constraints]; + self.safeAreaBackground.hidden = adView.hidden; + + // + // Determine ad width + // + CGFloat adViewWidth; + + // Check if publisher has overridden width as points + if ( isWidthPtsOverridden ) + { + adViewWidth = self.adViewWidths[adUnitIdentifier].floatValue; + } + // Top center / bottom center stretches full screen + else if ( [adViewPosition isEqual: @"top_center"] || [adViewPosition isEqual: @"bottom_center"] ) + { + adViewWidth = CGRectGetWidth(KEY_WINDOW.bounds); + } + // Else use standard widths of 320, 728, or 300 + else + { + adViewWidth = adFormat.size.width; + } + + // + // Determine ad height + // + CGFloat adViewHeight; + + if ( (adFormat == MAAdFormat.banner || adFormat == MAAdFormat.leader) && !isAdaptiveBannerDisabled ) + { + adViewHeight = [adFormat adaptiveSizeForWidth: adViewWidth].height; + } + else + { + adViewHeight = adFormat.size.height; + } + + CGSize adViewSize = CGSizeMake(adViewWidth, adViewHeight); + + // All positions have constant height + NSMutableArray *constraints = [NSMutableArray arrayWithObject: [adView.heightAnchor constraintEqualToConstant: adViewSize.height]]; + + UILayoutGuide *layoutGuide = superview.safeAreaLayoutGuide; + + if ( [adViewPosition isEqual: @"top_center"] || [adViewPosition isEqual: @"bottom_center"] ) + { + // Non AdMob banners will still be of 50/90 points tall. Set the auto sizing mask such that the inner ad view is pinned to the bottom or top according to the ad view position. + if ( !isAdaptiveBannerDisabled ) + { + adView.autoresizingMask = UIViewAutoresizingFlexibleWidth; + + if ( [@"top_center" isEqual: adViewPosition] ) + { + adView.autoresizingMask |= UIViewAutoresizingFlexibleBottomMargin; + } + else // bottom_center + { + adView.autoresizingMask |= UIViewAutoresizingFlexibleTopMargin; + } + } + + // If publisher actually provided a banner background color + if ( self.publisherBannerBackgroundColor && adFormat != MAAdFormat.mrec ) + { + if ( isWidthPtsOverridden ) + { + [constraints addObjectsFromArray: @[[adView.widthAnchor constraintEqualToConstant: adViewWidth], + [adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor], + [self.safeAreaBackground.widthAnchor constraintEqualToConstant: adViewWidth], + [self.safeAreaBackground.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor]]]; + + if ( [adViewPosition isEqual: @"top_center"] ) + { + [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: layoutGuide.topAnchor], + [self.safeAreaBackground.topAnchor constraintEqualToAnchor: superview.topAnchor], + [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: adView.topAnchor]]]; + } + else // bottom_center + { + [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor], + [self.safeAreaBackground.topAnchor constraintEqualToAnchor: adView.bottomAnchor], + [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: superview.bottomAnchor]]]; + } + } + else + { + [constraints addObjectsFromArray: @[[adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor], + [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor], + [self.safeAreaBackground.leftAnchor constraintEqualToAnchor: superview.leftAnchor], + [self.safeAreaBackground.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]]; + + if ( [adViewPosition isEqual: @"top_center"] ) + { + [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: layoutGuide.topAnchor], + [self.safeAreaBackground.topAnchor constraintEqualToAnchor: superview.topAnchor], + [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: adView.topAnchor]]]; + } + else // bottom_center + { + [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor], + [self.safeAreaBackground.topAnchor constraintEqualToAnchor: adView.bottomAnchor], + [self.safeAreaBackground.bottomAnchor constraintEqualToAnchor: superview.bottomAnchor]]]; + } + } + } + // If pub does not have a background color set or this is not a banner + else + { + self.safeAreaBackground.hidden = YES; + + [constraints addObjectsFromArray: @[[adView.widthAnchor constraintEqualToConstant: adViewWidth], + [adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor]]]; + + if ( [adViewPosition isEqual: @"top_center"] ) + { + [constraints addObject: [adView.topAnchor constraintEqualToAnchor: layoutGuide.topAnchor]]; + } + else // BottomCenter + { + [constraints addObject: [adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor]]; + } + } + } + // Check if the publisher wants vertical banners. + else if ( [adViewPosition isEqual: @"center_left"] || [adViewPosition isEqual: @"center_right"] ) + { + if ( MAAdFormat.mrec == adFormat ) + { + [constraints addObject: [adView.widthAnchor constraintEqualToConstant: adViewSize.width]]; + + if ( [adViewPosition isEqual: @"center_left"] ) + { + [constraints addObjectsFromArray: @[[adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor], + [adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]]; + + [constraints addObjectsFromArray: @[[self.safeAreaBackground.rightAnchor constraintEqualToAnchor: layoutGuide.leftAnchor], + [self.safeAreaBackground.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]]; + } + else // center_right + { + [constraints addObjectsFromArray: @[[adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor], + [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]]; + + [constraints addObjectsFromArray: @[[self.safeAreaBackground.leftAnchor constraintEqualToAnchor: layoutGuide.rightAnchor], + [self.safeAreaBackground.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]]; + } + } + else + { + /* Align the center of the view such that when rotated it snaps into place. + * + * +---+---+-------+ + * | | | + * | | | + * | | | + * | | | + * | | | + * | | | + * +-------------+---+-----------+--+ + * | | + | + | | + * +-------------+---+-----------+--+ + * <+> | | + * |+ | | + * || | | + * || | | + * || | | + * || | | + * +|--+-----------+ + * v + * Banner Half Height + */ + self.safeAreaBackground.hidden = YES; + + adView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_2); + + CGFloat width; + // If the publiser has a background color set - set the width to the height of the screen, to span the ad across the screen after it is rotated. + if ( self.publisherBannerBackgroundColor ) + { + if ( isWidthPtsOverridden ) + { + width = adViewWidth; + } + else + { + width = CGRectGetHeight(KEY_WINDOW.bounds); + } + } + // Otherwise - we shouldn't span the banner the width of the realm (there might be user-interactable UI on the sides) + else + { + width = adViewWidth; + } + [constraints addObject: [adView.widthAnchor constraintEqualToConstant: width]]; + + // Set constraints such that the center of the banner aligns with the center left or right as needed. That way, once rotated, the banner snaps into place. + [constraints addObject: [adView.centerYAnchor constraintEqualToAnchor: superview.centerYAnchor]]; + + // Place the center of the banner half the height of the banner away from the side. If we align the center exactly with the left/right anchor, only half the banner will be visible. + CGFloat bannerHalfHeight = adViewSize.height / 2.0; + UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; + if ( [adViewPosition isEqual: @"center_left"] ) + { + NSLayoutAnchor *anchor = ( orientation == UIInterfaceOrientationLandscapeRight ) ? layoutGuide.leftAnchor : superview.leftAnchor; + [constraints addObject: [adView.centerXAnchor constraintEqualToAnchor: anchor constant: bannerHalfHeight]]; + } + else // CenterRight + { + NSLayoutAnchor *anchor = ( orientation == UIInterfaceOrientationLandscapeLeft ) ? layoutGuide.rightAnchor : superview.rightAnchor; + [constraints addObject: [adView.centerXAnchor constraintEqualToAnchor: anchor constant: -bannerHalfHeight]]; + } + + // Store the ad view with format, so that it can be updated when the orientation changes. + self.verticalAdViewFormats[adUnitIdentifier] = adFormat; + + // If adaptive - make top flexible since we anchor with the bottom of the banner at the edge of the screen + if ( !isAdaptiveBannerDisabled ) + { + adView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; + } + } + } + // Otherwise, publisher will likely construct his own views around the adview + else + { + self.safeAreaBackground.hidden = YES; + + [constraints addObject: [adView.widthAnchor constraintEqualToConstant: adViewWidth]]; + + if ( [adViewPosition isEqual: @"top_left"] ) + { + [constraints addObjectsFromArray: @[[adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor constant: adViewOffset.x], + [adView.topAnchor constraintEqualToAnchor: layoutGuide.topAnchor constant: adViewOffset.y]]]; + } + else if ( [adViewPosition isEqual: @"top_right"] ) + { + [constraints addObjectsFromArray: @[[adView.topAnchor constraintEqualToAnchor: layoutGuide.topAnchor], + [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]]; + } + else if ( [adViewPosition isEqual: @"centered"] ) + { + [constraints addObjectsFromArray: @[[adView.centerXAnchor constraintEqualToAnchor: layoutGuide.centerXAnchor], + [adView.centerYAnchor constraintEqualToAnchor: layoutGuide.centerYAnchor]]]; + } + else if ( [adViewPosition isEqual: @"bottom_left"] ) + { + [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor], + [adView.leftAnchor constraintEqualToAnchor: superview.leftAnchor]]]; + } + else if ( [adViewPosition isEqual: @"bottom_right"] ) + { + [constraints addObjectsFromArray: @[[adView.bottomAnchor constraintEqualToAnchor: layoutGuide.bottomAnchor], + [adView.rightAnchor constraintEqualToAnchor: superview.rightAnchor]]]; + } + } + + self.adViewConstraints[adUnitIdentifier] = constraints; + + [NSLayoutConstraint activateConstraints: constraints]; + }); +} + +- (UIViewController *)unityViewController +{ + // Handle edge case where `UnityGetGLViewController()` returns nil + return UnityGetGLViewController() ?: UnityGetMainWindow().rootViewController ?: [KEY_WINDOW rootViewController]; +} + +- (void)forwardUnityEventWithArgs:(NSDictionary *)args +{ +#if !IS_TEST_APP + extern bool _didResignActive; + // We should not call any script callbacks when application is not active. Suspend the callback queue if resign is active. + // We'll resume the queue once the application becomes active again. + self.backgroundCallbackEventsQueue.suspended = _didResignActive; +#endif + + [self.backgroundCallbackEventsQueue addOperationWithBlock:^{ + NSString *serializedParameters = [MAUnityAdManager serializeParameters: args]; + backgroundCallback(serializedParameters.UTF8String); + }]; +} + ++ (NSString *)serializeParameters:(NSDictionary *)dict +{ + NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict options: 0 error: nil]; + return [[NSString alloc] initWithData: jsonData encoding: NSUTF8StringEncoding]; +} + ++ (NSDictionary *)deserializeParameters:(nullable NSString *)serialized +{ + if ( serialized.length > 0 ) + { + NSError *error; + NSDictionary *deserialized = [NSJSONSerialization JSONObjectWithData: [serialized dataUsingEncoding:NSUTF8StringEncoding] + options: 0 + error: &error]; + if ( error ) + { + [self log: @"Failed to deserialize (%@) with error %@", serialized, error]; + return @{}; + } + + return deserialized; + } + else + { + return @{}; + } +} + +- (MAAdFormat *)adViewAdFormatForAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + if ( self.adViewAdFormats[adUnitIdentifier] ) + { + return self.adViewAdFormats[adUnitIdentifier]; + } + else + { + return DEVICE_SPECIFIC_ADVIEW_AD_FORMAT; + } +} + +- (NSString *)requestLatencyMillisFromRequestLatency:(NSTimeInterval)requestLatency +{ + // Convert latency from seconds to milliseconds to match Android. + long requestLatencyMillis = requestLatency * 1000; + return @(requestLatencyMillis).stringValue; +} + +#pragma mark - User Service + +- (void)didDismissUserConsentDialog +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self forwardUnityEventWithArgs: @{@"name" : @"OnSdkConsentDialogDismissedEvent"}]; + }); +} + +#pragma mark - CMP Service + +- (void)showCMPForExistingUser +{ + [self.sdk.cmpService showCMPForExistingUserWithCompletion:^(ALCMPError * _Nullable error) { + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + NSMutableDictionary *args = [NSMutableDictionary dictionaryWithCapacity: 2]; + args[@"name"] = @"OnCmpCompletedEvent"; + + if ( error ) + { + args[@"error"] = @{@"code": @(error.code), + @"message": error.message, + @"cmpCode": @(error.cmpCode), + @"cmpMessage": error.cmpMessage, + @"keepInBackground": @(YES)}; + } + + [self forwardUnityEventWithArgs: args]; + }); + }]; +} + +#pragma mark - Application + +- (void)applicationPaused:(NSNotification *)notification +{ + [self notifyApplicationStateChangedEventForPauseState: YES]; +} + +- (void)applicationResumed:(NSNotification *)notification +{ + [self notifyApplicationStateChangedEventForPauseState: NO]; +} + +- (void)notifyApplicationStateChangedEventForPauseState:(BOOL)isPaused +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self forwardUnityEventWithArgs: @{@"name": @"OnApplicationStateChanged", + @"isPaused": @(isPaused)}]; + }); +} + +- (MAAd *)adWithAdUnitIdentifier:(NSString *)adUnitIdentifier +{ + @synchronized ( self.adInfoDictLock ) + { + return self.adInfoDict[adUnitIdentifier]; + } +} + +@end diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m.meta b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m.meta new file mode 100644 index 0000000..8c3581e --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m.meta @@ -0,0 +1,109 @@ +fileFormatVersion: 2 +guid: 2973e70bd2fa74984b35aea07ae9db52 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/iOS/MAUnityAdManager.m +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 0 + Exclude tvOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 1 + settings: + CompileFlags: + FrameworkDependencies: + - first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm new file mode 100644 index 0000000..0ec08fd --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm @@ -0,0 +1,1165 @@ +// +// MAUnityPlugin.mm +// AppLovin MAX Unity Plugin +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +#import "MAUnityAdManager.h" + +#define VERSION @"8.0.1" +#define NSSTRING(_X) ( (_X != NULL) ? [NSString stringWithCString: _X encoding: NSStringEncodingConversionAllowLossy].al_stringByTrimmingWhitespace : nil) + +@interface NSString (ALUtils) +@property (nonatomic, copy, readonly) NSString *al_stringByTrimmingWhitespace; +@property (assign, readonly, getter=al_isValidString) BOOL al_validString; +- (BOOL)al_isEqualToStringIgnoringCase:(nullable NSString *)otherString; +@end + +@interface ALSdkInitializationConfigurationBuilder (ALUtils) +- (void)setSdkKey:(NSString *)sdkKey; +@end + +// When native code plugin is implemented in .mm / .cpp file, then functions +// should be surrounded with extern "C" block to conform C function naming rules +extern "C" +{ + static NSString *const TAG = @"MAUnityPlugin"; + static NSString *const KeySdkKey = @"SdkKey"; + + UIView* UnityGetGLView(); + + static ALSdkInitializationConfigurationBuilder *_initConfigurationBuilder; + static ALSdk *_sdk; + static MAUnityAdManager *_adManager; + + static bool _isSdkInitialized = false; + static bool _initializeSdkCalled = false; + static bool _disableAllLogs = false; + + // Helper method to create C string copy + static const char * cStringCopy(NSString *string); + // Helper method to log errors + void logUninitializedAccessError(const char *callingMethod); + void e(NSString *message); + + ALSdk *getSdk() + { + if ( !_sdk ) + { + _sdk = [ALSdk shared]; + } + + return _sdk; + } + + MAUnityAdManager *getAdManager() + { + if ( !_adManager ) + { + _adManager = [MAUnityAdManager shared]; + } + + return _adManager; + } + + ALSdkInitializationConfigurationBuilder *getInitConfigurationBuilder() + { + if ( !_initConfigurationBuilder ) + { + NSString *sdkKey = [getSdk().settings.extraParameters al_stringForKey: KeySdkKey]; + _initConfigurationBuilder = [ALSdkInitializationConfiguration builderWithSdkKey: sdkKey]; + } + + return _initConfigurationBuilder; + } + + bool max_unity_should_disable_all_logs() + { + return _disableAllLogs; + } + + int getConsentStatusValue(NSNumber *consentStatus) + { + if ( consentStatus ) + { + return consentStatus.intValue; + } + else + { + return -1; + } + } + + id getLocalExtraParameterValue(const char *json) + { + NSData *jsonData = [NSSTRING(json) dataUsingEncoding: NSUTF8StringEncoding]; + NSError *error; + NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: jsonData + options: 0 + error: &error]; + + if ( error ) + { + return nil; + } + else + { + return jsonDict[@"value"]; + } + } + + NSArray * toStringArray(char **arrayPointer, int size) + { + NSMutableArray *array = [NSMutableArray arrayWithCapacity: size]; + for ( int i = 0; i < size; i++ ) + { + NSString *element = NSSTRING(arrayPointer[i]); + if ( element ) + { + [array addObject: element]; + } + } + + return array; + } + + MASegmentCollection *getSegmentCollection(const char *collectionJson) + { + MASegmentCollectionBuilder *segmentCollectionBuilder = [MASegmentCollection builder]; + + NSDictionary *jsonDict = [MAUnityAdManager deserializeParameters: [NSString stringWithUTF8String: collectionJson]]; + + NSArray *segmentsArray = jsonDict[@"segments"]; + for (NSDictionary *segmentDict in segmentsArray) + { + NSNumber *key = segmentDict[@"key"]; + NSArray *valuesArray = segmentDict[@"values"]; + NSMutableArray *values = [NSMutableArray array]; + for (NSNumber *value in valuesArray) + { + [values addObject:value]; + } + + MASegment *segment = [[MASegment alloc] initWithKey:key values:values]; + [segmentCollectionBuilder addSegment:segment]; + } + + return [segmentCollectionBuilder build]; + } + + void _MaxSetBackgroundCallback(ALUnityBackgroundCallback backgroundCallback) + { + [MAUnityAdManager setUnityBackgroundCallback: backgroundCallback]; + } + + void _MaxSetSdkKey(const char *sdkKey) + { + if (!sdkKey) return; + + NSString *sdkKeyStr = [NSString stringWithUTF8String: sdkKey]; + [getInitConfigurationBuilder() setSdkKey: sdkKeyStr]; + } + + void _MaxInitializeSdk(const char *serializedAdUnitIdentifiers, const char *serializedMetaData) + { + ALSdkInitializationConfigurationBuilder *initConfigurationBuilder = getInitConfigurationBuilder(); + initConfigurationBuilder.mediationProvider = @"max"; + initConfigurationBuilder.pluginVersion = [@"Max-Unity-" stringByAppendingString: VERSION]; + initConfigurationBuilder.adUnitIdentifiers = [[NSString stringWithUTF8String: serializedAdUnitIdentifiers] componentsSeparatedByString: @","]; + + [getSdk().settings setExtraParameterForKey: @"applovin_unity_metadata" value: NSSTRING(serializedMetaData)]; + + ALSdkInitializationConfiguration *initConfig = [initConfigurationBuilder build]; + + [getAdManager() initializeSdkWithConfiguration: initConfig andCompletionHandler:^(ALSdkConfiguration *configuration) { + _isSdkInitialized = true; + }]; + + _initializeSdkCalled = true; + } + + bool _MaxIsInitialized() + { + return _isSdkInitialized; + } + + const char * _MaxGetAvailableMediatedNetworks() + { + NSArray *availableMediatedNetworks = [getSdk() availableMediatedNetworks]; + + // Create array of serialized network strings + NSMutableArray *> *serializedNetworks = [NSMutableArray arrayWithCapacity: availableMediatedNetworks.count]; + for ( MAMediatedNetworkInfo *mediatedNetwork in availableMediatedNetworks ) + { + NSDictionary *mediatedNetworkDictionary = @{@"name" : mediatedNetwork.name, + @"adapterClassName" : mediatedNetwork.adapterClassName, + @"adapterVersion" : mediatedNetwork.adapterVersion, + @"sdkVersion" : mediatedNetwork.sdkVersion}; + [serializedNetworks addObject: mediatedNetworkDictionary]; + } + + NSData *jsonData = [NSJSONSerialization dataWithJSONObject: serializedNetworks options: 0 error: nil]; + return cStringCopy([[NSString alloc] initWithData: jsonData encoding: NSUTF8StringEncoding]); + } + + void _MaxShowMediationDebugger() + { + if ( !_initializeSdkCalled ) + { + e(@"Failed to show mediation debugger - please ensure the AppLovin MAX Unity Plugin has been initialized by calling 'MaxSdk.InitializeSdk();'!"); + return; + } + + [getSdk() showMediationDebugger]; + } + + void _MaxShowCreativeDebugger() + { + if ( !_initializeSdkCalled ) + { + e(@"Failed to show creative debugger - please ensure the AppLovin MAX Unity Plugin has been initialized by calling 'MaxSdk.InitializeSdk();'!"); + return; + } + + [getSdk() showCreativeDebugger]; + } + + int _MaxConsentDialogState() + { + if ( !_isSdkInitialized ) return ALConsentDialogStateUnknown; + + return (int) getSdk().configuration.consentDialogState; + } + + void _MaxSetUserId(const char *userId) + { + getSdk().settings.userIdentifier = NSSTRING(userId); + } + + void _MaxSetSegmentCollection(const char *collectionJson) + { + if ( _initializeSdkCalled ) + { + e(@"Segment collection must be set before MAX SDK is initialized"); + return; + } + + getInitConfigurationBuilder().segmentCollection = getSegmentCollection(collectionJson); + } + + const char * _MaxGetSdkConfiguration() + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxGetSdkConfiguration"); + return cStringCopy(@""); + } + + NSString *consentFlowUserGeographyStr = @(getSdk().configuration.consentFlowUserGeography).stringValue; + NSString *consentDialogStateStr = @(getSdk().configuration.consentDialogState).stringValue; + NSString *appTrackingStatus = @(getSdk().configuration.appTrackingTransparencyStatus).stringValue; // Deliberately name it `appTrackingStatus` to be a bit more generic (in case Android introduces a similar concept) + + return cStringCopy([MAUnityAdManager serializeParameters: @{@"consentFlowUserGeography" : consentFlowUserGeographyStr, + @"consentDialogState" : consentDialogStateStr, + @"countryCode" : getSdk().configuration.countryCode, + @"appTrackingStatus" : appTrackingStatus, + @"isSuccessfullyInitialized" : @([getSdk() isInitialized]), + @"isTestModeEnabled" : @([getSdk().configuration isTestModeEnabled])}]); + } + + void _MaxSetHasUserConsent(bool hasUserConsent) + { + [ALPrivacySettings setHasUserConsent: hasUserConsent]; + } + + bool _MaxHasUserConsent() + { + return [ALPrivacySettings hasUserConsent]; + } + + bool _MaxIsUserConsentSet() + { + return [ALPrivacySettings isUserConsentSet]; + } + + void _MaxSetDoNotSell(bool doNotSell) + { + [ALPrivacySettings setDoNotSell: doNotSell]; + } + + bool _MaxIsDoNotSell() + { + return [ALPrivacySettings isDoNotSell]; + } + + bool _MaxIsDoNotSellSet() + { + return [ALPrivacySettings isDoNotSellSet]; + } + + void _MaxCreateBanner(const char *adUnitIdentifier, const char *bannerPosition) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxCreateBanner"); + return; + } + + [getAdManager() createBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) atPosition: NSSTRING(bannerPosition)]; + } + + void _MaxCreateBannerXY(const char *adUnitIdentifier, const float x, const float y) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxCreateBannerXY"); + return; + } + + [getAdManager() createBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) x: x y: y]; + } + + void _MaxLoadBanner(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadBanner"); + return; + } + + [getAdManager() loadBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetBannerBackgroundColor(const char *adUnitIdentifier, const char *hexColorCode) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerBackgroundColor"); + return; + } + + [getAdManager() setBannerBackgroundColorForAdUnitIdentifier: NSSTRING(adUnitIdentifier) hexColorCode: NSSTRING(hexColorCode)]; + } + + void _MaxSetBannerPlacement(const char *adUnitIdentifier, const char *placement) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerPlacement"); + return; + } + + [getAdManager() setBannerPlacement: NSSTRING(placement) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxStartBannerAutoRefresh(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxStartBannerAutoRefresh"); + return; + } + + [getAdManager() startBannerAutoRefreshForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxStopBannerAutoRefresh(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxStopBannerAutoRefresh"); + return; + } + + [getAdManager() stopBannerAutoRefreshForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetBannerExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerExtraParameter"); + return; + } + + [getAdManager() setBannerExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetBannerLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerLocalExtraParameter"); + return; + } + + [getAdManager() setBannerLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id) value]; + } + + void _MaxSetBannerLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setBannerLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + void _MaxSetBannerCustomData(const char *adUnitIdentifier, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerCustomData"); + return; + } + + [getAdManager() setBannerCustomData: NSSTRING(customData) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetBannerWidth(const char *adUnitIdentifier, const float width) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetBannerWidth"); + return; + } + + [getAdManager() setBannerWidth: width forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxUpdateBannerPosition(const char *adUnitIdentifier, const char *bannerPosition) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxUpdateBannerPosition"); + return; + } + + [getAdManager() updateBannerPosition: NSSTRING(bannerPosition) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxUpdateBannerPositionXY(const char *adUnitIdentifier, const float x, const float y) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxUpdateBannerPositionXY"); + return; + } + + [getAdManager() updateBannerPosition: x y: y forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowBanner(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowBanner"); + return; + } + + [getAdManager() showBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxDestroyBanner(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxDestroyBanner"); + return; + } + + [getAdManager() destroyBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxHideBanner(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxHideBanner"); + return; + } + + [getAdManager() hideBannerWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + const char * _MaxGetBannerLayout(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxGetBannerLayout"); + return cStringCopy(@""); + } + + return cStringCopy([getAdManager() bannerLayoutForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]); + } + + void _MaxCreateMRec(const char *adUnitIdentifier, const char *mrecPosition) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxCreateMRec"); + return; + } + + [getAdManager() createMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) atPosition: NSSTRING(mrecPosition)]; + } + + void _MaxCreateMRecXY(const char *adUnitIdentifier, const float x, const float y) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxCreateMRecXY"); + return; + } + + [getAdManager() createMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) x: x y: y]; + } + + void _MaxLoadMRec(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadMRec"); + return; + } + + [getAdManager() loadMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetMRecPlacement(const char *adUnitIdentifier, const char *placement) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetMRecPlacement"); + return; + } + + [getAdManager() setMRecPlacement: NSSTRING(placement) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxStartMRecAutoRefresh(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxStartMRecAutoRefresh"); + return; + } + + [getAdManager() startMRecAutoRefreshForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxStopMRecAutoRefresh(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxStopMRecAutoRefresh"); + return; + } + + [getAdManager() stopMRecAutoRefreshForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxUpdateMRecPosition(const char *adUnitIdentifier, const char *mrecPosition) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxUpdateMRecPosition"); + return; + } + + [getAdManager() updateMRecPosition: NSSTRING(mrecPosition) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxUpdateMRecPositionXY(const char *adUnitIdentifier, const float x, const float y) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxUpdateMRecPositionXY"); + return; + } + + [getAdManager() updateMRecPosition: x y: y forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowMRec(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowMRec"); + return; + } + + [getAdManager() showMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxDestroyMRec(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxDestroyMRec"); + return; + } + + [getAdManager() destroyMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxHideMRec(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxHideMRec"); + return; + } + + [getAdManager() hideMRecWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetMRecExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetMRecExtraParameter"); + return; + } + + [getAdManager() setMRecExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetMRecLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetMRecLocalExtraParameter"); + return; + } + + [getAdManager() setMRecLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id)value]; + } + + void _MaxSetMRecLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetMRecLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setMRecLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + void _MaxSetMRecCustomData(const char *adUnitIdentifier, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetMRecCustomData"); + return; + } + + [getAdManager() setMRecCustomData: NSSTRING(customData) forAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + const char * _MaxGetMRecLayout(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxGetMRecLayout"); + return cStringCopy(@""); + } + + return cStringCopy([getAdManager() mrecLayoutForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]); + } + + void _MaxLoadInterstitial(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadInterstitial"); + return; + } + + [getAdManager() loadInterstitialWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetInterstitialExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetInterstitialExtraParameter"); + return; + } + + [getAdManager() setInterstitialExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetInterstitialLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetInterstitialLocalExtraParameter"); + return; + } + + [getAdManager() setInterstitialLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id)value]; + } + + void _MaxSetInterstitialLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetInterstitialLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setInterstitialLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + bool _MaxIsInterstitialReady(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxIsInterstitialReady"); + return false; + } + + return [getAdManager() isInterstitialReadyWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowInterstitial(const char *adUnitIdentifier, const char *placement, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowInterstitial"); + return; + } + + [getAdManager() showInterstitialWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) placement: NSSTRING(placement) customData: NSSTRING(customData)]; + } + + void _MaxLoadAppOpenAd(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadAppOpenAd"); + return; + } + + [getAdManager() loadAppOpenAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetAppOpenAdExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetAppOpenAdExtraParameter"); + return; + } + + [getAdManager() setAppOpenAdExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetAppOpenAdLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetAppOpenAdLocalExtraParameter"); + return; + } + + [getAdManager() setAppOpenAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id)value]; + } + + void _MaxSetAppOpenAdLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetAppOpenAdLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setAppOpenAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + bool _MaxIsAppOpenAdReady(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxIsAppOpenAdReady"); + return false; + } + + return [getAdManager() isAppOpenAdReadyWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowAppOpenAd(const char *adUnitIdentifier, const char *placement, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowAppOpenAd"); + return; + } + + [getAdManager() showAppOpenAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) placement: NSSTRING(placement) customData: NSSTRING(customData)]; + } + + void _MaxLoadRewardedAd(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadRewardedAd"); + return; + } + + [getAdManager() loadRewardedAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetRewardedAdExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedAdExtraParameter"); + return; + } + + [getAdManager() setRewardedAdExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetRewardedAdLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedAdLocalExtraParameter"); + return; + } + + [getAdManager() setRewardedAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id)value]; + } + + void _MaxSetRewardedAdLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedAdLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setRewardedAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + bool _MaxIsRewardedAdReady(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxIsRewardedAdReady"); + return false; + } + + return [getAdManager() isRewardedAdReadyWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowRewardedAd(const char *adUnitIdentifier, const char *placement, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowRewardedAd"); + return; + } + + [getAdManager() showRewardedAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) placement: NSSTRING(placement) customData: NSSTRING(customData)]; + } + + void _MaxLoadRewardedInterstitialAd(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxLoadRewardedInterstitialAd"); + return; + } + + [getAdManager() loadRewardedInterstitialAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxSetRewardedInterstitialAdExtraParameter(const char *adUnitIdentifier, const char *key, const char *value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedInterstitialAdExtraParameter"); + return; + } + + [getAdManager() setRewardedInterstitialAdExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: NSSTRING(value)]; + } + + void _MaxSetRewardedInterstitialAdLocalExtraParameter(const char *adUnitIdentifier, const char *key, MAUnityRef value) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedInterstitialAdLocalExtraParameter"); + return; + } + + [getAdManager() setRewardedInterstitialAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: (__bridge id)value]; + } + + void _MaxSetRewardedInterstitialAdLocalExtraParameterJSON(const char *adUnitIdentifier, const char *key, const char *json) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxSetRewardedInterstitialAdLocalExtraParameter"); + return; + } + + id value = getLocalExtraParameterValue(json); + [getAdManager() setRewardedInterstitialAdLocalExtraParameterForAdUnitIdentifier: NSSTRING(adUnitIdentifier) + key: NSSTRING(key) + value: value]; + } + + bool _MaxIsRewardedInterstitialAdReady(const char *adUnitIdentifier) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxIsRewardedInterstitialAdReady"); + return false; + } + + return [getAdManager() isRewardedInterstitialAdReadyWithAdUnitIdentifier: NSSTRING(adUnitIdentifier)]; + } + + void _MaxShowRewardedInterstitialAd(const char *adUnitIdentifier, const char *placement, const char *customData) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowRewardedInterstitialAd"); + return; + } + + [getAdManager() showRewardedInterstitialAdWithAdUnitIdentifier: NSSTRING(adUnitIdentifier) placement: NSSTRING(placement) customData: NSSTRING(customData)]; + } + + void _MaxTrackEvent(const char *event, const char *parameters) + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxTrackEvent"); + return; + } + + [getAdManager() trackEvent: NSSTRING(event) parameters: NSSTRING(parameters)]; + } + + bool _MaxIsTablet() + { + return [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad; + } + + bool _MaxIsPhysicalDevice() + { + return !ALUtils.simulator; + } + + int _MaxGetTcfVendorConsentStatus(int vendorIdentifier) + { + NSNumber *consentStatus = [ALPrivacySettings tcfVendorConsentStatusForIdentifier: vendorIdentifier]; + return getConsentStatusValue(consentStatus); + } + + int _MaxGetAdditionalConsentStatus(int atpIdentifier) + { + NSNumber *consentStatus = [ALPrivacySettings additionalConsentStatusForIdentifier: atpIdentifier]; + return getConsentStatusValue(consentStatus); + } + + int _MaxGetPurposeConsentStatus(int purposeIdentifier) + { + NSNumber *consentStatus = [ALPrivacySettings purposeConsentStatusForIdentifier: purposeIdentifier]; + return getConsentStatusValue(consentStatus); + } + + int _MaxGetSpecialFeatureOptInStatus(int specialFeatureIdentifier) + { + NSNumber *consentStatus = [ALPrivacySettings specialFeatureOptInStatusForIdentifier: specialFeatureIdentifier]; + return getConsentStatusValue(consentStatus); + } + + static const char * cStringCopy(NSString *string) + { + const char *value = string.UTF8String; + return value ? strdup(value) : NULL; + } + + void _MaxSetMuted(bool muted) + { + getSdk().settings.muted = muted; + } + + bool _MaxIsMuted() + { + return getSdk().settings.muted; + } + + float _MaxScreenDensity() + { + return [UIScreen.mainScreen nativeScale]; + } + + const char * _MaxGetAdInfo(const char *adUnitIdentifier) + { + return cStringCopy([getAdManager() adInfoForAdUnitIdentifier: NSSTRING(adUnitIdentifier)]); + } + + const char * _MaxGetAdValue(const char *adUnitIdentifier, const char *key) + { + return cStringCopy([getAdManager() adValueForAdUnitIdentifier: NSSTRING(adUnitIdentifier) withKey: NSSTRING(key)]); + } + + void _MaxSetVerboseLogging(bool enabled) + { + getSdk().settings.verboseLoggingEnabled = enabled; + } + + bool _MaxIsVerboseLoggingEnabled() + { + return [getSdk().settings isVerboseLoggingEnabled]; + } + + void _MaxSetTestDeviceAdvertisingIdentifiers(char **advertisingIdentifiers, int size) + { + if ( _initializeSdkCalled ) + { + e(@"Test device advertising IDs must be set before MAX SDK is initialized"); + return; + } + + NSArray *advertisingIdentifiersArray = toStringArray(advertisingIdentifiers, size); + getInitConfigurationBuilder().testDeviceAdvertisingIdentifiers = advertisingIdentifiersArray; + } + + void _MaxSetCreativeDebuggerEnabled(bool enabled) + { + getSdk().settings.creativeDebuggerEnabled = enabled; + } + + void _MaxSetExceptionHandlerEnabled(bool enabled) + { + if ( _initializeSdkCalled ) + { + e(@"Exception handler must be enabled/disabled before MAX SDK is initialized"); + return; + } + + getInitConfigurationBuilder().exceptionHandlerEnabled = enabled; + } + + void _MaxSetExtraParameter(const char *key, const char *value) + { + NSString *stringKey = NSSTRING(key); + if ( ![stringKey al_isValidString] ) + { + NSString *message = [NSString stringWithFormat:@"Failed to set extra parameter for nil or empty key: %@", stringKey]; + e(message); + return; + } + + NSString *stringValue = NSSTRING(value); + if ( [@"disable_all_logs" isEqualToString: stringKey] ) + { + _disableAllLogs = [@"true" al_isEqualToStringIgnoringCase: stringValue]; + } + + ALSdkSettings *settings = getSdk().settings; + [settings setExtraParameterForKey: stringKey value: stringValue]; + } + + int * _MaxGetSafeAreaInsets() + { + UIEdgeInsets safeAreaInsets = UnityGetGLView().safeAreaInsets; + static int insets[4] = {(int) safeAreaInsets.left, (int) safeAreaInsets.top, (int) safeAreaInsets.right, (int) safeAreaInsets.bottom}; + return insets; + } + + void _MaxShowCmpForExistingUser() + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxShowCmpForExistingUser"); + return; + } + + [getAdManager() showCMPForExistingUser]; + } + + bool _MaxHasSupportedCmp() + { + if ( !_initializeSdkCalled ) + { + logUninitializedAccessError("_MaxHasSupportedCmp"); + return false; + } + + return [getSdk().cmpService hasSupportedCMP]; + } + + float _MaxGetAdaptiveBannerHeight(const float width) + { + return [MAUnityAdManager adaptiveBannerHeightForWidth: width]; + } + + void logUninitializedAccessError(const char *callingMethod) + { + NSString *message = [NSString stringWithFormat:@"Failed to execute: %s - please ensure the AppLovin MAX Unity Plugin has been initialized by calling 'MaxSdk.InitializeSdk();'!", callingMethod]; + e(message); + } + + void e(NSString *message) + { + if (_disableAllLogs) return; + + NSString *logMessage = [NSString stringWithFormat: @"[%@] %@", TAG, message]; + NSLog(@"%@", logMessage); + } +} + +#pragma clang diagnostic pop diff --git a/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm.meta b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm.meta new file mode 100644 index 0000000..5ea08ff --- /dev/null +++ b/Assets/MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm.meta @@ -0,0 +1,109 @@ +fileFormatVersion: 2 +guid: 7e373ed7168b243e6b706e991ab5a643 +labels: +- al_max +- al_max_export_path-MaxSdk/AppLovin/Plugins/iOS/MAUnityPlugin.mm +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 0 + Exclude tvOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 1 + settings: + CompileFlags: + FrameworkDependencies: + - first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/CHANGELOG.md b/Assets/MaxSdk/CHANGELOG.md new file mode 100644 index 0000000..6153543 --- /dev/null +++ b/Assets/MaxSdk/CHANGELOG.md @@ -0,0 +1,3 @@ +# AppLovin MAX Unity Plugin + +To get the latest changes, see the [AppLovin MAX Unity Changelog](https://developers.applovin.com/en/max/unity/changelog). diff --git a/Assets/MaxSdk/CHANGELOG.md.meta b/Assets/MaxSdk/CHANGELOG.md.meta new file mode 100644 index 0000000..6d06bcb --- /dev/null +++ b/Assets/MaxSdk/CHANGELOG.md.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: dfb944c2e1cb479cabf023040a5942d2 +labels: +- al_max +- al_max_export_path-MaxSdk/CHANGELOG.md +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation.meta b/Assets/MaxSdk/Mediation.meta new file mode 100644 index 0000000..103dd6f --- /dev/null +++ b/Assets/MaxSdk/Mediation.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dcf2020c4018447c9b91170c0f62d799 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/BigoAds.meta b/Assets/MaxSdk/Mediation/BigoAds.meta new file mode 100644 index 0000000..60c36d7 --- /dev/null +++ b/Assets/MaxSdk/Mediation/BigoAds.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac25046ac442f4c1895555ada8d01866 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/BigoAds/Editor.meta b/Assets/MaxSdk/Mediation/BigoAds/Editor.meta new file mode 100644 index 0000000..39a3140 --- /dev/null +++ b/Assets/MaxSdk/Mediation/BigoAds/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1235281c630214a8999b2185ceba6388 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/BigoAds/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml new file mode 100644 index 0000000..fe507b1 --- /dev/null +++ b/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..521ce00 --- /dev/null +++ b/Assets/MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: fba397d5cac8648fea9b0fe82e201e63 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/BigoAds/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/ByteDance.meta b/Assets/MaxSdk/Mediation/ByteDance.meta new file mode 100644 index 0000000..d880057 --- /dev/null +++ b/Assets/MaxSdk/Mediation/ByteDance.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 70a10024731384305a71bfeeaf9c2f52 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/ByteDance/Editor.meta b/Assets/MaxSdk/Mediation/ByteDance/Editor.meta new file mode 100644 index 0000000..e54a766 --- /dev/null +++ b/Assets/MaxSdk/Mediation/ByteDance/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef8467ffb0e4447b79a8804884a7520a +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/ByteDance/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml new file mode 100644 index 0000000..1285ac4 --- /dev/null +++ b/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml @@ -0,0 +1,13 @@ + + + + + + https://artifact.bytedance.com/repository/pangle + + + + + + + diff --git a/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..5205233 --- /dev/null +++ b/Assets/MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0828555cb1ce94702a4af6f3dce3d735 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/ByteDance/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Chartboost.meta b/Assets/MaxSdk/Mediation/Chartboost.meta new file mode 100644 index 0000000..3a12ea2 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Chartboost.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 876e3a1a94b4b496ebbf9ccfa956ab1a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Chartboost/Editor.meta b/Assets/MaxSdk/Mediation/Chartboost/Editor.meta new file mode 100644 index 0000000..38bff8d --- /dev/null +++ b/Assets/MaxSdk/Mediation/Chartboost/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a90f13141c35746f5a2996c8ad068fe9 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Chartboost/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml new file mode 100644 index 0000000..2707701 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml @@ -0,0 +1,14 @@ + + + + + + https://cboost.jfrog.io/artifactory/chartboost-ads/ + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..02628eb --- /dev/null +++ b/Assets/MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 93b0a4618bd884871af0981a7867bb2f +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Chartboost/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Facebook.meta b/Assets/MaxSdk/Mediation/Facebook.meta new file mode 100644 index 0000000..339a799 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Facebook.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ceafa35ff4b964f12b9c025f47227c44 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Facebook/Editor.meta b/Assets/MaxSdk/Mediation/Facebook/Editor.meta new file mode 100644 index 0000000..4beff5e --- /dev/null +++ b/Assets/MaxSdk/Mediation/Facebook/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28880992a399a48b7abe95b66649d711 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Facebook/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml new file mode 100644 index 0000000..b303ae6 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..69b5d2c --- /dev/null +++ b/Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: aea9bdf974328420db5ae118ef0d2b87 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Facebook/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Fyber.meta b/Assets/MaxSdk/Mediation/Fyber.meta new file mode 100644 index 0000000..6e4ea33 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Fyber.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d082a8938aab642cd8a004a029248a3b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Fyber/Editor.meta b/Assets/MaxSdk/Mediation/Fyber/Editor.meta new file mode 100644 index 0000000..315e8c8 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Fyber/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e076e4ef7e2874ba69b108cc7a346c2a +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Fyber/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml new file mode 100644 index 0000000..ef011d7 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..fd0bbbf --- /dev/null +++ b/Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 5e123cdc08e804dffb2c40c4fbc83caf +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Fyber/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Google.meta b/Assets/MaxSdk/Mediation/Google.meta new file mode 100644 index 0000000..e85db52 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Google.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dceba57a99cb74bed9bf83511f3ecbe5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Google/Editor.meta b/Assets/MaxSdk/Mediation/Google/Editor.meta new file mode 100644 index 0000000..ea8dd55 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Google/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e8015bd045cea462c8f39c8a05867d08 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Google/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml new file mode 100644 index 0000000..ef7f6b6 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..36bef72 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 053b810d3594744e38b6fd0fa378fb57 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Google/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/InMobi.meta b/Assets/MaxSdk/Mediation/InMobi.meta new file mode 100644 index 0000000..78725ba --- /dev/null +++ b/Assets/MaxSdk/Mediation/InMobi.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9a754b55ab1c44663bd6f3f529c0db5f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/InMobi/Editor.meta b/Assets/MaxSdk/Mediation/InMobi/Editor.meta new file mode 100644 index 0000000..a998cfd --- /dev/null +++ b/Assets/MaxSdk/Mediation/InMobi/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a141703acd55a48c2a3e6e6599f90c64 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/InMobi/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml new file mode 100644 index 0000000..17f006f --- /dev/null +++ b/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..1b62e82 --- /dev/null +++ b/Assets/MaxSdk/Mediation/InMobi/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: bc66a0ef4503843ee9b1bf1b1e867367 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/InMobi/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/IronSource.meta b/Assets/MaxSdk/Mediation/IronSource.meta new file mode 100644 index 0000000..b026b0a --- /dev/null +++ b/Assets/MaxSdk/Mediation/IronSource.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0d540ee5f5b374e3ea122e65b3d9fa98 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/IronSource/Editor.meta b/Assets/MaxSdk/Mediation/IronSource/Editor.meta new file mode 100644 index 0000000..327f5d6 --- /dev/null +++ b/Assets/MaxSdk/Mediation/IronSource/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 531d860cac61f47d19e32f526470ae43 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/IronSource/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml new file mode 100644 index 0000000..ee5c72b --- /dev/null +++ b/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml @@ -0,0 +1,13 @@ + + + + + + https://android-sdk.is.com/ + + + + + + + diff --git a/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..f77e6f0 --- /dev/null +++ b/Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 19262406303f04f05b14b31b3c734d35 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/IronSource/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/MediationAdapters.txt b/Assets/MaxSdk/Mediation/MediationAdapters.txt new file mode 100644 index 0000000..40f94d0 --- /dev/null +++ b/Assets/MaxSdk/Mediation/MediationAdapters.txt @@ -0,0 +1,2 @@ +A placeholder file to make sure that the Mediation folder asset is exported with the base plugin. +This ensures that the adapters are imported into this directory even when the plugin has been moved to a different folder. diff --git a/Assets/MaxSdk/Mediation/MediationAdapters.txt.meta b/Assets/MaxSdk/Mediation/MediationAdapters.txt.meta new file mode 100644 index 0000000..41fb994 --- /dev/null +++ b/Assets/MaxSdk/Mediation/MediationAdapters.txt.meta @@ -0,0 +1,6 @@ +fileFormatVersion: 2 +guid: 9a8f83e97729443c86120be3bb24190d +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/MediationAdapters.txt +timeCreated: 1609308536 diff --git a/Assets/MaxSdk/Mediation/Mintegral.meta b/Assets/MaxSdk/Mediation/Mintegral.meta new file mode 100644 index 0000000..4391db2 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Mintegral.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3153085a2bb3044fd9629cbfa40eb431 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Mintegral/Editor.meta b/Assets/MaxSdk/Mediation/Mintegral/Editor.meta new file mode 100644 index 0000000..d189ce0 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Mintegral/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db1de4066dc4e4290b3879b34fa87de2 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Mintegral/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml new file mode 100644 index 0000000..54b233b --- /dev/null +++ b/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml @@ -0,0 +1,14 @@ + + + + + + https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..415c4ab --- /dev/null +++ b/Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 221b2a20a58a04f2cb4afb0779587206 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/UnityAds.meta b/Assets/MaxSdk/Mediation/UnityAds.meta new file mode 100644 index 0000000..bec0455 --- /dev/null +++ b/Assets/MaxSdk/Mediation/UnityAds.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 65275fe8716b147f2a622c8018ca68d2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/UnityAds/Editor.meta b/Assets/MaxSdk/Mediation/UnityAds/Editor.meta new file mode 100644 index 0000000..b66e846 --- /dev/null +++ b/Assets/MaxSdk/Mediation/UnityAds/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 30751f2dc322a40e588edfb7c978c9c0 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/UnityAds/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml new file mode 100644 index 0000000..b237050 --- /dev/null +++ b/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..937df6e --- /dev/null +++ b/Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9950f1cb0da1e43efbeca604db142076 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Vungle.meta b/Assets/MaxSdk/Mediation/Vungle.meta new file mode 100644 index 0000000..bc30441 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Vungle.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 83e47aa65ef684577b34edb98b63a226 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Vungle/Editor.meta b/Assets/MaxSdk/Mediation/Vungle/Editor.meta new file mode 100644 index 0000000..1ea75cc --- /dev/null +++ b/Assets/MaxSdk/Mediation/Vungle/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 77b6ea05736a9458f8ef8762ee9b64bb +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Vungle/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml b/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml new file mode 100644 index 0000000..34a47af --- /dev/null +++ b/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml.meta b/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml.meta new file mode 100644 index 0000000..7038186 --- /dev/null +++ b/Assets/MaxSdk/Mediation/Vungle/Editor/Dependencies.xml.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0d8ad3a6ddc4f44fab2efe607fe14f26 +labels: +- al_max +- al_max_export_path-MaxSdk/Mediation/Vungle/Editor/Dependencies.xml +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Prefabs.meta b/Assets/MaxSdk/Prefabs.meta new file mode 100644 index 0000000..5e8f342 --- /dev/null +++ b/Assets/MaxSdk/Prefabs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 53776d7e6d4bb4027885aa1709549628 +labels: +- al_max +- al_max_export_path-MaxSdk/Prefabs +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Prefabs/BannerBottom.prefab b/Assets/MaxSdk/Prefabs/BannerBottom.prefab new file mode 100644 index 0000000..bba7ac6 --- /dev/null +++ b/Assets/MaxSdk/Prefabs/BannerBottom.prefab @@ -0,0 +1,402 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &3149432657757030138 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5965516886513985157} + - component: {fileID: 3167928293195730454} + - component: {fileID: 6048907697713132302} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5965516886513985157 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 4118862295226300947} + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 0} + m_AnchoredPosition: {x: 0, y: 84} + m_SizeDelta: {x: 0, y: 168} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &3167928293195730454 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_CullTransparentMesh: 0 +--- !u!114 &6048907697713132302 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0, g: 0, b: 0, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &3829518492429360636 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4118862295226300947} + - component: {fileID: 5582763645243389146} + - component: {fileID: 1436650035481827287} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &4118862295226300947 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 5084927109723455527} + - {fileID: 8189983859356672495} + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 1} + m_AnchorMax: {x: 0.5, y: 1} + m_AnchoredPosition: {x: 0, y: -50} + m_SizeDelta: {x: 640, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &5582763645243389146 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_CullTransparentMesh: 0 +--- !u!114 &1436650035481827287 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &4772536868390647122 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 8189983859356672495} + - component: {fileID: 7216515036998124610} + - component: {fileID: 3801875349924125266} + m_Layer: 5 + m_Name: InfoText + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &8189983859356672495 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4772536868390647122} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4118862295226300947} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 3} + m_SizeDelta: {x: 0, y: -6} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7216515036998124610 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4772536868390647122} + m_CullTransparentMesh: 0 +--- !u!114 &3801875349924125266 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4772536868390647122} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.29411766, g: 0.29411766, b: 0.29411766, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 18 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 7 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Actual banner size may vary on mobile devices +--- !u!1 &7742712311334970126 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3413013686078446151} + - component: {fileID: 2511819091764556577} + - component: {fileID: 2638196187645015298} + - component: {fileID: 633018877563332563} + m_Layer: 5 + m_Name: BannerBottom + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &3413013686078446151 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 5965516886513985157} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!223 &2511819091764556577 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 500 + m_TargetDisplay: 0 +--- !u!114 &2638196187645015298 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!114 &633018877563332563 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!1 &8436952342056443077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5084927109723455527} + - component: {fileID: 7267203896389005665} + - component: {fileID: 5500603550844857255} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5084927109723455527 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4118862295226300947} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -4} + m_SizeDelta: {x: 0, y: -8} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7267203896389005665 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_CullTransparentMesh: 0 +--- !u!114 &5500603550844857255 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 26 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 0 + m_MaxSize: 71 + m_Alignment: 1 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: MAX Banner Ad diff --git a/Assets/MaxSdk/Prefabs/BannerBottom.prefab.meta b/Assets/MaxSdk/Prefabs/BannerBottom.prefab.meta new file mode 100644 index 0000000..153cfcf --- /dev/null +++ b/Assets/MaxSdk/Prefabs/BannerBottom.prefab.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 54c062c0526b148efa2ea2e9489b3aa0 +labels: +- al_max +- al_max_export_path-MaxSdk/Prefabs/BannerBottom.prefab +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Prefabs/BannerTop.prefab b/Assets/MaxSdk/Prefabs/BannerTop.prefab new file mode 100644 index 0000000..25d5f49 --- /dev/null +++ b/Assets/MaxSdk/Prefabs/BannerTop.prefab @@ -0,0 +1,402 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &3149432657757030138 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5965516886513985157} + - component: {fileID: 3167928293195730454} + - component: {fileID: 6048907697713132302} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5965516886513985157 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 4118862295226300947} + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -50} + m_SizeDelta: {x: 0, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &3167928293195730454 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_CullTransparentMesh: 0 +--- !u!114 &6048907697713132302 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0, g: 0, b: 0, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &3829518492429360636 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 4118862295226300947} + - component: {fileID: 5582763645243389146} + - component: {fileID: 1436650035481827287} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &4118862295226300947 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 5084927109723455527} + - {fileID: 7429934296583149777} + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0} + m_AnchorMax: {x: 0.5, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 640, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &5582763645243389146 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_CullTransparentMesh: 0 +--- !u!114 &1436650035481827287 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3829518492429360636} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &5625059666589051168 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 7429934296583149777} + - component: {fileID: 6576623406533516677} + - component: {fileID: 5405475098690228567} + m_Layer: 5 + m_Name: InfoText + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &7429934296583149777 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5625059666589051168} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4118862295226300947} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 3} + m_SizeDelta: {x: 0, y: -6} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &6576623406533516677 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5625059666589051168} + m_CullTransparentMesh: 0 +--- !u!114 &5405475098690228567 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5625059666589051168} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.29411766, g: 0.29411766, b: 0.29411766, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 18 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 1 + m_MaxSize: 40 + m_Alignment: 7 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Actual banner size may vary on mobile devices +--- !u!1 &7742712311334970126 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3413013686078446151} + - component: {fileID: 2511819091764556577} + - component: {fileID: 2638196187645015298} + - component: {fileID: 633018877563332563} + m_Layer: 5 + m_Name: BannerTop + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &3413013686078446151 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 5965516886513985157} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!223 &2511819091764556577 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 500 + m_TargetDisplay: 0 +--- !u!114 &2638196187645015298 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!114 &633018877563332563 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!1 &8436952342056443077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5084927109723455527} + - component: {fileID: 7267203896389005665} + - component: {fileID: 5500603550844857255} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5084927109723455527 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 4118862295226300947} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: -4} + m_SizeDelta: {x: 0, y: -8} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7267203896389005665 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_CullTransparentMesh: 0 +--- !u!114 &5500603550844857255 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 26 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 0 + m_MaxSize: 71 + m_Alignment: 1 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: MAX Banner Ad diff --git a/Assets/MaxSdk/Prefabs/BannerTop.prefab.meta b/Assets/MaxSdk/Prefabs/BannerTop.prefab.meta new file mode 100644 index 0000000..52ef464 --- /dev/null +++ b/Assets/MaxSdk/Prefabs/BannerTop.prefab.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 6521750c87fd14f709d09a1e38ffde47 +labels: +- al_max +- al_max_export_path-MaxSdk/Prefabs/BannerTop.prefab +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Prefabs/Interstitial.prefab b/Assets/MaxSdk/Prefabs/Interstitial.prefab new file mode 100644 index 0000000..10c7c7b --- /dev/null +++ b/Assets/MaxSdk/Prefabs/Interstitial.prefab @@ -0,0 +1,523 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &3149432657757030138 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5965516886513985157} + - component: {fileID: 3167928293195730454} + - component: {fileID: 6048907697713132302} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5965516886513985157 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 5084927109723455527} + - {fileID: 8681486192829137138} + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &3167928293195730454 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_CullTransparentMesh: 0 +--- !u!114 &6048907697713132302 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.88235295, g: 0.88235295, b: 0.88235295, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &5668641863723001099 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 8681486192829137138} + - component: {fileID: 8217482188885705039} + - component: {fileID: 3177344817093501532} + - component: {fileID: 4415703054918645549} + m_Layer: 5 + m_Name: MaxInterstitialCloseButton + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &8681486192829137138 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 763654547095120985} + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: -200, y: -100} + m_SizeDelta: {x: 250, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &8217482188885705039 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_CullTransparentMesh: 0 +--- !u!114 &3177344817093501532 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &4415703054918645549 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 3177344817093501532} + m_OnClick: + m_PersistentCalls: + m_Calls: [] +--- !u!1 &6155160063690407013 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1672649117655046507} + - component: {fileID: 2484422763836779945} + - component: {fileID: 1332063313327512547} + - component: {fileID: 9160434328933334999} + m_Layer: 5 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1672649117655046507 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6155160063690407013} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &2484422763836779945 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6155160063690407013} + m_Enabled: 0 + m_EditorHideFlags: 0 + m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!114 &1332063313327512547 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6155160063690407013} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &9160434328933334999 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6155160063690407013} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: e0acf281ba86b4929a6942ecd998395b, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &6462551400748024402 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 763654547095120985} + - component: {fileID: 6719360953530842803} + - component: {fileID: 4616290306121202327} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &763654547095120985 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 8681486192829137138} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &6719360953530842803 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_CullTransparentMesh: 0 +--- !u!114 &4616290306121202327 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 40 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 4 + m_MaxSize: 47 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Close +--- !u!1 &7742712311334970126 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3413013686078446151} + - component: {fileID: 2511819091764556577} + - component: {fileID: 2638196187645015298} + - component: {fileID: 633018877563332563} + m_Layer: 5 + m_Name: Interstitial + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &3413013686078446151 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 5965516886513985157} + - {fileID: 1672649117655046507} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!223 &2511819091764556577 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 999 + m_TargetDisplay: 0 +--- !u!114 &2638196187645015298 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!114 &633018877563332563 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!1 &8436952342056443077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5084927109723455527} + - component: {fileID: 7267203896389005665} + - component: {fileID: 5500603550844857255} + m_Layer: 5 + m_Name: MaxInterstitialTitle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5084927109723455527 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 300} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7267203896389005665 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_CullTransparentMesh: 0 +--- !u!114 &5500603550844857255 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 50 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 0 + m_MaxSize: 71 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: MAX Interstitial Ad diff --git a/Assets/MaxSdk/Prefabs/Interstitial.prefab.meta b/Assets/MaxSdk/Prefabs/Interstitial.prefab.meta new file mode 100644 index 0000000..4fa240b --- /dev/null +++ b/Assets/MaxSdk/Prefabs/Interstitial.prefab.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3fc0c2627ce8a4490b8e319326f8a535 +labels: +- al_max +- al_max_export_path-MaxSdk/Prefabs/Interstitial.prefab +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Prefabs/Rewarded.prefab b/Assets/MaxSdk/Prefabs/Rewarded.prefab new file mode 100644 index 0000000..dd3457e --- /dev/null +++ b/Assets/MaxSdk/Prefabs/Rewarded.prefab @@ -0,0 +1,795 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1 &288832541099509301 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 6736833388881778366} + - component: {fileID: 738723989743429661} + - component: {fileID: 3366016410383180441} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &6736833388881778366 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288832541099509301} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 2219183527695013266} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &738723989743429661 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288832541099509301} + m_CullTransparentMesh: 0 +--- !u!114 &3366016410383180441 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 288832541099509301} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 35 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 3 + m_MaxSize: 48 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: 'Grant Reward + + (5 coins)' +--- !u!1 &2620135977249264498 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3035265698078104281} + - component: {fileID: 7277178523579209441} + - component: {fileID: 8085319417655039649} + m_Layer: 5 + m_Name: MaxRewardStatus + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &3035265698078104281 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2620135977249264498} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: -250} + m_SizeDelta: {x: 0, y: 200} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7277178523579209441 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2620135977249264498} + m_CullTransparentMesh: 0 +--- !u!114 &8085319417655039649 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2620135977249264498} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 40 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 10 + m_MaxSize: 69 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Reward not yet granted. +--- !u!1 &3096027301306273604 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2219183527695013266} + - component: {fileID: 3687429596110321440} + - component: {fileID: 3757577222601629632} + - component: {fileID: 87227930114769318} + m_Layer: 5 + m_Name: MaxRewardButton + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &2219183527695013266 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3096027301306273604} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 6736833388881778366} + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 0, y: -150} + m_SizeDelta: {x: 300, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &3687429596110321440 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3096027301306273604} + m_CullTransparentMesh: 0 +--- !u!114 &3757577222601629632 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3096027301306273604} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &87227930114769318 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3096027301306273604} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 3757577222601629632} + m_OnClick: + m_PersistentCalls: + m_Calls: [] +--- !u!1 &3149432657757030138 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5965516886513985157} + - component: {fileID: 3167928293195730454} + - component: {fileID: 6048907697713132302} + m_Layer: 5 + m_Name: Panel + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5965516886513985157 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 5084927109723455527} + - {fileID: 8681486192829137138} + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &3167928293195730454 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_CullTransparentMesh: 0 +--- !u!114 &6048907697713132302 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 3149432657757030138} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.88235295, g: 0.88235295, b: 0.88235295, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!1 &4010021198786516228 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3074011789293951898} + - component: {fileID: 301935380126337495} + - component: {fileID: 535359239537776472} + - component: {fileID: 1463999766055390634} + m_Layer: 5 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &3074011789293951898 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4010021198786516228} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 3413013686078446151} + m_RootOrder: 3 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &301935380126337495 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4010021198786516228} + m_Enabled: 0 + m_EditorHideFlags: 0 + m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!114 &535359239537776472 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4010021198786516228} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &1463999766055390634 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 4010021198786516228} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: e0acf281ba86b4929a6942ecd998395b, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &5668641863723001099 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 8681486192829137138} + - component: {fileID: 8217482188885705039} + - component: {fileID: 3177344817093501532} + - component: {fileID: 4415703054918645549} + m_Layer: 5 + m_Name: MaxRewardedCloseButton + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &8681486192829137138 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 763654547095120985} + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 1, y: 1} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: -200, y: -100} + m_SizeDelta: {x: 250, y: 100} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &8217482188885705039 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_CullTransparentMesh: 0 +--- !u!114 &3177344817093501532 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: -765806418, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 +--- !u!114 &4415703054918645549 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 5668641863723001099} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 3177344817093501532} + m_OnClick: + m_PersistentCalls: + m_Calls: [] +--- !u!1 &6462551400748024402 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 763654547095120985} + - component: {fileID: 6719360953530842803} + - component: {fileID: 4616290306121202327} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &763654547095120985 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 8681486192829137138} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &6719360953530842803 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_CullTransparentMesh: 0 +--- !u!114 &4616290306121202327 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 6462551400748024402} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 40 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 4 + m_MaxSize: 47 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Close +--- !u!1 &7742712311334970126 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3413013686078446151} + - component: {fileID: 2511819091764556577} + - component: {fileID: 2638196187645015298} + - component: {fileID: 633018877563332563} + m_Layer: 5 + m_Name: Rewarded + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &3413013686078446151 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 5965516886513985157} + - {fileID: 3035265698078104281} + - {fileID: 2219183527695013266} + - {fileID: 3074011789293951898} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!223 &2511819091764556577 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 999 + m_TargetDisplay: 0 +--- !u!114 &2638196187645015298 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!114 &633018877563332563 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 7742712311334970126} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!1 &8436952342056443077 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 5084927109723455527} + - component: {fileID: 7267203896389005665} + - component: {fileID: 5500603550844857255} + m_Layer: 5 + m_Name: MaxRewardTitle + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &5084927109723455527 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 5965516886513985157} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0.5} + m_AnchorMax: {x: 1, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 300} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!222 &7267203896389005665 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_CullTransparentMesh: 0 +--- !u!114 &5500603550844857255 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 8436952342056443077} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 50 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 0 + m_MaxSize: 71 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: MAX Rewarded Ad diff --git a/Assets/MaxSdk/Prefabs/Rewarded.prefab.meta b/Assets/MaxSdk/Prefabs/Rewarded.prefab.meta new file mode 100644 index 0000000..214bea1 --- /dev/null +++ b/Assets/MaxSdk/Prefabs/Rewarded.prefab.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a28c1544d6f094d5eafc8da2343c9119 +labels: +- al_max +- al_max_export_path-MaxSdk/Prefabs/Rewarded.prefab +PrefabImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources.meta b/Assets/MaxSdk/Resources.meta new file mode 100644 index 0000000..70c4ae0 --- /dev/null +++ b/Assets/MaxSdk/Resources.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d584eda23f1654b7da1e6390bdaea873 +labels: +- al_max +- al_max_export_path-MaxSdk/Resources +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources/AppLovinSettings.asset b/Assets/MaxSdk/Resources/AppLovinSettings.asset new file mode 100644 index 0000000..9fb1d37 --- /dev/null +++ b/Assets/MaxSdk/Resources/AppLovinSettings.asset @@ -0,0 +1,36 @@ +%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: ebc0ba1b5ef6b4a6b9dd53d7eadfea16, type: 3} + m_Name: AppLovinSettings + m_EditorClassIdentifier: + qualityServiceEnabled: 0 + sdkKey: oXM0CzVDi7P1HstOpKvFMInPMOzpQ9uA6t3x75q5f5wQvsEy9vuiiiM94ZJCJSV7PcZGroSSInQCTGsu04QEiE + setAttributionReportEndpoint: 1 + addApsSkAdNetworkIds: 0 + customGradleVersionUrl: + customGradleToolsVersion: + consentFlowEnabled: 0 + consentFlowPlatform: 0 + consentFlowPrivacyPolicyUrl: + consentFlowTermsOfServiceUrl: + userTrackingUsageDescriptionEn: + userTrackingUsageLocalizationEnabled: 0 + userTrackingUsageDescriptionDe: + userTrackingUsageDescriptionEs: + userTrackingUsageDescriptionFr: + userTrackingUsageDescriptionJa: + userTrackingUsageDescriptionKo: + userTrackingUsageDescriptionZhHans: + userTrackingUsageDescriptionZhHant: + adMobAndroidAppId: ca-app-pub-4689347727715111~4432754000 + adMobIosAppId: ca-app-pub-4689347727715111~4432754000 + showInternalSettingsInIntegrationManager: 0 diff --git a/Assets/MaxSdk/Resources/AppLovinSettings.asset.meta b/Assets/MaxSdk/Resources/AppLovinSettings.asset.meta new file mode 100644 index 0000000..ad40e6a --- /dev/null +++ b/Assets/MaxSdk/Resources/AppLovinSettings.asset.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46f515cb20839d5428316dcec4ccbdfd +labels: +- al_max +- al_max_export_path-MaxSdk/Resources/AppLovinSettings.asset +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources/Images.meta b/Assets/MaxSdk/Resources/Images.meta new file mode 100644 index 0000000..44e3b1b --- /dev/null +++ b/Assets/MaxSdk/Resources/Images.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45fe0b6198ac146d8a25f5ac8cd7af41 +labels: +- al_max +- al_max_export_path-MaxSdk/Resources/Images +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources/Images/alert_icon.png b/Assets/MaxSdk/Resources/Images/alert_icon.png new file mode 100644 index 0000000..1651950 Binary files /dev/null and b/Assets/MaxSdk/Resources/Images/alert_icon.png differ diff --git a/Assets/MaxSdk/Resources/Images/alert_icon.png.meta b/Assets/MaxSdk/Resources/Images/alert_icon.png.meta new file mode 100644 index 0000000..634d290 --- /dev/null +++ b/Assets/MaxSdk/Resources/Images/alert_icon.png.meta @@ -0,0 +1,94 @@ +fileFormatVersion: 2 +guid: 572fee4574afa4f6dbf2846e0c152fe8 +labels: +- al_max +- al_max_export_path-MaxSdk/Resources/Images/alert_icon.png +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources/Images/uninstall_icon.png b/Assets/MaxSdk/Resources/Images/uninstall_icon.png new file mode 100644 index 0000000..3b55354 Binary files /dev/null and b/Assets/MaxSdk/Resources/Images/uninstall_icon.png differ diff --git a/Assets/MaxSdk/Resources/Images/uninstall_icon.png.meta b/Assets/MaxSdk/Resources/Images/uninstall_icon.png.meta new file mode 100644 index 0000000..0f39816 --- /dev/null +++ b/Assets/MaxSdk/Resources/Images/uninstall_icon.png.meta @@ -0,0 +1,94 @@ +fileFormatVersion: 2 +guid: d24994f48fdd0430692e3d49279cd782 +labels: +- al_max +- al_max_export_path-MaxSdk/Resources/Images/uninstall_icon.png +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Resources/Images/warning_icon.png b/Assets/MaxSdk/Resources/Images/warning_icon.png new file mode 100644 index 0000000..cc9660e Binary files /dev/null and b/Assets/MaxSdk/Resources/Images/warning_icon.png differ diff --git a/Assets/MaxSdk/Resources/Images/warning_icon.png.meta b/Assets/MaxSdk/Resources/Images/warning_icon.png.meta new file mode 100644 index 0000000..ee4941c --- /dev/null +++ b/Assets/MaxSdk/Resources/Images/warning_icon.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: b504c956e7ed744b6b0e7f014e1cac5a +labels: +- al_max +- al_max_export_path-MaxSdk/Resources/Images/warning_icon.png +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts.meta b/Assets/MaxSdk/Scripts.meta new file mode 100644 index 0000000..0a6693e --- /dev/null +++ b/Assets/MaxSdk/Scripts.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a2c75115209744dcd915513c36d31e94 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager.meta b/Assets/MaxSdk/Scripts/IntegrationManager.meta new file mode 100644 index 0000000..39f65cc --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e01816bc45c944d03afb95d035caf0e1 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor.meta new file mode 100644 index 0000000..1d8400a --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0da229e279400497786c39933fe02e52 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs new file mode 100644 index 0000000..08e543c --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs @@ -0,0 +1,172 @@ +// +// AppLovinAutoUpdater.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 1/27/20. +// Copyright © 2020 AppLovin. All rights reserved. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// Handles auto updates for AppLovin MAX plugin. + /// + public class AppLovinAutoUpdater + { + public const string KeyAutoUpdateEnabled = "com.applovin.auto_update_enabled"; + private const string KeyLastUpdateCheckTime = "com.applovin.last_update_check_time_v2"; // Updated to v2 to force adapter version checks in plugin version 3.1.10. + private static readonly DateTime EpochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly int SecondsInADay = (int) TimeSpan.FromDays(1).TotalSeconds; + + // TODO: Make this list dynamic. + public static readonly Dictionary MinAdapterVersions = new Dictionary() + { + {"ADMOB_NETWORK", "android_23.3.0.1_ios_11.9.0.1"}, + {"BIDMACHINE_NETWORK", "android_3.0.1.1_ios_3.0.0.0.1"}, + {"CHARTBOOST_NETWORK", "android_9.7.0.3_ios_9.7.0.2"}, + {"FACEBOOK_MEDIATE", "android_6.17.0.1_ios_6.15.2.1"}, + {"FYBER_NETWORK", "android_8.3.1.1_ios_8.3.2.1"}, + {"GOOGLE_AD_MANAGER_NETWORK", "android_23.3.0.1_ios_11.9.0.1"}, + {"HYPRMX_NETWORK", "android_6.4.2.1_ios_6.4.1.0.1"}, + {"INMOBI_NETWORK", "android_10.7.7.1_ios_10.7.5.1"}, + {"IRONSOURCE_NETWORK", "android_8.3.0.0.2_ios_8.3.0.0.1"}, + {"LINE_NETWORK", "android_2024.8.27.1_ios_2.8.20240827.1"}, + {"MINTEGRAL_NETWORK", "android_16.8.51.1_ios_7.7.2.0.1"}, + {"MOBILEFUSE_NETWORK", "android_1.7.6.1_ios_1.7.6.1"}, + {"MOLOCO_NETWORK", "android_3.1.0.1_ios_3.1.3.1"}, + {"MYTARGET_NETWORK", "android_5.22.1.1_ios_5.21.7.1"}, + {"PUBMATIC_NETWORK", "android_3.9.0.2_ios_3.9.0.2"}, + {"SMAATO_NETWORK", "android_22.7.0.1_ios_22.8.4.1"}, + {"TIKTOK_NETWORK", "android_6.2.0.5.2_ios_6.2.0.7.2"}, + {"UNITY_NETWORK", "android_4.12.2.1_ios_4.12.2.1"}, + {"VERVE_NETWORK", "android_3.0.4.1_ios_3.0.4.1"}, + {"VUNGLE_NETWORK", "android_7.4.1.1_ios_7.4.1.1"}, + {"YANDEX_NETWORK", "android_7.4.0.1_ios_2.18.0.1"}, + }; + + /// + /// Checks if a new version of the plugin is available and prompts the user to update if one is available. + /// + public static void Update() + { + var now = (int) (DateTime.UtcNow - EpochTime).TotalSeconds; + if (EditorPrefs.HasKey(KeyLastUpdateCheckTime)) + { + var elapsedTime = now - EditorPrefs.GetInt(KeyLastUpdateCheckTime); + + // Check if we have checked for a new version in the last 24 hrs and skip update if we have. + if (elapsedTime < SecondsInADay) return; + } + + // Update last checked time. + EditorPrefs.SetInt(KeyLastUpdateCheckTime, now); + + // Load the plugin data + AppLovinEditorCoroutine.StartCoroutine(AppLovinIntegrationManager.Instance.LoadPluginData(data => + { + if (data == null) return; + + ShowPluginUpdateDialogIfNeeded(data); + ShowNetworkAdaptersUpdateDialogIfNeeded(data.MediatedNetworks); + ShowGoogleNetworkAdaptersUpdateDialogIfNeeded(data.MediatedNetworks); + })); + } + + private static void ShowPluginUpdateDialogIfNeeded(PluginData data) + { + // Check if publisher has disabled auto update. + if (!EditorPrefs.GetBool(KeyAutoUpdateEnabled, true)) return; + + // Check if the current and latest version are the same or if the publisher is on a newer version (on beta). If so, skip update. + var comparison = data.AppLovinMax.CurrentToLatestVersionComparisonResult; + if (comparison == MaxSdkUtils.VersionComparisonResult.Equal || comparison == MaxSdkUtils.VersionComparisonResult.Greater) return; + + // A new version of the plugin is available. Show a dialog to the publisher. + var option = EditorUtility.DisplayDialogComplex( + "AppLovin MAX Plugin Update", + "A new version of AppLovin MAX plugin is available for download. Update now?", + "Download", + "Not Now", + "Don't Ask Again"); + + if (option == 0) // Download + { + MaxSdkLogger.UserDebug("Downloading plugin..."); + AppLovinIntegrationManager.downloadPluginProgressCallback = AppLovinIntegrationManagerWindow.OnDownloadPluginProgress; + AppLovinEditorCoroutine.StartCoroutine(AppLovinIntegrationManager.Instance.DownloadPlugin(data.AppLovinMax)); + } + else if (option == 1) // Not Now + { + // Do nothing + MaxSdkLogger.UserDebug("Update postponed."); + } + else if (option == 2) // Don't Ask Again + { + MaxSdkLogger.UserDebug("Auto Update disabled. You can enable it again from the AppLovin Integration Manager"); + EditorPrefs.SetBool(KeyAutoUpdateEnabled, false); + } + } + + private static void ShowNetworkAdaptersUpdateDialogIfNeeded(Network[] networks) + { + var networksToUpdate = networks.Where(network => network.RequiresUpdate).ToList(); + + // If all networks are above the required version, do nothing. + if (networksToUpdate.Count <= 0) return; + + // We found a few adapters that are not compatible with the current SDK, show alert. + var message = "The following network adapters are not compatible with the current version of AppLovin MAX Plugin:\n"; + foreach (var networkName in networksToUpdate) + { + message += "\n- "; + message += networkName.DisplayName + " (Requires " + MinAdapterVersions[networkName.Name] + " or newer)"; + } + + message += "\n\nPlease update them to the latest versions to avoid any issues."; + + AppLovinIntegrationManager.ShowBuildFailureDialog(message); + } + + private static void ShowGoogleNetworkAdaptersUpdateDialogIfNeeded(Network[] networks) + { + // AdMob and GAM use the same SDKs so their adapters should use the same underlying SDK version. + var googleNetwork = networks.FirstOrDefault(network => network.Name.Equals("ADMOB_NETWORK")); + var googleAdManagerNetwork = networks.FirstOrDefault(network => network.Name.Equals("GOOGLE_AD_MANAGER_NETWORK")); + + // If both AdMob and GAM are not integrated, do nothing. + if (googleNetwork == null || string.IsNullOrEmpty(googleNetwork.CurrentVersions.Unity) || + googleAdManagerNetwork == null || string.IsNullOrEmpty(googleAdManagerNetwork.CurrentVersions.Unity)) return; + + var isAndroidVersionCompatible = GoogleNetworkAdaptersCompatible(googleNetwork.CurrentVersions.Android, googleAdManagerNetwork.CurrentVersions.Android, "19.8.0.0"); + var isIosVersionCompatible = GoogleNetworkAdaptersCompatible(googleNetwork.CurrentVersions.Ios, googleAdManagerNetwork.CurrentVersions.Ios, "8.0.0.0"); + + if (isAndroidVersionCompatible && isIosVersionCompatible) return; + + var message = "You may see unexpected errors if you use different versions of the AdMob and Google Ad Manager adapter SDKs. " + + "AdMob and Google Ad Manager share the same SDKs.\n\n" + + "You can be sure that you are using the same SDK for both if the first three numbers in each adapter version match."; + + AppLovinIntegrationManager.ShowBuildFailureDialog(message); + } + + private static bool GoogleNetworkAdaptersCompatible(string googleVersion, string googleAdManagerVersion, string breakingVersion) + { + var googleResult = MaxSdkUtils.CompareVersions(googleVersion, breakingVersion); + var googleAdManagerResult = MaxSdkUtils.CompareVersions(googleAdManagerVersion, breakingVersion); + + // If one is less than the breaking version and the other is not, they are not compatible. + if (googleResult == MaxSdkUtils.VersionComparisonResult.Lesser && + googleAdManagerResult != MaxSdkUtils.VersionComparisonResult.Lesser) return false; + + if (googleAdManagerResult == MaxSdkUtils.VersionComparisonResult.Lesser && + googleResult != MaxSdkUtils.VersionComparisonResult.Lesser) return false; + + return true; + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs.meta new file mode 100644 index 0000000..0070e74 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 8bcdd5226273242c5bd9ec79568202e6 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinAutoUpdater.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs new file mode 100644 index 0000000..c9cd21f --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs @@ -0,0 +1,94 @@ +// +// AppLovinBuildPostProcessor.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 10/30/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if UNITY_IOS || UNITY_IPHONE + +using System.Diagnostics; +using System.IO; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// A helper class to run command line tools. + /// + /// TODO: Currently only supports shell (Linux). Add support for Windows machines. + /// + public class AppLovinCommandLine + { + /// + /// Result obtained by running a command line command. + /// + public class Result + { + /// + /// Standard output stream from command line. + /// + public string StandardOutput; + + /// + /// Standard error stream from command line. + /// + public string StandardError; + + /// + /// Exit code returned from command line. + /// + public int ExitCode; + + /// + /// The description of the result that can be used for error logging. + /// + public string Message; + } + + /// + /// Runs a command line tool using the provided and . + /// + /// The tool path to run + /// The arguments to be passed to the command line tool + /// The directory from which to run this command. + /// + public static Result Run(string toolPath, string arguments, string workingDirectory) + { + var stdoutFileName = Path.GetTempFileName(); + var stderrFileName = Path.GetTempFileName(); + + var process = new Process(); + process.StartInfo.UseShellExecute = true; + process.StartInfo.CreateNoWindow = false; + process.StartInfo.RedirectStandardInput = false; + process.StartInfo.RedirectStandardOutput = false; + process.StartInfo.RedirectStandardError = false; + + process.StartInfo.WorkingDirectory = workingDirectory; + process.StartInfo.FileName = "bash"; + process.StartInfo.Arguments = string.Format("-l -c '\"{0}\" {1} 1> {2} 2> {3}'", toolPath, arguments, stdoutFileName, stderrFileName); + process.Start(); + + process.WaitForExit(); + + var stdout = File.ReadAllText(stdoutFileName); + var stderr = File.ReadAllText(stderrFileName); + + File.Delete(stdoutFileName); + File.Delete(stderrFileName); + + var result = new Result(); + result.StandardOutput = stdout; + result.StandardError = stderr; + result.ExitCode = process.ExitCode; + + var messagePrefix = result.ExitCode == 0 ? "Command executed successfully" : "Failed to run command"; + result.Message = string.Format("{0}: '{1} {2}'\nstdout: {3}\nstderr: {4}\nExit code: {5}", messagePrefix, toolPath, arguments, stdout, stderr, process.ExitCode); + + return result; + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs.meta new file mode 100644 index 0000000..2c3ff20 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 2d0aa55f9a7d2440f871dfb256372a33 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinCommandLine.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs new file mode 100644 index 0000000..75f359a --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs @@ -0,0 +1,75 @@ +// +// AppLovinDownloadHandler.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 7/26/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if !UNITY_2017_2_OR_NEWER + +using System; +using System.IO; +using UnityEngine.Networking; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public class AppLovinDownloadHandler : DownloadHandlerScript + { + // Required by DownloadHandler base class. Called when you address the 'bytes' property. + protected override byte[] GetData() + { + return null; + } + + private FileStream fileStream; + + public AppLovinDownloadHandler(string path) : base(new byte[2048]) + { + var downloadDirectory = Path.GetDirectoryName(path); + if (!Directory.Exists(downloadDirectory)) + { + Directory.CreateDirectory(downloadDirectory); + } + + try + { + //Open the current file to write to + fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); + } + catch (Exception exception) + { + MaxSdkLogger.UserError(string.Format("Failed to create file at {0}\n{1}", path, exception.Message)); + } + } + + protected override bool ReceiveData(byte[] byteFromServer, int dataLength) + { + if (byteFromServer == null || byteFromServer.Length < 1 || fileStream == null) + { + return false; + } + + try + { + //Write the current data to the file + fileStream.Write(byteFromServer, 0, dataLength); + } + catch (Exception exception) + { + fileStream.Close(); + fileStream = null; + MaxSdkLogger.UserError(string.Format("Failed to download file{0}", exception.Message)); + } + + return true; + } + + protected override void CompleteContent() + { + fileStream.Close(); + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs.meta new file mode 100644 index 0000000..5a69775 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: c85c3812a13e04838951767c1285e4da +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinDownloadHandler.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs new file mode 100644 index 0000000..f5be939 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs @@ -0,0 +1,91 @@ +// +// AppLovinEditorCoroutine.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 7/25/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using System.Collections; +using System.Collections.Generic; +using UnityEditor; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// A coroutine that can update based on editor application update. + /// + public class AppLovinEditorCoroutine + { + /// + /// Keeps track of the coroutine currently running. + /// + private IEnumerator enumerator; + + /// + /// Keeps track of coroutines that have yielded to the current enumerator. + /// + private readonly List history = new List(); + + private AppLovinEditorCoroutine(IEnumerator enumerator) + { + this.enumerator = enumerator; + } + + /// + /// Creates and starts a coroutine. + /// + /// The coroutine to be started + /// The coroutine that has been started. + public static AppLovinEditorCoroutine StartCoroutine(IEnumerator enumerator) + { + var coroutine = new AppLovinEditorCoroutine(enumerator); + coroutine.Start(); + return coroutine; + } + + private void Start() + { + EditorApplication.update += OnEditorUpdate; + } + + /// + /// Stops the coroutine. + /// + public void Stop() + { + if (EditorApplication.update == null) return; + + EditorApplication.update -= OnEditorUpdate; + } + + private void OnEditorUpdate() + { + if (enumerator.MoveNext()) + { + // If there is a coroutine to yield for inside the coroutine, add the initial one to history and continue the second one + if (enumerator.Current is IEnumerator) + { + history.Add(enumerator); + enumerator = (IEnumerator) enumerator.Current; + } + } + else + { + // Current coroutine has ended, check if we have more coroutines in history to be run. + if (history.Count == 0) + { + // No more coroutines to run, stop updating. + Stop(); + } + // Step out and finish the code in the coroutine that yielded to it + else + { + var index = history.Count - 1; + enumerator = history[index]; + history.RemoveAt(index); + } + } + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs.meta new file mode 100644 index 0000000..c622bab --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 95747c688378548eeb92aeb528ac96ff +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinEditorCoroutine.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs new file mode 100644 index 0000000..b15f60d --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs @@ -0,0 +1,137 @@ +// +// MaxInitialization.cs +// AppLovin MAX Unity Plugin +// +// Created by Thomas So on 5/24/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using AppLovinMax.Scripts.IntegrationManager.Editor; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + [InitializeOnLoad] + public class AppLovinInitialize + { + private static readonly List ObsoleteNetworks = new List + { + "AdColony", + "Criteo", + "Nend", + "Snap", + "Tapjoy", + "VerizonAds", + "VoodooAds" + }; + + private static readonly List ObsoleteFileExportPathsToDelete = new List + { + // The `MaxSdk/Scripts/Editor` folder contents have been moved into `MaxSdk/Scripts/IntegrationManager/Editor`. + "MaxSdk/Scripts/Editor", + "MaxSdk/Scripts/Editor.meta", + + // The `EventSystemChecker` has been renamed to `MaxEventSystemChecker`. + "MaxSdk/Scripts/EventSystemChecker.cs", + "MaxSdk/Scripts/EventSystemChecker.cs.meta", + + // Google AdMob adapter pre/post process scripts. The logic has been migrated to the main plugin. + "MaxSdk/Mediation/Google/Editor/MaxGoogleInitialize.cs", + "MaxSdk/Mediation/Google/Editor/MaxGoogleInitialize.cs.meta", + "MaxSdk/Mediation/Google/Editor/MaxMediationGoogleUtils.cs", + "MaxSdk/Mediation/Google/Editor/MaxMediationGoogleUtils.cs.meta", + "MaxSdk/Mediation/Google/Editor/PostProcessor.cs", + "MaxSdk/Mediation/Google/Editor/PostProcessor.cs.meta", + "MaxSdk/Mediation/Google/Editor/PreProcessor.cs", + "MaxSdk/Mediation/Google/Editor/PreProcessor.cs.meta", + "MaxSdk/Mediation/Google/Editor/MaxSdk.Mediation.Google.Editor.asmdef", + "MaxSdk/Mediation/Google/MaxSdk.Mediation.Google.Editor.asmdef.meta", + "Plugins/Android/MaxMediationGoogle.androidlib", + "Plugins/Android/MaxMediationGoogle.androidlib.meta", + + // Google Ad Manager adapter pre/post process scripts. The logic has been migrated to the main plugin. + "MaxSdk/Mediation/GoogleAdManager/Editor/MaxGoogleAdManagerInitialize.cs", + "MaxSdk/Mediation/GoogleAdManager/Editor/MaxGoogleAdManagerInitialize.cs.meta", + "MaxSdk/Mediation/GoogleAdManager/Editor/PostProcessor.cs", + "MaxSdk/Mediation/GoogleAdManager/Editor/PostProcessor.cs.meta", + "MaxSdk/Mediation/GoogleAdManager/Editor/MaxSdk.Mediation.GoogleAdManager.Editor.asmdef", + "MaxSdk/Mediation/GoogleAdManager/Editor/MaxSdk.Mediation.GoogleAdManager.Editor.asmdef.meta", + "Plugins/Android/MaxMediationGoogleAdManager.androidlib", + "Plugins/Android/MaxMediationGoogleAdManager.androidlib.meta", + + // The `VariableService` has been removed. + "MaxSdk/Scripts/MaxVariableServiceAndroid.cs", + "MaxSdk/Scripts/MaxVariableServiceAndroid.cs.meta", + "MaxSdk/Scripts/MaxVariableServiceiOS.cs", + "MaxSdk/Scripts/MaxVariableServiceiOS.cs.meta", + "MaxSdk/Scripts/MaxVariableServiceUnityEditor.cs", + "MaxSdk/Scripts/MaxVariableServiceUnityEditor.cs.meta", + + // The `MaxSdk/Scripts/Editor` folder contents have been moved into `MaxSdk/Scripts/IntegrationManager/Editor`. + "MaxSdk/Version.md", + "MaxSdk/Version.md.meta", + + // TODO: Add MaxTargetingData and MaxUserSegment when the plugin has enough traction. + }; + + static AppLovinInitialize() + { +#if UNITY_IOS + // Check that the publisher is targeting iOS 9.0+ + if (!PlayerSettings.iOS.targetOSVersionString.StartsWith("9.") && !PlayerSettings.iOS.targetOSVersionString.StartsWith("1")) + { + MaxSdkLogger.UserError("Detected iOS project version less than iOS 9 - The AppLovin MAX SDK WILL NOT WORK ON < iOS9!!!"); + } +#endif + + var isPluginInPackageManager = AppLovinIntegrationManager.IsPluginInPackageManager; + if (!isPluginInPackageManager) + { + var changesMade = false; + foreach (var obsoleteFileExportPathToDelete in ObsoleteFileExportPathsToDelete) + { + var pathToDelete = MaxSdkUtils.GetAssetPathForExportPath(obsoleteFileExportPathToDelete); + if (CheckExistence(pathToDelete)) + { + MaxSdkLogger.UserDebug("Deleting obsolete file '" + pathToDelete + "' that is no longer needed."); + FileUtil.DeleteFileOrDirectory(pathToDelete); + changesMade = true; + } + } + + var pluginParentDir = AppLovinIntegrationManager.PluginParentDirectory; + // Check if any obsolete networks are installed + foreach (var obsoleteNetwork in ObsoleteNetworks) + { + var networkDir = Path.Combine(pluginParentDir, "MaxSdk/Mediation/" + obsoleteNetwork); + if (CheckExistence(networkDir)) + { + MaxSdkLogger.UserDebug("Deleting obsolete network " + obsoleteNetwork + " from path " + networkDir + "..."); + FileUtil.DeleteFileOrDirectory(networkDir); + FileUtil.DeleteFileOrDirectory(networkDir + ".meta"); + changesMade = true; + } + } + + // Refresh UI + if (changesMade) + { + AssetDatabase.Refresh(); + MaxSdkLogger.UserDebug("Obsolete networks and files removed."); + } + } + + AppLovinAutoUpdater.Update(); + } + + private static bool CheckExistence(string location) + { + return File.Exists(location) || + Directory.Exists(location) || + (location.EndsWith("/*") && Directory.Exists(Path.GetDirectoryName(location))); + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs.meta new file mode 100644 index 0000000..fb8a55c --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 6b7dce7fe193a4058bc51d9f4d3a2aed +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInitialize.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs new file mode 100644 index 0000000..1f4c940 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs @@ -0,0 +1,458 @@ +// +// MaxIntegrationManager.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 6/1/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.Networking; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + [Serializable] + public class PluginData + { + public Network AppLovinMax; + public Network[] MediatedNetworks; + public Network[] PartnerMicroSdks; + public DynamicLibraryToEmbed[] ThirdPartyDynamicLibrariesToEmbed; + } + + [Serializable] + public class Network + { + // + // Sample network data: + // + // { + // "Name": "adcolony", + // "DisplayName": "AdColony", + // "DownloadUrl": "https://bintray.com/applovin/Unity-Mediation-Packages/download_file?file_path=AppLovin-AdColony-Adapters-Android-3.3.10.1-iOS-3.3.7.2.unitypackage", + // "PluginFileName": "AppLovin-AdColony-Adapters-Android-3.3.10.1-iOS-3.3.7.2.unitypackage", + // "DependenciesFilePath": "MaxSdk/Mediation/AdColony/Editor/Dependencies.xml", + // "LatestVersions" : { + // "Unity": "android_3.3.10.1_ios_3.3.7.2", + // "Android": "3.3.10.1", + // "Ios": "3.3.7.2" + // } + // } + // + + public string Name; + public string DisplayName; + public string DownloadUrl; + public string DependenciesFilePath; + public PackageInfo[] Packages; + public string[] PluginFilePaths; + public Versions LatestVersions; + [NonSerialized] public Versions CurrentVersions; + [NonSerialized] public MaxSdkUtils.VersionComparisonResult CurrentToLatestVersionComparisonResult = MaxSdkUtils.VersionComparisonResult.Lesser; + [NonSerialized] public bool RequiresUpdate; + public DynamicLibraryToEmbed[] DynamicLibrariesToEmbed; + } + + [Serializable] + public class DynamicLibraryToEmbed + { + public string PodName; + public string[] FrameworkNames; + + // Min and max versions are inclusive, so if the adapter is the min or max version, the xcframework will get embedded. + public string MinVersion; + public string MaxVersion; + + public DynamicLibraryToEmbed(string podName, string[] frameworkNames, string minVersion, string maxVersion) + { + PodName = podName; + FrameworkNames = frameworkNames; + MinVersion = minVersion; + MaxVersion = maxVersion; + } + } + + /// + /// A helper data class used to get current versions from Dependency.xml files. + /// + [Serializable] + public class Versions + { + public string Unity; + public string Android; + public string Ios; + + public override bool Equals(object value) + { + var versions = value as Versions; + + return versions != null + && Unity.Equals(versions.Unity) + && (Android == null || Android.Equals(versions.Android)) + && (Ios == null || Ios.Equals(versions.Ios)); + } + + public bool HasEqualSdkVersions(Versions versions) + { + return versions != null + && AdapterSdkVersion(Android).Equals(AdapterSdkVersion(versions.Android)) + && AdapterSdkVersion(Ios).Equals(AdapterSdkVersion(versions.Ios)); + } + + public override int GetHashCode() + { + return new {Unity, Android, Ios}.GetHashCode(); + } + + private static string AdapterSdkVersion(string adapterVersion) + { + var index = adapterVersion.LastIndexOf("."); + return index > 0 ? adapterVersion.Substring(0, index) : adapterVersion; + } + } + + /// + /// A manager class for MAX integration manager window. + /// + public class AppLovinIntegrationManager + { + /// + /// Delegate to be called when downloading a plugin with the progress percentage. + /// + /// The name of the plugin being downloaded. + /// Percentage downloaded. + /// Whether or not the download is complete. + public delegate void DownloadPluginProgressCallback(string pluginName, float progress, bool done); + + /// + /// Delegate to be called when a plugin package is imported. + /// + /// The network data for which the package is imported. + public delegate void ImportPackageCompletedCallback(Network network); + + private static readonly AppLovinIntegrationManager instance = new AppLovinIntegrationManager(); + + internal static readonly string GradleTemplatePath = Path.Combine("Assets/Plugins/Android", "mainTemplate.gradle"); + private const string MaxSdkAssetExportPath = "MaxSdk/Scripts/MaxSdk.cs"; + + private static readonly string PluginDataEndpoint = "https://unity.applovin.com/max/1.0/integration_manager_info?plugin_version={0}"; + + private static string externalDependencyManagerVersion; + + public static DownloadPluginProgressCallback downloadPluginProgressCallback; + public static ImportPackageCompletedCallback importPackageCompletedCallback; + + private UnityWebRequest webRequest; + private Network importingNetwork; + + /// + /// An Instance of the Integration manager. + /// + public static AppLovinIntegrationManager Instance + { + get { return instance; } + } + + /// + /// The parent directory path where the MaxSdk plugin directory is placed. + /// + public static string PluginParentDirectory + { + get + { + // Search for the asset with the default exported path first, In most cases, we should be able to find the asset. + // In some cases where we don't, use the platform specific export path to search for the asset (in case of migrating a project from Windows to Mac or vice versa). + var maxSdkScriptAssetPath = MaxSdkUtils.GetAssetPathForExportPath(MaxSdkAssetExportPath); + + // maxSdkScriptAssetPath will always have AltDirectorySeparatorChar (/) as the path separator. Convert to platform specific path. + return maxSdkScriptAssetPath.Replace(MaxSdkAssetExportPath, "") + .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + } + } + + /// + /// Whether or not the plugin is in the Unity Package Manager. + /// + public static bool IsPluginInPackageManager + { + get { return PluginParentDirectory.StartsWith("Packages"); } + } + + /// + /// Whether or not gradle build system is enabled. + /// + public static bool GradleBuildEnabled + { + get { return GetEditorUserBuildSetting("androidBuildSystem", "").ToString().Equals("Gradle"); } + } + + /// + /// Whether or not Gradle template is enabled. + /// + public static bool GradleTemplateEnabled + { + get { return GradleBuildEnabled && File.Exists(GradleTemplatePath); } + } + + /// + /// Whether or not the Quality Service settings can be processed which requires Gradle template enabled or Unity IDE newer than version 2018_2. + /// + public static bool CanProcessAndroidQualityServiceSettings + { + get { return GradleTemplateEnabled || GradleBuildEnabled; } + } + + /// + /// The External Dependency Manager version obtained dynamically. + /// + public static string ExternalDependencyManagerVersion + { + get + { + if (!string.IsNullOrEmpty(externalDependencyManagerVersion)) return externalDependencyManagerVersion; + + try + { + var versionHandlerVersionNumberType = Type.GetType("Google.VersionHandlerVersionNumber, Google.VersionHandlerImpl"); + externalDependencyManagerVersion = versionHandlerVersionNumberType.GetProperty("Value").GetValue(null, null).ToString(); + } +#pragma warning disable 0168 + catch (Exception ignored) +#pragma warning restore 0168 + { + externalDependencyManagerVersion = "Failed to get version."; + } + + return externalDependencyManagerVersion; + } + } + + private AppLovinIntegrationManager() + { + // Add asset import callbacks. + AssetDatabase.importPackageCompleted += packageName => + { + if (!IsImportingNetwork(packageName)) return; + + AssetDatabase.Refresh(); + + CallImportPackageCompletedCallback(importingNetwork); + importingNetwork = null; + }; + + AssetDatabase.importPackageCancelled += packageName => + { + if (!IsImportingNetwork(packageName)) return; + + MaxSdkLogger.UserDebug("Package import cancelled."); + importingNetwork = null; + }; + + AssetDatabase.importPackageFailed += (packageName, errorMessage) => + { + if (!IsImportingNetwork(packageName)) return; + + MaxSdkLogger.UserError(errorMessage); + importingNetwork = null; + }; + } + + static AppLovinIntegrationManager() { } + + public static PluginData LoadPluginDataSync() + { + var url = string.Format(PluginDataEndpoint, MaxSdk.Version); + using (var unityWebRequest = UnityWebRequest.Get(url)) + { + var operation = unityWebRequest.SendWebRequest(); + + // Just wait till www is done + while (!operation.isDone) { } + + return CreatePluginDataFromWebResponse(unityWebRequest); + } + } + + /// + /// Loads the plugin data to be display by integration manager window. + /// + /// Callback to be called once the plugin data download completes. + public IEnumerator LoadPluginData(Action callback) + { + var url = string.Format(PluginDataEndpoint, MaxSdk.Version); + using (var unityWebRequest = UnityWebRequest.Get(url)) + { + var operation = unityWebRequest.SendWebRequest(); + + while (!operation.isDone) yield return new WaitForSeconds(0.1f); // Just wait till www is done. Our coroutine is pretty rudimentary. + + var pluginData = CreatePluginDataFromWebResponse(unityWebRequest); + + callback(pluginData); + } + } + + private static PluginData CreatePluginDataFromWebResponse(UnityWebRequest unityWebRequest) + { +#if UNITY_2020_1_OR_NEWER + if (unityWebRequest.result != UnityWebRequest.Result.Success) +#else + if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) +#endif + { + MaxSdkLogger.E("Failed to load plugin data. Please check your internet connection."); + return null; + } + + PluginData pluginData; + try + { + pluginData = JsonUtility.FromJson(unityWebRequest.downloadHandler.text); + AppLovinPackageManager.PluginData = pluginData; + } + catch (Exception exception) + { + Console.WriteLine(exception); + pluginData = null; + } + + if (pluginData == null) return null; + + // Get current version of the plugin + var appLovinMax = pluginData.AppLovinMax; + AppLovinPackageManager.UpdateCurrentVersions(appLovinMax); + + // Get current versions for all the mediation networks. + foreach (var network in pluginData.MediatedNetworks) + { + AppLovinPackageManager.UpdateCurrentVersions(network); + } + + foreach (var partnerMicroSdk in pluginData.PartnerMicroSdks) + { + AppLovinPackageManager.UpdateCurrentVersions(partnerMicroSdk); + } + + return pluginData; + } + + /// + /// Downloads the plugin file for a given network. + /// + /// Network for which to download the current version. + /// Whether or not to show the import window when downloading. Defaults to true. + /// + public IEnumerator DownloadPlugin(Network network, bool showImport = true) + { + var path = Path.Combine(Application.temporaryCachePath, GetPluginFileName(network)); // TODO: Maybe delete plugin file after finishing import. + var downloadHandler = new DownloadHandlerFile(path); + webRequest = new UnityWebRequest(network.DownloadUrl) + { + method = UnityWebRequest.kHttpVerbGET, + downloadHandler = downloadHandler + }; + + var operation = webRequest.SendWebRequest(); + while (!operation.isDone) + { + yield return new WaitForSeconds(0.1f); // Just wait till webRequest is completed. Our coroutine is pretty rudimentary. + CallDownloadPluginProgressCallback(network.DisplayName, operation.progress, operation.isDone); + } + +#if UNITY_2020_1_OR_NEWER + if (webRequest.result != UnityWebRequest.Result.Success) +#else + if (webRequest.isNetworkError || webRequest.isHttpError) +#endif + { + MaxSdkLogger.UserError(webRequest.error); + } + else + { + importingNetwork = network; + AssetDatabase.ImportPackage(path, showImport); + } + + webRequest.Dispose(); + webRequest = null; + } + + /// + /// Cancels the plugin download if one is in progress. + /// + public void CancelDownload() + { + if (webRequest == null) return; + + webRequest.Abort(); + } + + /// + /// Shows a dialog to the user with the given message and logs the error message to console. + /// + /// The failure message to be shown to the user. + public static void ShowBuildFailureDialog(string message) + { + var openIntegrationManager = EditorUtility.DisplayDialog("AppLovin MAX", message, "Open Integration Manager", "Dismiss"); + if (openIntegrationManager) + { + AppLovinIntegrationManagerWindow.ShowManager(); + } + + MaxSdkLogger.UserError(message); + } + + #region Utility Methods + + /// + /// Checks whether or not the given package name is the currently importing package. + /// + /// The name of the package that needs to be checked. + /// true if the importing package matches the given package name. + private bool IsImportingNetwork(string packageName) + { + // Note: The pluginName doesn't have the '.unitypackage' extension included in its name but the pluginFileName does. So using Contains instead of Equals. + return importingNetwork != null && GetPluginFileName(importingNetwork).Contains(packageName); + } + + private static void CallDownloadPluginProgressCallback(string pluginName, float progress, bool isDone) + { + if (downloadPluginProgressCallback == null) return; + + downloadPluginProgressCallback(pluginName, progress, isDone); + } + + private static void CallImportPackageCompletedCallback(Network network) + { + if (importPackageCompletedCallback == null) return; + + importPackageCompletedCallback(network); + } + + private static object GetEditorUserBuildSetting(string name, object defaultValue) + { + var editorUserBuildSettingsType = typeof(EditorUserBuildSettings); + var property = editorUserBuildSettingsType.GetProperty(name); + if (property != null) + { + var value = property.GetValue(null, null); + if (value != null) return value; + } + + return defaultValue; + } + + private static string GetPluginFileName(Network network) + { + return network.Name.ToLowerInvariant() + "_" + network.LatestVersions.Unity + ".unitypackage"; + } + + #endregion + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs.meta new file mode 100644 index 0000000..e9e3603 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: c5b874c1e65274159bcc0dc15d9458cc +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManager.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs new file mode 100644 index 0000000..6f50f25 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs @@ -0,0 +1,80 @@ +using System; +using System.Linq; +using UnityEngine; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public static class AppLovinIntegrationManagerUtils + { + /// + /// Compares AppLovin MAX Unity mediation adapter plugin versions. Returns , , + /// or as the first version is less than, equal to, or greater than the second. + /// + /// If a version for a specific platform is only present in one of the provided versions, the one that contains it is considered newer. + /// + /// The first version to be compared. + /// The second version to be compared. + /// + /// if versionA is less than versionB. + /// if versionA and versionB are equal. + /// if versionA is greater than versionB. + /// + internal static MaxSdkUtils.VersionComparisonResult CompareUnityMediationVersions(string versionA, string versionB) + { + if (versionA.Equals(versionB)) return MaxSdkUtils.VersionComparisonResult.Equal; + + // Unity version would be of format: android_w.x.y.z_ios_a.b.c.d + // For Android only versions it would be: android_w.x.y.z + // For iOS only version it would be: ios_a.b.c.d + + // After splitting into their respective components, the versions would be at the odd indices. + var versionAComponents = versionA.Split('_').ToList(); + var versionBComponents = versionB.Split('_').ToList(); + + var androidComparison = MaxSdkUtils.VersionComparisonResult.Equal; + if (versionA.Contains("android") && versionB.Contains("android")) + { + var androidVersionA = versionAComponents[1]; + var androidVersionB = versionBComponents[1]; + androidComparison = MaxSdkUtils.CompareVersions(androidVersionA, androidVersionB); + + // Remove the Android version component so that iOS versions can be processed. + versionAComponents.RemoveRange(0, 2); + versionBComponents.RemoveRange(0, 2); + } + else if (versionA.Contains("android")) + { + androidComparison = MaxSdkUtils.VersionComparisonResult.Greater; + + // Remove the Android version component so that iOS versions can be processed. + versionAComponents.RemoveRange(0, 2); + } + else if (versionB.Contains("android")) + { + androidComparison = MaxSdkUtils.VersionComparisonResult.Lesser; + + // Remove the Android version component so that iOS version can be processed. + versionBComponents.RemoveRange(0, 2); + } + + var iosComparison = MaxSdkUtils.VersionComparisonResult.Equal; + if (versionA.Contains("ios") && versionB.Contains("ios")) + { + var iosVersionA = versionAComponents[1]; + var iosVersionB = versionBComponents[1]; + iosComparison = MaxSdkUtils.CompareVersions(iosVersionA, iosVersionB); + } + else if (versionA.Contains("ios")) + { + iosComparison = MaxSdkUtils.VersionComparisonResult.Greater; + } + else if (versionB.Contains("ios")) + { + iosComparison = MaxSdkUtils.VersionComparisonResult.Lesser; + } + + // If either one of the Android or iOS version is greater, the entire version should be greater. + return (androidComparison == MaxSdkUtils.VersionComparisonResult.Greater || iosComparison == MaxSdkUtils.VersionComparisonResult.Greater) ? MaxSdkUtils.VersionComparisonResult.Greater : MaxSdkUtils.VersionComparisonResult.Lesser; + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs.meta new file mode 100644 index 0000000..9efcdd9 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 96efb4dba39eb48d2a60afab69786e6a +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerUtils.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs new file mode 100644 index 0000000..151d5d6 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs @@ -0,0 +1,1071 @@ +// +// MaxIntegrationManager.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 5/27/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using System; +using System.Collections; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public class AppLovinIntegrationManagerWindow : EditorWindow + { + private const string windowTitle = "AppLovin Integration Manager"; + + private const string appLovinSdkKeyLink = "https://dash.applovin.com/o/account#keys"; + + private const string userTrackingUsageDescriptionDocsLink = "https://developer.apple.com/documentation/bundleresources/information_property_list/nsusertrackingusagedescription"; + private const string documentationTermsAndPrivacyPolicyFlow = "https://developers.applovin.com/en/unity/overview/terms-and-privacy-policy-flow"; + private const string documentationAdaptersLink = "https://developers.applovin.com/en/unity/preparing-mediated-networks"; + private const string documentationNote = "Please ensure that integration instructions (e.g. permissions, ATS settings, etc) specific to each network are implemented as well. Click the link below for more info:"; + private const string uninstallIconExportPath = "MaxSdk/Resources/Images/uninstall_icon.png"; + private const string alertIconExportPath = "MaxSdk/Resources/Images/alert_icon.png"; + private const string warningIconExportPath = "MaxSdk/Resources/Images/warning_icon.png"; + + private const string qualityServiceRequiresGradleBuildErrorMsg = "AppLovin Quality Service integration via AppLovin Integration Manager requires Custom Gradle Template enabled or Unity 2018.2 or higher.\n" + + "If you would like to continue using your existing setup, please add Quality Service Plugin to your build.gradle manually."; + + private const string customGradleVersionTooltip = "To set the version to 6.9.3, set the field to: https://services.gradle.org/distributions/gradle-6.9.3-bin.zip"; + private const string customGradleToolsVersionTooltip = "To set the version to 4.2.0, set the field to: 4.2.0"; + + private const string keyShowMicroSdkPartners = "com.applovin.show_micro_sdk_partners"; + private const string keyShowMediatedNetworks = "com.applovin.show_mediated_networks"; + private const string keyShowSdkSettings = "com.applovin.show_sdk_settings"; + private const string keyShowPrivacySettings = "com.applovin.show_privacy_settings"; + private const string keyShowOtherSettings = "com.applovin.show_other_settings"; + + private const string expandButtonText = "+"; + private const string collapseButtonText = "-"; + + private const string externalDependencyManagerPath = "Assets/ExternalDependencyManager"; + + private readonly string[] termsFlowPlatforms = new string[3] {"Both", "Android", "iOS"}; + private readonly string[] debugUserGeographies = new string[2] {"Not Set", "GDPR"}; + + private Vector2 scrollPosition; + private static readonly Vector2 windowMinSize = new Vector2(750, 750); + private const float actionFieldWidth = 60f; + private const float upgradeAllButtonWidth = 80f; + private const float networkFieldMinWidth = 100f; + private const float versionFieldMinWidth = 190f; + private const float privacySettingLabelWidth = 250f; + private const float networkFieldWidthPercentage = 0.22f; + private const float versionFieldWidthPercentage = 0.36f; // There are two version fields. Each take 40% of the width, network field takes the remaining 20%. + private static float previousWindowWidth = windowMinSize.x; + private static GUILayoutOption networkWidthOption = GUILayout.Width(networkFieldMinWidth); + private static GUILayoutOption versionWidthOption = GUILayout.Width(versionFieldMinWidth); + + private static GUILayoutOption privacySettingFieldWidthOption = GUILayout.Width(400); + private static readonly GUILayoutOption fieldWidth = GUILayout.Width(actionFieldWidth); + private static readonly GUILayoutOption upgradeAllButtonFieldWidth = GUILayout.Width(upgradeAllButtonWidth); + private static readonly GUILayoutOption collapseButtonWidthOption = GUILayout.Width(20f); + + private static readonly Color darkModeTextColor = new Color(0.29f, 0.6f, 0.8f); + + private GUIStyle titleLabelStyle; + private GUIStyle headerLabelStyle; + private GUIStyle environmentValueStyle; + private GUIStyle wrapTextLabelStyle; + private GUIStyle linkLabelStyle; + private GUIStyle iconStyle; + + private PluginData pluginData; + private bool pluginDataLoadFailed; + private bool shouldShowGoogleWarning; + private bool networkButtonsEnabled = true; + + private AppLovinEditorCoroutine loadDataCoroutine; + private Texture2D uninstallIcon; + private Texture2D alertIcon; + private Texture2D warningIcon; + + public static void ShowManager() + { + var manager = GetWindow(utility: true, title: windowTitle, focus: true); + manager.minSize = windowMinSize; + } + + #region Editor Window Lifecyle Methods + + private void Awake() + { + titleLabelStyle = new GUIStyle(EditorStyles.label) + { + fontSize = 14, + fontStyle = FontStyle.Bold, + fixedHeight = 20 + }; + + headerLabelStyle = new GUIStyle(EditorStyles.label) + { + fontSize = 12, + fontStyle = FontStyle.Bold, + fixedHeight = 18 + }; + + environmentValueStyle = new GUIStyle(EditorStyles.label) + { + alignment = TextAnchor.MiddleRight + }; + + linkLabelStyle = new GUIStyle(EditorStyles.label) + { + wordWrap = true, + normal = {textColor = EditorGUIUtility.isProSkin ? darkModeTextColor : Color.blue} + }; + + wrapTextLabelStyle = new GUIStyle(EditorStyles.label) + { + wordWrap = true + }; + + iconStyle = new GUIStyle(EditorStyles.miniButton) + { + fixedWidth = 18, + fixedHeight = 18, + padding = new RectOffset(1, 1, 1, 1) + }; + + // Load uninstall icon texture. + var uninstallIconData = File.ReadAllBytes(MaxSdkUtils.GetAssetPathForExportPath(uninstallIconExportPath)); + uninstallIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false); // 1. Initial size doesn't matter here, will be automatically resized once the image asset is loaded. 2. Set mipChain to false, else the texture has a weird blurry effect. + uninstallIcon.LoadImage(uninstallIconData); + + // Load alert icon texture. + var alertIconData = File.ReadAllBytes(MaxSdkUtils.GetAssetPathForExportPath(alertIconExportPath)); + alertIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false); + alertIcon.LoadImage(alertIconData); + + // Load warning icon texture. + var warningIconData = File.ReadAllBytes(MaxSdkUtils.GetAssetPathForExportPath(warningIconExportPath)); + warningIcon = new Texture2D(0, 0, TextureFormat.RGBA32, false); + warningIcon.LoadImage(warningIconData); + } + + private void OnEnable() + { + // Script reloads can cause AppLovinSettings.Instance to be null for one frame, + // so we load the Integration Manager on the following frame + if (AppLovinSettings.Instance == null) + { + AppLovinEditorCoroutine.StartCoroutine(WaitForNextFrameForEnable()); + } + else + { + OnWindowEnabled(); + } + } + + private IEnumerator WaitForNextFrameForEnable() + { + yield return new WaitForEndOfFrame(); + OnWindowEnabled(); + } + + private void OnWindowEnabled() + { + AppLovinIntegrationManager.downloadPluginProgressCallback = OnDownloadPluginProgress; + + // Plugin downloaded and imported. Update current versions for the imported package. + AppLovinIntegrationManager.importPackageCompletedCallback = OnImportPackageCompleted; + + Load(); + } + + private void OnDisable() + { + if (loadDataCoroutine != null) + { + loadDataCoroutine.Stop(); + loadDataCoroutine = null; + } + + AppLovinIntegrationManager.Instance.CancelDownload(); + EditorUtility.ClearProgressBar(); + + // Saves the AppLovinSettings object if it has been changed. + AssetDatabase.SaveAssets(); + } + + private void OnGUI() + { + // OnGUI is called on each frame draw, so we don't want to do any unnecessary calculation if we can avoid it. So only calculate it when the width actually changed. + if (Math.Abs(previousWindowWidth - position.width) > 1) + { + previousWindowWidth = position.width; + CalculateFieldWidth(); + } + + using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPosition, false, false)) + { + scrollPosition = scrollView.scrollPosition; + + GUILayout.Space(5); + + // Draw AppLovin MAX plugin details + EditorGUILayout.LabelField("AppLovin MAX Plugin Details", titleLabelStyle); + + DrawPluginDetails(); + + if (pluginData != null && pluginData.PartnerMicroSdks != null) + { + DrawCollapsableSection(keyShowMicroSdkPartners, "AppLovin Micro SDK Partners", DrawPartnerMicroSdks); + } + + // Draw mediated networks); + EditorGUILayout.BeginHorizontal(); + var showDetails = DrawExpandCollapseButton(keyShowMediatedNetworks); + EditorGUILayout.LabelField("Mediated Networks", titleLabelStyle); + GUILayout.FlexibleSpace(); + DrawUpgradeAllButton(); + EditorGUILayout.EndHorizontal(); + if (showDetails) + { + DrawMediatedNetworks(); + } + +#if UNITY_2019_2_OR_NEWER + if (!AppLovinIntegrationManager.IsPluginInPackageManager) + { + EditorGUILayout.LabelField("Unity Package Manager Migration", titleLabelStyle); + DrawPluginMigrationHelper(); + } +#endif + + // Draw AppLovin Quality Service settings + DrawCollapsableSection(keyShowSdkSettings, "SDK Settings", DrawQualityServiceSettings); + + DrawCollapsableSection(keyShowPrivacySettings, "Privacy Settings", DrawPrivacySettings); + + DrawCollapsableSection(keyShowOtherSettings, "Other Settings", DrawOtherSettings); + + // Draw Unity environment details + EditorGUILayout.LabelField("Unity Environment Details", titleLabelStyle); + DrawUnityEnvironmentDetails(); + + // Draw documentation notes + EditorGUILayout.LabelField(new GUIContent(documentationNote), wrapTextLabelStyle); + if (GUILayout.Button(new GUIContent(documentationAdaptersLink), linkLabelStyle)) + { + Application.OpenURL(documentationAdaptersLink); + } + } + + if (GUI.changed) + { + AppLovinSettings.Instance.SaveAsync(); + AppLovinInternalSettings.Instance.Save(); + } + } + + #endregion + + #region UI Methods + + /// + /// Shows failure or loading screen based on whether or not plugin data failed to load. + /// + private void DrawEmptyPluginData() + { + GUILayout.Space(5); + + // Plugin data failed to load. Show error and retry button. + if (pluginDataLoadFailed) + { + GUILayout.Space(10); + GUILayout.BeginHorizontal(); + GUILayout.Space(5); + EditorGUILayout.LabelField("Failed to load plugin data. Please click retry or restart the integration manager.", titleLabelStyle); + if (GUILayout.Button("Retry", fieldWidth)) + { + pluginDataLoadFailed = false; + Load(); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + GUILayout.Space(10); + } + // Still loading, show loading label. + else + { + GUILayout.Space(10); + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + EditorGUILayout.LabelField("Loading data...", titleLabelStyle); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.Space(10); + } + + GUILayout.Space(5); + } + + /// + /// Draws AppLovin MAX plugin details. + /// + private void DrawPluginDetails() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + // Draw plugin version details + DrawHeaders("Platform", false); + + // Immediately after downloading and importing a plugin the entire IDE reloads and current versions can be null in that case. Will just show loading text in that case. + if (pluginData == null || pluginData.AppLovinMax.CurrentVersions == null) + { + DrawEmptyPluginData(); + } + else + { + var appLovinMax = pluginData.AppLovinMax; + // Check if a newer version is available to enable the upgrade button. + var upgradeButtonEnabled = appLovinMax.CurrentToLatestVersionComparisonResult == MaxSdkUtils.VersionComparisonResult.Lesser; + DrawPluginDetailRow("Unity 3D", appLovinMax.CurrentVersions.Unity, appLovinMax.LatestVersions.Unity); + DrawPluginDetailRow("Android", appLovinMax.CurrentVersions.Android, appLovinMax.LatestVersions.Android); + DrawPluginDetailRow("iOS", appLovinMax.CurrentVersions.Ios, appLovinMax.LatestVersions.Ios); + + // BeginHorizontal combined with FlexibleSpace makes sure that the button is centered horizontally. + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + + GUI.enabled = upgradeButtonEnabled; + if (GUILayout.Button(new GUIContent("Upgrade"), fieldWidth)) + { + AppLovinEditorCoroutine.StartCoroutine(AppLovinPackageManager.AddNetwork(pluginData.AppLovinMax, true)); + } + + GUI.enabled = true; + GUILayout.Space(5); + GUILayout.EndHorizontal(); + + GUILayout.Space(5); + } + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + /// + /// Draws the headers for a table. + /// + private void DrawHeaders(string firstColumnTitle, bool drawAction) + { + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Space(5); + EditorGUILayout.LabelField(firstColumnTitle, headerLabelStyle, networkWidthOption); + EditorGUILayout.LabelField("Current Version", headerLabelStyle, versionWidthOption); + GUILayout.Space(3); + EditorGUILayout.LabelField("Latest Version", headerLabelStyle, versionWidthOption); + GUILayout.Space(3); + if (drawAction) + { + GUILayout.FlexibleSpace(); + GUILayout.Button("Actions", headerLabelStyle, fieldWidth); + GUILayout.Space(5); + } + } + + GUILayout.Space(4); + } + + /// + /// Draws the platform specific version details for AppLovin MAX plugin. + /// + private void DrawPluginDetailRow(string platform, string currentVersion, string latestVersion) + { + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Space(5); + EditorGUILayout.LabelField(new GUIContent(platform), networkWidthOption); + EditorGUILayout.LabelField(new GUIContent(currentVersion), versionWidthOption); + GUILayout.Space(3); + EditorGUILayout.LabelField(new GUIContent(latestVersion), versionWidthOption); + GUILayout.Space(3); + } + + GUILayout.Space(4); + } + + /// + /// Draws mediated network details table. + /// + private void DrawMediatedNetworks() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + DrawHeaders("Network", true); + + // Immediately after downloading and importing a plugin the entire IDE reloads and current versions can be null in that case. Will just show loading text in that case. + if (pluginData == null || pluginData.AppLovinMax.CurrentVersions == null) + { + DrawEmptyPluginData(); + } + else + { + var networks = pluginData.MediatedNetworks; + foreach (var network in networks) + { + DrawNetworkDetailRow(network); + } + + GUILayout.Space(10); + } + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + private void DrawPartnerMicroSdks() + { + if (pluginData == null) return; + + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + DrawHeaders("Network", true); + + var partnerMicroSdks = pluginData.PartnerMicroSdks; + foreach (var partnerMicroSdk in partnerMicroSdks) + { + DrawNetworkDetailRow(partnerMicroSdk); + } + + GUILayout.Space(10); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + /// + /// Draws the network specific details for a given network. + /// + private void DrawNetworkDetailRow(Network network) + { + string action; + var currentVersion = network.CurrentVersions != null ? network.CurrentVersions.Unity : ""; + var latestVersion = network.LatestVersions.Unity; + bool isActionEnabled; + bool isInstalled; + if (string.IsNullOrEmpty(currentVersion)) + { + action = "Install"; + currentVersion = "Not Installed"; + isActionEnabled = true; + isInstalled = false; + } + else + { + isInstalled = true; + + var comparison = network.CurrentToLatestVersionComparisonResult; + // A newer version is available + if (comparison == MaxSdkUtils.VersionComparisonResult.Lesser) + { + action = "Upgrade"; + isActionEnabled = true; + } + // Current installed version is newer than latest version from DB (beta version) + else if (comparison == MaxSdkUtils.VersionComparisonResult.Greater) + { + action = "Installed"; + isActionEnabled = false; + } + // Already on the latest version + else + { + action = "Installed"; + isActionEnabled = false; + } + } + + GUILayout.Space(4); + using (new EditorGUILayout.HorizontalScope(GUILayout.ExpandHeight(false))) + { + GUILayout.Space(5); + EditorGUILayout.LabelField(new GUIContent(network.DisplayName), networkWidthOption); + EditorGUILayout.LabelField(new GUIContent(currentVersion), versionWidthOption); + GUILayout.Space(3); + EditorGUILayout.LabelField(new GUIContent(latestVersion), versionWidthOption); + GUILayout.Space(3); + GUILayout.FlexibleSpace(); + + if (network.RequiresUpdate) + { + GUILayout.Label(new GUIContent {image = alertIcon, tooltip = "Adapter not compatible, please update to the latest version."}, iconStyle); + } + else if ((network.Name.Equals("ADMOB_NETWORK") || network.Name.Equals("GOOGLE_AD_MANAGER_NETWORK")) && shouldShowGoogleWarning) + { + GUILayout.Label(new GUIContent {image = warningIcon, tooltip = "You may see unexpected errors if you use different versions of the AdMob and Google Ad Manager adapter SDKs."}, iconStyle); + } + + GUI.enabled = networkButtonsEnabled && isActionEnabled; + if (GUILayout.Button(new GUIContent(action), fieldWidth)) + { + AppLovinEditorCoroutine.StartCoroutine(AppLovinPackageManager.AddNetwork(network, true)); + } + + GUI.enabled = true; + GUILayout.Space(2); + + GUI.enabled = networkButtonsEnabled && isInstalled; + if (GUILayout.Button(new GUIContent {image = uninstallIcon, tooltip = "Uninstall"}, iconStyle)) + { + EditorUtility.DisplayProgressBar("Integration Manager", "Deleting " + network.Name + "...", 0.5f); + AppLovinPackageManager.RemoveNetwork(network); + EditorUtility.ClearProgressBar(); + } + + GUI.enabled = true; + GUILayout.Space(5); + } + + if (isInstalled) + { + DrawGoogleAppIdTextBoxIfNeeded(network); + } + } + + private void DrawGoogleAppIdTextBoxIfNeeded(Network network) + { + // Custom integration for AdMob where the user can enter the Android and iOS App IDs. + if (network.Name.Equals("ADMOB_NETWORK")) + { + // Show only one set of text boxes if both ADMOB and GAM are installed + if (AppLovinPackageManager.IsAdapterInstalled(pluginData, "GOOGLE_AD_MANAGER_NETWORK")) return; + + DrawGoogleAppIdTextBox(); + } + // Custom integration for GAM where the user can enter the Android and iOS App IDs. + else if (network.Name.Equals("GOOGLE_AD_MANAGER_NETWORK")) + { + DrawGoogleAppIdTextBox(); + } + } + + /// + /// Draws the text box for GAM or ADMOB to input the App ID + /// + private void DrawGoogleAppIdTextBox() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(20); + using (new EditorGUILayout.VerticalScope("box")) + { + GUILayout.Space(2); + AppLovinSettings.Instance.AdMobAndroidAppId = DrawTextField("App ID (Android)", AppLovinSettings.Instance.AdMobAndroidAppId, networkWidthOption); + AppLovinSettings.Instance.AdMobIosAppId = DrawTextField("App ID (iOS)", AppLovinSettings.Instance.AdMobIosAppId, networkWidthOption); + } + + GUILayout.EndHorizontal(); + } + + /// + /// Draws the upgrade all button + /// + private void DrawUpgradeAllButton() + { + GUI.enabled = NetworksRequireUpgrade(); + if (GUILayout.Button(new GUIContent("Upgrade All"), upgradeAllButtonFieldWidth)) + { + AppLovinEditorCoroutine.StartCoroutine(UpgradeAllNetworks()); + } + + GUI.enabled = true; + GUILayout.Space(10); + } + +#if UNITY_2019_2_OR_NEWER + private void DrawPluginMigrationHelper() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + GUILayout.Space(5); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.LabelField(new GUIContent("This will migrate the AppLovin MAX Unity Plugin and adapters to the Unity Package Manager."), wrapTextLabelStyle); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + + GUI.enabled = true; + GUILayout.Space(3); + GUILayout.FlexibleSpace(); + + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + var migrationText = "Upgrade All Adapters and Migrate to UPM"; + if (GUILayout.Button(new GUIContent(migrationText))) + { + if (EditorUtility.DisplayDialog("Migrate to UPM?", + "Are you sure you want to migrate the SDK and adapters to UPM? This action will move both the MAX SDK and its adapters.", "Yes", "No")) + { + var deleteExternalDependencyManager = false; + if (Directory.Exists(externalDependencyManagerPath)) + { + deleteExternalDependencyManager = EditorUtility.DisplayDialog("External Dependency Manager Detected", + "Our plugin includes the External Dependency Manager via the Unity Package Manager. Would you like us to automatically remove the existing External Dependency Manager folder, or would you prefer to manage it manually?", "Remove Automatically", "Manage Manually"); + } + + AppLovinPluginMigrationHelper.MigrateToUnityPackageManager(pluginData, deleteExternalDependencyManager); + } + } + + GUILayout.Space(10); + GUILayout.EndHorizontal(); + + GUILayout.Space(5); + EditorGUILayout.HelpBox("Ensure all changes are committed before migration.", MessageType.Warning); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } +#endif + + private void DrawQualityServiceSettings() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + GUILayout.Space(4); + if (!AppLovinIntegrationManager.CanProcessAndroidQualityServiceSettings) + { + GUILayout.Space(4); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.HelpBox(qualityServiceRequiresGradleBuildErrorMsg, MessageType.Warning); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + + GUILayout.Space(4); + } + + AppLovinSettings.Instance.SdkKey = DrawTextField("AppLovin SDK Key", AppLovinSettings.Instance.SdkKey, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + GUILayout.Button("You can find your SDK key here: ", wrapTextLabelStyle, GUILayout.Width(185)); // Setting a fixed width since Unity adds arbitrary padding at the end leaving a space between link and text. + if (GUILayout.Button(new GUIContent(appLovinSdkKeyLink), linkLabelStyle)) + { + Application.OpenURL(appLovinSdkKeyLink); + } + + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + + GUILayout.Space(4); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + AppLovinSettings.Instance.QualityServiceEnabled = GUILayout.Toggle(AppLovinSettings.Instance.QualityServiceEnabled, " Enable MAX Ad Review"); + GUILayout.EndHorizontal(); + GUILayout.Space(4); + + GUILayout.Space(4); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + private string DrawTextField(string fieldTitle, string text, GUILayoutOption labelWidth, GUILayoutOption textFieldWidthOption = null, bool isTextFieldEditable = true, string tooltip = "") + { + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + var guiContent = MaxSdkUtils.IsValidString(tooltip) ? new GUIContent(fieldTitle, tooltip) : new GUIContent(fieldTitle); + EditorGUILayout.LabelField(guiContent, labelWidth); + GUILayout.Space(4); + if (isTextFieldEditable) + { + text = (textFieldWidthOption == null) ? GUILayout.TextField(text) : GUILayout.TextField(text, textFieldWidthOption); + } + else + { + if (textFieldWidthOption == null) + { + GUILayout.Label(text); + } + else + { + GUILayout.Label(text, textFieldWidthOption); + } + } + + GUILayout.Space(4); + GUILayout.EndHorizontal(); + GUILayout.Space(4); + + return text; + } + + private void DrawPrivacySettings() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + DrawConsentFlowSettings(); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + private void DrawConsentFlowSettings() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + AppLovinInternalSettings.Instance.ConsentFlowEnabled = GUILayout.Toggle(AppLovinInternalSettings.Instance.ConsentFlowEnabled, " Enable MAX Terms and Privacy Policy Flow"); + GUILayout.EndHorizontal(); + GUILayout.Space(6); + GUILayout.Space(4); + EditorGUILayout.HelpBox("This flow automatically includes Google UMP.", MessageType.Info); + + GUI.enabled = true; + + if (!AppLovinInternalSettings.Instance.ConsentFlowEnabled) return; + + GUILayout.Space(6); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.LabelField("Click the link below to access the guide on creating the GDPR form within AdMob's dashboard."); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + if (GUILayout.Button(new GUIContent(documentationTermsAndPrivacyPolicyFlow), linkLabelStyle)) + { + Application.OpenURL(documentationTermsAndPrivacyPolicyFlow); + } + + GUILayout.Space(4); + GUILayout.EndHorizontal(); + + GUILayout.Space(8); + + AppLovinInternalSettings.Instance.ConsentFlowPrivacyPolicyUrl = DrawTextField("Privacy Policy URL", AppLovinInternalSettings.Instance.ConsentFlowPrivacyPolicyUrl, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption); + AppLovinInternalSettings.Instance.ConsentFlowTermsOfServiceUrl = DrawTextField("Terms of Service URL (optional)", AppLovinInternalSettings.Instance.ConsentFlowTermsOfServiceUrl, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption); + + GUILayout.Space(4); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.LabelField("iOS specific settings:", headerLabelStyle); + GUILayout.EndHorizontal(); + + var isEditableTextField = AppLovinInternalSettings.Instance.OverrideDefaultUserTrackingUsageDescriptions; + + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + AppLovinInternalSettings.Instance.OverrideDefaultUserTrackingUsageDescriptions = GUILayout.Toggle(AppLovinInternalSettings.Instance.OverrideDefaultUserTrackingUsageDescriptions, " Override Default User Tracking Usage Description"); + GUILayout.EndHorizontal(); + GUILayout.Space(4); + + GUILayout.Space(4); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEn = DrawTextField("User Tracking Usage Description", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEn, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + AppLovinInternalSettings.Instance.UserTrackingUsageLocalizationEnabled = GUILayout.Toggle(AppLovinInternalSettings.Instance.UserTrackingUsageLocalizationEnabled, " Localize User Tracking Usage Description"); + GUILayout.EndHorizontal(); + GUILayout.Space(4); + + if (AppLovinInternalSettings.Instance.UserTrackingUsageLocalizationEnabled) + { + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHans = DrawTextField("Chinese, Simplified (zh-Hans)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHans, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHant = DrawTextField("Chinese, Traditional (zh-Hant)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHant, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionFr = DrawTextField("French (fr)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionFr, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionDe = DrawTextField("German (de)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionDe, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionJa = DrawTextField("Japanese (ja)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionJa, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionKo = DrawTextField("Korean (ko)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionKo, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEs = DrawTextField("Spanish (es)", AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEs, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, isEditableTextField); + + GUILayout.Space(4); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.HelpBox("If you have your own implementation of InfoPlist.strings localization implementation, please use that instead. Using both at the same time may cause conflicts.", MessageType.Info); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + } + + GUILayout.Space(4); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + GUILayout.Button("Click the link below for more information about User Tracking Usage Description: ", wrapTextLabelStyle); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + if (GUILayout.Button(new GUIContent(userTrackingUsageDescriptionDocsLink), linkLabelStyle)) + { + Application.OpenURL(userTrackingUsageDescriptionDocsLink); + } + + GUILayout.Space(4); + GUILayout.EndHorizontal(); + GUILayout.Space(8); + + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.LabelField("Testing:", headerLabelStyle); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + GUILayout.Space(4); + EditorGUILayout.LabelField("Debug User Geography"); + AppLovinInternalSettings.Instance.DebugUserGeography = (MaxSdkBase.ConsentFlowUserGeography) EditorGUILayout.Popup((int) AppLovinInternalSettings.Instance.DebugUserGeography, debugUserGeographies, privacySettingFieldWidthOption); + GUILayout.Space(4); + GUILayout.EndHorizontal(); + + EditorGUILayout.HelpBox("Debug User Geography is only enabled in debug mode", MessageType.Info); + } + + private void DrawOtherSettings() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + GUILayout.Space(5); + AppLovinSettings.Instance.SetAttributionReportEndpoint = DrawOtherSettingsToggle(AppLovinSettings.Instance.SetAttributionReportEndpoint, " Set Advertising Attribution Report Endpoint in Info.plist (iOS only)"); + GUILayout.Space(5); + AppLovinSettings.Instance.AddApsSkAdNetworkIds = DrawOtherSettingsToggle(AppLovinSettings.Instance.AddApsSkAdNetworkIds, " Add Amazon Publisher Services SKAdNetworkID's"); + GUILayout.Space(5); + var autoUpdateEnabled = DrawOtherSettingsToggle(EditorPrefs.GetBool(AppLovinAutoUpdater.KeyAutoUpdateEnabled, true), " Enable Auto Update", "Checks for AppLovin MAX plugin updates and notifies you when an update is available."); + EditorPrefs.SetBool(AppLovinAutoUpdater.KeyAutoUpdateEnabled, autoUpdateEnabled); + GUILayout.Space(5); + var verboseLoggingEnabled = DrawOtherSettingsToggle(EditorPrefs.GetBool(MaxSdkLogger.KeyVerboseLoggingEnabled, false), " Enable Verbose Logging"); + EditorPrefs.SetBool(MaxSdkLogger.KeyVerboseLoggingEnabled, verboseLoggingEnabled); + GUILayout.Space(5); + AppLovinSettings.Instance.CustomGradleVersionUrl = DrawTextField("Custom Gradle Version URL", AppLovinSettings.Instance.CustomGradleVersionUrl, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, tooltip: customGradleVersionTooltip); + AppLovinSettings.Instance.CustomGradleToolsVersion = DrawTextField("Custom Gradle Tools Version", AppLovinSettings.Instance.CustomGradleToolsVersion, GUILayout.Width(privacySettingLabelWidth), privacySettingFieldWidthOption, tooltip: customGradleToolsVersionTooltip); + EditorGUILayout.HelpBox("This will overwrite the gradle build tools version in your base gradle template.", MessageType.Info); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + private bool DrawOtherSettingsToggle(bool value, string text, string tooltip = "") + { + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Space(4); + var content = MaxSdkUtils.IsValidString(tooltip) ? new GUIContent(text, tooltip) : new GUIContent(text); + var toggleValue = GUILayout.Toggle(value, content); + GUILayout.Space(4); + + return toggleValue; + } + } + + private void DrawUnityEnvironmentDetails() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(10); + using (new EditorGUILayout.VerticalScope("box")) + { + DrawUnityEnvironmentDetailRow("Unity Version", Application.unityVersion); + GUILayout.Space(5); + DrawUnityEnvironmentDetailRow("Platform", Application.platform.ToString()); + GUILayout.Space(5); + DrawUnityEnvironmentDetailRow("External Dependency Manager Version", AppLovinIntegrationManager.ExternalDependencyManagerVersion); + GUILayout.Space(5); + DrawUnityEnvironmentDetailRow("Gradle Template Enabled", AppLovinIntegrationManager.GradleTemplateEnabled.ToString()); + } + + GUILayout.Space(5); + GUILayout.EndHorizontal(); + } + + private void DrawUnityEnvironmentDetailRow(string key, string value) + { + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Space(5); + EditorGUILayout.LabelField(key, GUILayout.Width(250)); + GUILayout.FlexibleSpace(); + EditorGUILayout.LabelField(value, environmentValueStyle); + GUILayout.Space(5); + } + } + + private void DrawCollapsableSection(string keyShowDetails, string label, Action drawContent) + { + EditorGUILayout.BeginHorizontal(); + var showDetails = DrawExpandCollapseButton(keyShowDetails); + + EditorGUILayout.LabelField(label, titleLabelStyle); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + if (showDetails) + { + drawContent(); + } + } + + private bool DrawExpandCollapseButton(string keyShowDetails) + { + var showDetails = EditorPrefs.GetBool(keyShowDetails, true); + var buttonText = showDetails ? collapseButtonText : expandButtonText; + if (GUILayout.Button(buttonText, collapseButtonWidthOption)) + { + EditorPrefs.SetBool(keyShowDetails, !showDetails); + } + + return showDetails; + } + + /// + /// Calculates the fields width based on the width of the window. + /// + private void CalculateFieldWidth() + { + var currentWidth = position.width; + var availableWidth = currentWidth - actionFieldWidth - 80; // NOTE: Magic number alert. This is the sum of all the spacing the fields and other UI elements. + var networkLabelWidth = Math.Max(networkFieldMinWidth, availableWidth * networkFieldWidthPercentage); + networkWidthOption = GUILayout.Width(networkLabelWidth); + + var versionLabelWidth = Math.Max(versionFieldMinWidth, availableWidth * versionFieldWidthPercentage); + versionWidthOption = GUILayout.Width(versionLabelWidth); + + const int textFieldOtherUiElementsWidth = 55; // NOTE: Magic number alert. This is the sum of all the spacing the fields and other UI elements. + var availableUserDescriptionTextFieldWidth = currentWidth - privacySettingLabelWidth - textFieldOtherUiElementsWidth; + privacySettingFieldWidthOption = GUILayout.Width(availableUserDescriptionTextFieldWidth); + } + + #endregion + + #region Utility Methods + + /// + /// Loads the plugin data to be displayed by this window. + /// + private void Load() + { + loadDataCoroutine = AppLovinEditorCoroutine.StartCoroutine(AppLovinIntegrationManager.Instance.LoadPluginData(data => + { + if (data == null) + { + pluginDataLoadFailed = true; + } + else + { + pluginData = data; + pluginDataLoadFailed = false; + + UpdateShouldShowGoogleWarningIfNeeded(); + } + + CalculateFieldWidth(); + Repaint(); + })); + } + + /// + /// Callback method that will be called with progress updates when the plugin is being downloaded. + /// + public static void OnDownloadPluginProgress(string pluginName, float progress, bool done) + { + // Download is complete. Clear progress bar. + if (done) + { + EditorUtility.ClearProgressBar(); + } + // Download is in progress, update progress bar. + else + { + if (EditorUtility.DisplayCancelableProgressBar(windowTitle, string.Format("Downloading {0} plugin...", pluginName), progress)) + { + AppLovinIntegrationManager.Instance.CancelDownload(); + EditorUtility.ClearProgressBar(); + } + } + } + + private void OnImportPackageCompleted(Network network) + { + AppLovinPackageManager.UpdateCurrentVersions(network); + + UpdateShouldShowGoogleWarningIfNeeded(); + } + + private void UpdateShouldShowGoogleWarningIfNeeded() + { + if (pluginData == null) + { + shouldShowGoogleWarning = false; + return; + } + + var networks = pluginData.MediatedNetworks; + var googleNetwork = networks.FirstOrDefault(foundNetwork => foundNetwork.Name.Equals("ADMOB_NETWORK")); + var googleAdManagerNetwork = networks.FirstOrDefault(foundNetwork => foundNetwork.Name.Equals("GOOGLE_AD_MANAGER_NETWORK")); + + if (googleNetwork != null && googleAdManagerNetwork != null && + !string.IsNullOrEmpty(googleNetwork.CurrentVersions.Unity) && !string.IsNullOrEmpty(googleAdManagerNetwork.CurrentVersions.Unity) && + !googleNetwork.CurrentVersions.HasEqualSdkVersions(googleAdManagerNetwork.CurrentVersions)) + { + shouldShowGoogleWarning = true; + } + else + { + shouldShowGoogleWarning = false; + } + } + + /// + /// Upgrades all outdated networks + /// + private IEnumerator UpgradeAllNetworks() + { + networkButtonsEnabled = false; + EditorApplication.LockReloadAssemblies(); + var networks = pluginData.MediatedNetworks; + foreach (var network in networks) + { + var comparison = network.CurrentToLatestVersionComparisonResult; + // A newer version is available + if (!string.IsNullOrEmpty(network.CurrentVersions.Unity) && comparison == MaxSdkUtils.VersionComparisonResult.Lesser) + { + yield return AppLovinPackageManager.AddNetwork(network, false); + } + } + + EditorApplication.UnlockReloadAssemblies(); + networkButtonsEnabled = true; + + // The pluginData becomes stale after the networks have been updated, and we should re-load it. + Load(); + } + + /// + /// Returns whether any network adapter needs to be upgraded + /// + private bool NetworksRequireUpgrade() + { + if (pluginData == null || pluginData.AppLovinMax.CurrentVersions == null) return false; + + var networks = pluginData.MediatedNetworks; + return networks.Any(network => !string.IsNullOrEmpty(network.CurrentVersions.Unity) && network.CurrentToLatestVersionComparisonResult == MaxSdkUtils.VersionComparisonResult.Lesser); + } + + #endregion + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs.meta new file mode 100644 index 0000000..d7996fd --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 84c61b4c05e114cec91df447d1b585f8 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinIntegrationManagerWindow.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs new file mode 100644 index 0000000..41552d9 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs @@ -0,0 +1,297 @@ +// +// AppLovinInternalSettigns.cs +// AppLovin User Engagement Unity Plugin +// +// Created by Santosh Bagadi on 9/15/22. +// Copyright © 2022 AppLovin. All rights reserved. +// + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// A representing the AppLovin internal settings that can be set in the Integration Manager Window. + /// + /// The scriptable object asset is saved under ProjectSettings as AppLovinInternalSettings.json. + /// + public class AppLovinInternalSettings : ScriptableObject + { + private static AppLovinInternalSettings instance; + + public const string DefaultUserTrackingDescriptionEn = "This uses device info for more personalized ads and content"; + public const string DefaultUserTrackingDescriptionDe = "Dies benutzt Gerätinformationen für relevantere Werbeinhalte"; + public const string DefaultUserTrackingDescriptionEs = "Esto utiliza la información del dispositivo para anuncios y contenido más personalizados"; + public const string DefaultUserTrackingDescriptionFr = "Cela permet d'utiliser les informations du téléphone pour afficher des contenus publicitaires plus pertinents."; + public const string DefaultUserTrackingDescriptionJa = "これはユーザーデータをもとに、より関連性の高い広告コンテンツをお客様に提供します"; + public const string DefaultUserTrackingDescriptionKo = "보다 개인화된 광고 및 콘텐츠를 위해 기기 정보를 사용합니다."; + public const string DefaultUserTrackingDescriptionZhHans = "我们使用设备信息来提供个性化的广告和内容。"; + public const string DefaultUserTrackingDescriptionZhHant = "我們使用設備信息來提供個性化的廣告和內容。"; + + [SerializeField] private bool consentFlowEnabled; + [SerializeField] private string consentFlowPrivacyPolicyUrl = string.Empty; + [SerializeField] private string consentFlowTermsOfServiceUrl = string.Empty; + [SerializeField] private bool overrideDefaultUserTrackingUsageDescriptions; + [SerializeField] private MaxSdkBase.ConsentFlowUserGeography debugUserGeography; + [SerializeField] private string userTrackingUsageDescriptionEn = string.Empty; + [SerializeField] private bool userTrackingUsageLocalizationEnabled; + [SerializeField] private string userTrackingUsageDescriptionDe = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionEs = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionFr = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionJa = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionKo = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionZhHans = string.Empty; + [SerializeField] private string userTrackingUsageDescriptionZhHant = string.Empty; + + private const string SettingsFilePath = "ProjectSettings/AppLovinInternalSettings.json"; + + public static AppLovinInternalSettings Instance + { + get + { + if (instance != null) return instance; + + instance = CreateInstance(); + + var projectRootPath = Path.GetDirectoryName(Application.dataPath); + var settingsFilePath = Path.Combine(projectRootPath, SettingsFilePath); + if (!File.Exists(settingsFilePath)) + { + instance.Save(); + return instance; + } + + var settingsJson = File.ReadAllText(settingsFilePath); + if (string.IsNullOrEmpty(settingsJson)) + { + instance.Save(); + return instance; + } + + JsonUtility.FromJsonOverwrite(settingsJson, instance); + return instance; + } + } + + public void Save() + { + var settingsJson = JsonUtility.ToJson(instance); + try + { + var projectRootPath = Path.GetDirectoryName(Application.dataPath); + var settingsFilePath = Path.Combine(projectRootPath, SettingsFilePath); + File.WriteAllText(settingsFilePath, settingsJson); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to save internal settings."); + Console.WriteLine(exception); + } + } + + /// + /// Whether or not AppLovin Consent Flow is enabled. + /// + public bool ConsentFlowEnabled + { + get { return consentFlowEnabled; } + set + { + var previousValue = consentFlowEnabled; + consentFlowEnabled = value; + + if (value) + { + // If the value didn't change, we don't need to update anything. + if (previousValue) return; + + UserTrackingUsageDescriptionEn = DefaultUserTrackingDescriptionEn; + UserTrackingUsageLocalizationEnabled = true; + } + else + { + ConsentFlowPrivacyPolicyUrl = string.Empty; + ConsentFlowTermsOfServiceUrl = string.Empty; + UserTrackingUsageDescriptionEn = string.Empty; + UserTrackingUsageLocalizationEnabled = false; + OverrideDefaultUserTrackingUsageDescriptions = false; + } + } + } + + /// + /// A URL pointing to the Privacy Policy for the app to be shown when prompting the user for consent. + /// + public string ConsentFlowPrivacyPolicyUrl + { + get { return consentFlowPrivacyPolicyUrl; } + set { consentFlowPrivacyPolicyUrl = value; } + } + + /// + /// An optional URL pointing to the Terms of Service for the app to be shown when prompting the user for consent. + /// + public string ConsentFlowTermsOfServiceUrl + { + get { return consentFlowTermsOfServiceUrl; } + set { consentFlowTermsOfServiceUrl = value; } + } + + /// + /// A User Tracking Usage Description in English to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionEn + { + get { return userTrackingUsageDescriptionEn; } + set { userTrackingUsageDescriptionEn = value; } + } + + /// + /// An optional string to set debug user geography + /// + public MaxSdkBase.ConsentFlowUserGeography DebugUserGeography + { + get { return debugUserGeography; } + set { debugUserGeography = value; } + } + + public bool OverrideDefaultUserTrackingUsageDescriptions + { + get { return overrideDefaultUserTrackingUsageDescriptions; } + set + { + var previousValue = overrideDefaultUserTrackingUsageDescriptions; + overrideDefaultUserTrackingUsageDescriptions = value; + + if (!value) + { + if (!previousValue) return; + + UserTrackingUsageDescriptionEn = DefaultUserTrackingDescriptionEn; + UserTrackingUsageDescriptionDe = DefaultUserTrackingDescriptionDe; + UserTrackingUsageDescriptionEs = DefaultUserTrackingDescriptionEs; + UserTrackingUsageDescriptionFr = DefaultUserTrackingDescriptionFr; + UserTrackingUsageDescriptionJa = DefaultUserTrackingDescriptionJa; + UserTrackingUsageDescriptionKo = DefaultUserTrackingDescriptionKo; + UserTrackingUsageDescriptionZhHans = DefaultUserTrackingDescriptionZhHans; + UserTrackingUsageDescriptionZhHant = DefaultUserTrackingDescriptionZhHant; + } + } + } + + /// + /// Whether or not to localize User Tracking Usage Description. + /// For more information see Apple's documentation. + /// + public bool UserTrackingUsageLocalizationEnabled + { + get { return userTrackingUsageLocalizationEnabled; } + set + { + var previousValue = userTrackingUsageLocalizationEnabled; + userTrackingUsageLocalizationEnabled = value; + + if (value) + { + // If the value didn't change, don't do anything + if (previousValue) return; + + // Don't set the default values if they are being overriden. + if (OverrideDefaultUserTrackingUsageDescriptions) return; + + UserTrackingUsageDescriptionDe = DefaultUserTrackingDescriptionDe; + UserTrackingUsageDescriptionEs = DefaultUserTrackingDescriptionEs; + UserTrackingUsageDescriptionFr = DefaultUserTrackingDescriptionFr; + UserTrackingUsageDescriptionJa = DefaultUserTrackingDescriptionJa; + UserTrackingUsageDescriptionKo = DefaultUserTrackingDescriptionKo; + UserTrackingUsageDescriptionZhHans = DefaultUserTrackingDescriptionZhHans; + UserTrackingUsageDescriptionZhHant = DefaultUserTrackingDescriptionZhHant; + } + else + { + UserTrackingUsageDescriptionDe = string.Empty; + UserTrackingUsageDescriptionEs = string.Empty; + UserTrackingUsageDescriptionFr = string.Empty; + UserTrackingUsageDescriptionJa = string.Empty; + UserTrackingUsageDescriptionKo = string.Empty; + UserTrackingUsageDescriptionZhHans = string.Empty; + UserTrackingUsageDescriptionZhHant = string.Empty; + } + } + } + + /// + /// A User Tracking Usage Description in German to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionDe + { + get { return userTrackingUsageDescriptionDe; } + set { userTrackingUsageDescriptionDe = value; } + } + + /// + /// A User Tracking Usage Description in Spanish to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionEs + { + get { return userTrackingUsageDescriptionEs; } + set { userTrackingUsageDescriptionEs = value; } + } + + /// + /// A User Tracking Usage Description in French to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionFr + { + get { return userTrackingUsageDescriptionFr; } + set { userTrackingUsageDescriptionFr = value; } + } + + /// + /// A User Tracking Usage Description in Japanese to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionJa + { + get { return userTrackingUsageDescriptionJa; } + set { userTrackingUsageDescriptionJa = value; } + } + + /// + /// A User Tracking Usage Description in Korean to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionKo + { + get { return userTrackingUsageDescriptionKo; } + set { userTrackingUsageDescriptionKo = value; } + } + + /// + /// A User Tracking Usage Description in Chinese (Simplified) to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionZhHans + { + get { return userTrackingUsageDescriptionZhHans; } + set { userTrackingUsageDescriptionZhHans = value; } + } + + /// + /// A User Tracking Usage Description in Chinese (Traditional) to be shown to users when requesting permission to use data for tracking. + /// For more information see Apple's documentation. + /// + public string UserTrackingUsageDescriptionZhHant + { + get { return userTrackingUsageDescriptionZhHant; } + set { userTrackingUsageDescriptionZhHant = value; } + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs.meta new file mode 100644 index 0000000..a863905 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 65c51e21887ae42c2839962fb9585e9f +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinInternalSettings.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs new file mode 100644 index 0000000..130b383 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs @@ -0,0 +1,60 @@ +// +// MaxMenuItems.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 5/27/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using UnityEditor; +using UnityEngine; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public class AppLovinMenuItems + { + /** + * The special characters at the end represent a shortcut for this action. + * + * % - ctrl on Windows, cmd on macOS + * # - shift + * & - alt + * + * So, (shift + cmd/ctrl + i) will launch the integration manager + */ + [MenuItem("AppLovin/Integration Manager %#i")] + private static void IntegrationManager() + { + ShowIntegrationManager(); + } + + [MenuItem("AppLovin/Documentation")] + private static void Documentation() + { + Application.OpenURL("https://developers.applovin.com/en/unity/overview/integration"); + } + + [MenuItem("AppLovin/Contact Us")] + private static void ContactUs() + { + Application.OpenURL("https://www.applovin.com/contact/"); + } + + [MenuItem("AppLovin/About")] + private static void About() + { + Application.OpenURL("https://www.applovin.com/about/"); + } + + [MenuItem("Assets/AppLovin Integration Manager")] + private static void AssetsIntegrationManager() + { + ShowIntegrationManager(); + } + + private static void ShowIntegrationManager() + { + AppLovinIntegrationManagerWindow.ShowManager(); + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs.meta new file mode 100644 index 0000000..30fb834 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 02c2d277874f649d18a59d382420bf65 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinMenuItems.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs new file mode 100644 index 0000000..fcbed1d --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#if !UNITY_2020_1_OR_NEWER +using System.Reflection; +#endif +using System.Xml.Linq; +using UnityEditor; +using UnityEditor.PackageManager; +using UnityEngine; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + [Serializable] + public class PackageInfo + { + // ReSharper disable InconsistentNaming - For JSON Deserialization + public string Name; + public string Version; + } + + public interface IPackageManagerClient + { + List GetInstalledMediationNetworks(); + IEnumerator AddNetwork(Network network, bool showImport); + void RemoveNetwork(Network network); + } + + public static class AppLovinPackageManager + { +#if UNITY_2019_2_OR_NEWER + private static readonly IPackageManagerClient _upmPackageManager = new AppLovinUpmPackageManager(); +#endif + private static readonly IPackageManagerClient _assetsPackageManager = new AppLovinAssetsPackageManager(); + + private static bool _migrationPromptShown; + + private static IPackageManagerClient PackageManagerClient + { + get + { +#if UNITY_2019_2_OR_NEWER + return AppLovinIntegrationManager.IsPluginInPackageManager ? _upmPackageManager : _assetsPackageManager; +#else + return _assetsPackageManager; +#endif + } + } + + internal static PluginData PluginData { get; set; } + + /// + /// Checks whether or not an adapter with the given version or newer exists. + /// + /// The name of the network (the root adapter folder name in "MaxSdk/Mediation/" folder. + /// The min iOS adapter version to check for. Can be null if we want to check for any version. + /// The min android adapter version to check for. Can be null if we want to check for any version. + /// true if an adapter with the min version is installed. + internal static bool IsAdapterInstalled(string adapterName, string iosVersion = null, string androidVersion = null) + { + var dependencyFilePathList = GetAssetPathListForExportPath("MaxSdk/Mediation/" + adapterName + "/Editor/Dependencies.xml"); + if (dependencyFilePathList.Count <= 0) return false; + + var currentVersion = GetCurrentVersions(dependencyFilePathList); + if (iosVersion != null) + { + var iosVersionComparison = MaxSdkUtils.CompareVersions(currentVersion.Ios, iosVersion); + if (iosVersionComparison == MaxSdkUtils.VersionComparisonResult.Lesser) + { + return false; + } + } + + if (androidVersion != null) + { + var androidVersionComparison = MaxSdkUtils.CompareVersions(currentVersion.Android, androidVersion); + if (androidVersionComparison == MaxSdkUtils.VersionComparisonResult.Lesser) + { + return false; + } + } + + return true; + } + + /// + /// Checks whether an adapter is installed using the plugin data. + /// + /// The plugin data to check for the adapter + /// The name of the network. + /// Whether an adapter is installed in the plugin data + internal static bool IsAdapterInstalled(PluginData pluginData, string adapterName) + { + var network = pluginData.MediatedNetworks.Where(mediatedNetwork => mediatedNetwork.Name.Equals(adapterName)).ToList().FirstOrDefault(); + var networkVersion = network != null ? network.CurrentVersions : null; + var currentVersion = networkVersion != null ? networkVersion.Unity : ""; + + return MaxSdkUtils.IsValidString(currentVersion); + } + + /// + /// Gets the mediation networks that are currently installed in the project. If using UPM, checks + /// for networks in Packages folder and Mediation folder in case a custom adapter was added to the project. + /// + /// A list of the installed mediation network names. + internal static List GetInstalledMediationNetworks() + { + var installedNetworks = PackageManagerClient.GetInstalledMediationNetworks(); + if (AppLovinSettings.Instance.AddApsSkAdNetworkIds) + { + installedNetworks.Add("AmazonAdMarketplace"); + } + + return installedNetworks; + } + + /// + /// Adds a network to the project. + /// + /// The network to add. + /// Whether to show the import window (only for non UPM) + internal static IEnumerator AddNetwork(Network network, bool showImport) + { + yield return PackageManagerClient.AddNetwork(network, showImport); + + AppLovinEditorCoroutine.StartCoroutine(RefreshAssetsAtEndOfFrame(network)); + } + + /// + /// Removes a network from the project. + /// + /// The network to remove. + internal static void RemoveNetwork(Network network) + { + PackageManagerClient.RemoveNetwork(network); + + AppLovinEditorCoroutine.StartCoroutine(RefreshAssetsAtEndOfFrame(network)); + } + + #region Utility + + /// + /// Gets the list of all asset paths for a given MAX plugin export path. + /// + /// The actual exported path of the asset. + /// The exported path of the MAX plugin asset or an empty list if the asset is not found. + private static List GetAssetPathListForExportPath(string exportPath) + { + var assetLabelToFind = "l:al_max_export_path-" + exportPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + var assetGuids = AssetDatabase.FindAssets(assetLabelToFind); + + var assetPaths = new List(); + foreach (var assetGuid in assetGuids) + { + assetPaths.Add(AssetDatabase.GUIDToAssetPath(assetGuid)); + } + + return assetPaths.Count <= 0 ? new List() : assetPaths; + } + + /// + /// Updates the CurrentVersion fields for a given network data object. + /// + /// Network for which to update the current versions. + internal static void UpdateCurrentVersions(Network network) + { + var assetPaths = GetAssetPathListForExportPath(network.DependenciesFilePath); + var currentVersions = GetCurrentVersions(assetPaths); + network.CurrentVersions = currentVersions; + + // If AppLovin mediation plugin, get the version from MaxSdk and the latest and current version comparison. + if (network.Name.Equals("APPLOVIN_NETWORK")) + { + network.CurrentVersions.Unity = MaxSdk.Version; + + var unityVersionComparison = MaxSdkUtils.CompareVersions(network.CurrentVersions.Unity, network.LatestVersions.Unity); + var androidVersionComparison = MaxSdkUtils.CompareVersions(network.CurrentVersions.Android, network.LatestVersions.Android); + var iosVersionComparison = MaxSdkUtils.CompareVersions(network.CurrentVersions.Ios, network.LatestVersions.Ios); + + // Overall version is same if all the current and latest (from db) versions are same. + if (unityVersionComparison == MaxSdkUtils.VersionComparisonResult.Equal && + androidVersionComparison == MaxSdkUtils.VersionComparisonResult.Equal && + iosVersionComparison == MaxSdkUtils.VersionComparisonResult.Equal) + { + network.CurrentToLatestVersionComparisonResult = MaxSdkUtils.VersionComparisonResult.Equal; + } + // One of the installed versions is newer than the latest versions which means that the publisher is on a beta version. + else if (unityVersionComparison == MaxSdkUtils.VersionComparisonResult.Greater || + androidVersionComparison == MaxSdkUtils.VersionComparisonResult.Greater || + iosVersionComparison == MaxSdkUtils.VersionComparisonResult.Greater) + { + network.CurrentToLatestVersionComparisonResult = MaxSdkUtils.VersionComparisonResult.Greater; + } + // We have a new version available if all Android, iOS and Unity has a newer version available in db. + else + { + network.CurrentToLatestVersionComparisonResult = MaxSdkUtils.VersionComparisonResult.Lesser; + } + } + // For all other mediation adapters, get the version comparison using their Unity versions. + else + { + // If adapter is indeed installed, compare the current (installed) and the latest (from db) versions, so that we can determine if the publisher is on an older, current or a newer version of the adapter. + // If the publisher is on a newer version of the adapter than the db version, that means they are on a beta version. + if (!string.IsNullOrEmpty(currentVersions.Unity)) + { + network.CurrentToLatestVersionComparisonResult = AppLovinIntegrationManagerUtils.CompareUnityMediationVersions(currentVersions.Unity, network.LatestVersions.Unity); + } + + if (!string.IsNullOrEmpty(network.CurrentVersions.Unity) && AppLovinAutoUpdater.MinAdapterVersions.ContainsKey(network.Name)) + { + var comparisonResult = AppLovinIntegrationManagerUtils.CompareUnityMediationVersions(network.CurrentVersions.Unity, AppLovinAutoUpdater.MinAdapterVersions[network.Name]); + // Requires update if current version is lower than the min required version. + network.RequiresUpdate = comparisonResult < 0; + } + else + { + // Reset value so that the Integration manager can hide the alert icon once adapter is updated. + network.RequiresUpdate = false; + } + } + } + + /// + /// Gets the current versions for a given network's dependency file paths. UPM will have multiple paths + /// for each network - one each for iOS and Android. + /// + /// A list of dependency file paths to extract current versions from. + /// Current versions of a given network's dependency files. + private static Versions GetCurrentVersions(List dependencyPaths) + { + var currentVersions = new Versions(); + foreach (var dependencyPath in dependencyPaths) + { + GetCurrentVersion(currentVersions, dependencyPath); + } + + if (currentVersions.Android != null && currentVersions.Ios != null) + { + currentVersions.Unity = "android_" + currentVersions.Android + "_ios_" + currentVersions.Ios; + } + else if (currentVersions.Android != null) + { + currentVersions.Unity = "android_" + currentVersions.Android; + } + else if (currentVersions.Ios != null) + { + currentVersions.Unity = "ios_" + currentVersions.Ios; + } + + return currentVersions; + } + + /// + /// Extracts the current version of a network from its dependency.xml file. + /// + /// The Versions object we are using. + /// The path to the dependency.xml file. + private static void GetCurrentVersion(Versions currentVersions, string dependencyPath) + { + XDocument dependency; + try + { + dependency = XDocument.Load(dependencyPath); + } +#pragma warning disable 0168 + catch (IOException exception) +#pragma warning restore 0168 + { + // Couldn't find the dependencies file. The plugin is not installed. + return; + } + + // + // + // + // + // + // + // + // + string androidVersion = null; + string iosVersion = null; + var dependenciesElement = dependency.Element("dependencies"); + if (dependenciesElement != null) + { + var androidPackages = dependenciesElement.Element("androidPackages"); + if (androidPackages != null) + { + var adapterPackage = androidPackages.Descendants().FirstOrDefault(element => element.Name.LocalName.Equals("androidPackage") + && element.FirstAttribute.Name.LocalName.Equals("spec") + && element.FirstAttribute.Value.StartsWith("com.applovin")); + if (adapterPackage != null) + { + androidVersion = adapterPackage.FirstAttribute.Value.Split(':').Last(); + // Hack alert: Some Android versions might have square brackets to force a specific version. Remove them if they are detected. + if (androidVersion.StartsWith("[")) + { + androidVersion = androidVersion.Trim('[', ']'); + } + } + } + + var iosPods = dependenciesElement.Element("iosPods"); + if (iosPods != null) + { + var adapterPod = iosPods.Descendants().FirstOrDefault(element => element.Name.LocalName.Equals("iosPod") + && element.FirstAttribute.Name.LocalName.Equals("name") + && element.FirstAttribute.Value.StartsWith("AppLovin")); + if (adapterPod != null) + { + iosVersion = adapterPod.Attributes().First(attribute => attribute.Name.LocalName.Equals("version")).Value; + } + } + } + + if (androidVersion != null) + { + currentVersions.Android = androidVersion; + } + + if (iosVersion != null) + { + currentVersions.Ios = iosVersion; + } + } + +#if UNITY_2019_2_OR_NEWER + /// + /// Show the adapter migration prompt if it hasn't been shown yet. + /// + private static void ShowAdapterMigrationPrompt() + { + if (_migrationPromptShown) return; + + _migrationPromptShown = true; + var migrateAdapters = EditorUtility.DisplayDialog("Adapter Detected in Mediation Folder", + "It appears that you have an adapter in the Mediation folder while AppLovin's plugin is installed via UPM. This could potentially break the integration or cause unexpected errors. Would you like to automatically migrate all your adapters to UPM?", "Yes", "No"); + + if (migrateAdapters) + { + AppLovinPluginMigrationHelper.MigrateAdapters(PluginData, AppLovinUpmManifest.Load()); + } + } +#endif + + /// + /// Refresh assets and update current versions after a slight delay to allow for Client.Resolve to finish. + /// + /// The network that was just installed/removed. + private static IEnumerator RefreshAssetsAtEndOfFrame(Network network) + { + yield return new WaitForEndOfFrame(); + UpdateCurrentVersions(network); + AssetDatabase.Refresh(); + } + + #endregion + } + +#if UNITY_2019_2_OR_NEWER + public class AppLovinUpmPackageManager : IPackageManagerClient + { + public const string PackageNamePrefixAppLovin = "com.applovin.mediation.ads"; + private const string PackageNamePrefixNetwork = "com.applovin.mediation.adapters"; + private const string PackageNamePrefixDsp = "com.applovin.mediation.dsp"; + + private const float TimeoutFetchPackageCollectionSeconds = 10f; + +#if !UNITY_2020_1_OR_NEWER + private static Type packageManagerClientType; + private static MethodInfo packageManagerResolveMethod; +#endif + + public List GetInstalledMediationNetworks() + { + // Return empty list if we failed to get the package list + var packageCollection = GetPackageCollectionSync(TimeoutFetchPackageCollectionSeconds); + if (packageCollection == null) + { + return new List(); + } + + return packageCollection.Where(package => package.name.StartsWith(PackageNamePrefixNetwork) || package.name.StartsWith(PackageNamePrefixDsp)) + .SelectMany(package => package.keywords) + .Where(keyword => keyword.StartsWith("dir:")) + .Select(keyword => keyword.Replace("dir:", "")) + .Distinct() + .ToList(); + } + + public IEnumerator AddNetwork(Network network, bool showImport) + { + var appLovinManifest = AppLovinUpmManifest.Load(); + AddPackages(network, appLovinManifest); + appLovinManifest.Save(); + ResolvePackageManager(); + + yield break; + } + + public void RemoveNetwork(Network network) + { + var appLovinManifest = AppLovinUpmManifest.Load(); + RemovePackages(network, appLovinManifest); + appLovinManifest.Save(); + ResolvePackageManager(); + } + + /// + /// Adds a network's packages to the package manager removes any beta version that exists + /// + /// The network to add. + /// The AppLovinUpmManifest instance to edit + internal static void AddPackages(Network network, AppLovinUpmManifest appLovinManifest) + { + foreach (var packageInfo in network.Packages) + { + appLovinManifest.AddPackageDependency(packageInfo.Name, packageInfo.Version); + RemoveBetaPackage(packageInfo.Name, appLovinManifest); + } + } + + /// + /// Removes a network's packages from the package manager + /// + /// The network to add. + /// The AppLovinUpmManifest instance to edit + private static void RemovePackages(Network network, AppLovinUpmManifest appLovinManifest) + { + foreach (var packageInfo in network.Packages) + { + appLovinManifest.RemovePackageDependency(packageInfo.Name); + RemoveBetaPackage(packageInfo.Name, appLovinManifest); + } + } + + /// + /// Removes the beta version of a package name + /// + /// The name of the package to remove a beta for + /// The AppLovinUpmManifest instance to edit + private static void RemoveBetaPackage(string packageName, AppLovinUpmManifest appLovinManifest) + { + var prefix = ""; + if (packageName.Contains(PackageNamePrefixNetwork)) + { + prefix = PackageNamePrefixNetwork; + } + else if (packageName.Contains(PackageNamePrefixDsp)) + { + prefix = PackageNamePrefixDsp; + } + else if (packageName.Contains(PackageNamePrefixAppLovin)) + { + prefix = PackageNamePrefixAppLovin; + } + else + { + return; + } + + var betaPackageName = packageName.Replace(prefix, prefix + ".beta"); + appLovinManifest.RemovePackageDependency(betaPackageName); + } + + /// + /// Resolves the Unity Package Manager so any changes made to the manifest.json file are reflected in the Unity Editor. + /// + internal static void ResolvePackageManager() + { +#if UNITY_2020_1_OR_NEWER + Client.Resolve(); +#else + packageManagerClientType = packageManagerClientType ?? typeof(Client); + if (packageManagerClientType != null) + { + packageManagerResolveMethod = packageManagerResolveMethod ?? packageManagerClientType.GetMethod("Resolve", BindingFlags.NonPublic | BindingFlags.Static); + } + + if (packageManagerResolveMethod != null) + { + packageManagerResolveMethod.Invoke(null, null); + } +#endif + } + + /// + /// Gets the PackageCollection from the Unity Package Manager synchronously. + /// + /// How long to wait before exiting with a timeout error + /// + private static PackageCollection GetPackageCollectionSync(float timeoutSeconds = -1) + { + var request = Client.List(); + + // Just wait till the request is complete + var now = DateTime.Now; + while (!request.IsCompleted) + { + // Wait indefinitely if there is no timeout set. + if (timeoutSeconds < 0) continue; + + var delta = DateTime.Now - now; + if (delta.TotalSeconds > timeoutSeconds) + { + MaxSdkLogger.UserError("Failed to list UPM packages: Timeout"); + break; + } + } + + if (!request.IsCompleted) + { + return null; + } + + if (request.Status >= StatusCode.Failure) + { + MaxSdkLogger.UserError("Failed to list packages: " + request.Error.message); + return null; + } + + return (request.Status == StatusCode.Success) ? request.Result : null; + } + } + +#endif + + public class AppLovinAssetsPackageManager : IPackageManagerClient + { + public List GetInstalledMediationNetworks() + { + var maxMediationDirectory = Path.Combine(AppLovinIntegrationManager.PluginParentDirectory, "MaxSdk/Mediation/"); + if (!Directory.Exists(maxMediationDirectory)) return new List(); + + var mediationNetworkDirectories = Directory.GetDirectories(maxMediationDirectory); + return mediationNetworkDirectories.Select(Path.GetFileName).ToList(); + } + + public IEnumerator AddNetwork(Network network, bool showImport) + { + yield return AppLovinIntegrationManager.Instance.DownloadPlugin(network, showImport); + } + + public void RemoveNetwork(Network network) + { + foreach (var pluginFilePath in network.PluginFilePaths) + { + var filePath = Path.Combine(AppLovinIntegrationManager.PluginParentDirectory, pluginFilePath); + FileUtil.DeleteFileOrDirectory(filePath); + FileUtil.DeleteFileOrDirectory(filePath + ".meta"); + } + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs.meta new file mode 100644 index 0000000..5a508fa --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 69faa9dfd9aac483daa24261a3e11206 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPackageManager.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs new file mode 100644 index 0000000..9aa6d23 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs @@ -0,0 +1,111 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +#if UNITY_2019_2_OR_NEWER +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// Moves our SDK Unity Plugin from under the Assets folder to the Unity Package Manager. + /// + public static class AppLovinPluginMigrationHelper + { + private const string ApplovinRegistryName = "AppLovin MAX Unity"; + private const string ApplovinRegistryUrl = "https://unity.packages.applovin.com/"; + private static readonly List AppLovinRegistryScopes = new List() {"com.applovin.mediation.ads", "com.applovin.mediation.adapters", "com.applovin.mediation.dsp"}; + + private const string OpenUpmRegistryName = "package.openupm.com"; + private const string OpenUpmRegistryUrl = "https://package.openupm.com"; + private static readonly List OpenUpmRegistryScopes = new List() {"com.google.external-dependency-manager"}; + + /// + /// Attempts to move the Unity plugin to UPM by adding the AppLovin scoped registry and dependencies to the manifest. + /// + /// The Unity Plugin data for our sdk and mediation adapters. + /// Whether to delete the EDM folder under "Assets" + internal static void MigrateToUnityPackageManager(PluginData pluginData, bool deleteExternalDependencyManager) + { + MaxSdkLogger.UserDebug("Moving AppLovin Unity Plugin to package manager"); + + if (deleteExternalDependencyManager) + { + DeleteExternalDependencyManager(); + } + + var appLovinManifest = AppLovinUpmManifest.Load(); + + MigrateAdapters(pluginData, appLovinManifest); + MigratePlugin(pluginData, appLovinManifest); + + appLovinManifest.Save(); + AppLovinUpmPackageManager.ResolvePackageManager(); + DeletePluginFiles(); + } + + /// + /// Add all currently installed networks to the manifest. + /// + internal static void MigrateAdapters(PluginData pluginData, AppLovinUpmManifest appLovinManifest) + { + var allNetworks = pluginData.MediatedNetworks.Concat(pluginData.PartnerMicroSdks).ToArray(); + + // Add every currently installed network and separate it by android and iOS. + foreach (var network in allNetworks) + { + var currentVersion = network.CurrentVersions != null ? network.CurrentVersions.Unity : ""; + if (string.IsNullOrEmpty(currentVersion)) continue; + + AppLovinUpmPackageManager.AddPackages(network, appLovinManifest); + } + } + + /// + /// Add the AppLovin scoped registry to the manifest if it doesn't exist. Otherwise update it. + /// + private static void MigratePlugin(PluginData pluginData, AppLovinUpmManifest appLovinManifest) + { + appLovinManifest.AddOrUpdateRegistry(ApplovinRegistryName, ApplovinRegistryUrl, AppLovinRegistryScopes); + appLovinManifest.AddOrUpdateRegistry(OpenUpmRegistryName, OpenUpmRegistryUrl, OpenUpmRegistryScopes); + + var appLovinVersion = pluginData.AppLovinMax.LatestVersions.Unity; + appLovinManifest.AddPackageDependency(AppLovinUpmPackageManager.PackageNamePrefixAppLovin, appLovinVersion); + } + + #region Utility + + /// + /// Delete the external dependency manager folder from the project. + /// + private static void DeleteExternalDependencyManager() + { + var externalDependencyManagerPath = Path.Combine(Application.dataPath, "ExternalDependencyManager"); + FileUtil.DeleteFileOrDirectory(externalDependencyManagerPath); + FileUtil.DeleteFileOrDirectory(externalDependencyManagerPath + ".meta"); + } + + /// + /// Deletes all the files in the plugin directory except the AppLovinSettings.asset file. + /// + private static void DeletePluginFiles() + { + if (AppLovinIntegrationManager.IsPluginInPackageManager) return; + + var pluginPath = Path.Combine(AppLovinIntegrationManager.PluginParentDirectory, "MaxSdk"); + var appLovinSettingsPath = Path.Combine(pluginPath, "Resources/AppLovinSettings.asset"); + + var appLovinResourcesDirectory = Path.Combine(pluginPath, "Resources"); + var appLovinSettingsTempPath = Path.Combine(Path.GetTempPath(), "AppLovinSettings.asset"); + + // Move the AppLovinSettings.asset file to a temp directory, delete the plugin directory, then move the settings file back. + File.Copy(appLovinSettingsPath, appLovinSettingsTempPath, true); + FileUtil.DeleteFileOrDirectory(pluginPath); + Directory.CreateDirectory(appLovinResourcesDirectory); + File.Move(appLovinSettingsTempPath, appLovinSettingsPath); + } + + #endregion + } +} +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs.meta new file mode 100644 index 0000000..dc78f48 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 11288612632de49b99708cdee436692c +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPluginMigrationHelper.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs new file mode 100644 index 0000000..e0f8566 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs @@ -0,0 +1,499 @@ +// +// MaxPostProcessBuildAndroid.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 4/10/20. +// Copyright © 2020 AppLovin. All rights reserved. +// + +#if UNITY_ANDROID +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using AppLovinMax.ThirdParty.MiniJson; +using UnityEditor; +using UnityEditor.Android; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// A post processor used to update the Android project once it is generated. + /// + public class AppLovinPostProcessAndroid : IPostGenerateGradleAndroidProject + { +#if UNITY_2019_3_OR_NEWER + private const string PropertyAndroidX = "android.useAndroidX"; + private const string PropertyJetifier = "android.enableJetifier"; + private const string EnableProperty = "=true"; +#endif + private const string PropertyDexingArtifactTransform = "android.enableDexingArtifactTransform"; + private const string DisableProperty = "=false"; + + private const string KeyMetaDataAppLovinVerboseLoggingOn = "applovin.sdk.verbose_logging"; + private const string KeyMetaDataGoogleApplicationId = "com.google.android.gms.ads.APPLICATION_ID"; + private const string KeyMetaDataGoogleOptimizeInitialization = "com.google.android.gms.ads.flag.OPTIMIZE_INITIALIZATION"; + private const string KeyMetaDataGoogleOptimizeAdLoading = "com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING"; + + private const string KeyMetaDataMobileFuseAutoInit = "com.mobilefuse.sdk.disable_auto_init"; + private const string KeyMetaDataMyTargetAutoInit = "com.my.target.autoInitMode"; + + private const string KeyMetaDataAppLovinSdkKey = "applovin.sdk.key"; + + private const string AppLovinSettingsFileName = "applovin_settings.json"; + + private const string KeyTermsFlowSettings = "terms_flow_settings"; + private const string KeyTermsFlowEnabled = "terms_flow_enabled"; + private const string KeyTermsFlowTermsOfService = "terms_flow_terms_of_service"; + private const string KeyTermsFlowPrivacyPolicy = "terms_flow_privacy_policy"; + + private const string KeySdkKey = "sdk_key"; + private const string KeyConsentFlowSettings = "consent_flow_settings"; + private const string KeyConsentFlowEnabled = "consent_flow_enabled"; + private const string KeyConsentFlowTermsOfService = "consent_flow_terms_of_service"; + private const string KeyConsentFlowPrivacyPolicy = "consent_flow_privacy_policy"; + private const string KeyConsentFlowDebugUserGeography = "consent_flow_debug_user_geography"; + + private const string KeyRenderOutsideSafeArea = "render_outside_safe_area"; + +#if UNITY_2022_3_OR_NEWER + // To match "'com.android.library' version '7.3.1'" line in build.gradle + private static readonly Regex TokenGradleVersionLibrary = new Regex(".*id ['\"]com\\.android\\.library['\"] version"); + private static readonly Regex TokenGradleVersion = new Regex(".*id ['\"]com\\.android\\.application['\"] version"); +#else + // To match "classpath 'com.android.tools.build:gradle:4.0.1'" line in build.gradle + private static readonly Regex TokenGradleVersion = new Regex(".*classpath ['\"]com\\.android\\.tools\\.build:gradle:.*"); +#endif + + // To match "distributionUrl=..." in gradle-wrapper.properties file + private static readonly Regex TokenDistributionUrl = new Regex(".*distributionUrl.*"); + + private static readonly XNamespace AndroidNamespace = "http://schemas.android.com/apk/res/android"; + + public void OnPostGenerateGradleAndroidProject(string path) + { +#if UNITY_2019_3_OR_NEWER + var rootGradleBuildFilePath = Path.Combine(path, "../build.gradle"); + var gradlePropertiesPath = Path.Combine(path, "../gradle.properties"); + var gradleWrapperPropertiesPath = Path.Combine(path, "../gradle/wrapper/gradle-wrapper.properties"); +#else + var rootGradleBuildFilePath = Path.Combine(path, "build.gradle"); + var gradlePropertiesPath = Path.Combine(path, "gradle.properties"); + var gradleWrapperPropertiesPath = Path.Combine(path, "gradle/wrapper/gradle-wrapper.properties"); +#endif + + UpdateGradleVersionsIfNeeded(gradleWrapperPropertiesPath, rootGradleBuildFilePath); + + var gradlePropertiesUpdated = new List(); + + // If the gradle properties file already exists, make sure to add any previous properties. + if (File.Exists(gradlePropertiesPath)) + { + var lines = File.ReadAllLines(gradlePropertiesPath); + +#if UNITY_2019_3_OR_NEWER + // Add all properties except AndroidX, Jetifier, and DexingArtifactTransform since they may already exist. We will re-add them below. + gradlePropertiesUpdated.AddRange(lines.Where(line => !line.Contains(PropertyAndroidX) && !line.Contains(PropertyJetifier) && !line.Contains(PropertyDexingArtifactTransform))); +#else + // Add all properties except DexingArtifactTransform since it may already exist. We will re-add it below. + gradlePropertiesUpdated.AddRange(lines.Where(line => !line.Contains(PropertyDexingArtifactTransform))); +#endif + } + +#if UNITY_2019_3_OR_NEWER + // Enable AndroidX and Jetifier properties + gradlePropertiesUpdated.Add(PropertyAndroidX + EnableProperty); + gradlePropertiesUpdated.Add(PropertyJetifier + EnableProperty); +#endif + + // `DexingArtifactTransform` has been removed in Gradle 8+ which is the default Gradle version for Unity 6. +#if !UNITY_6000_0_OR_NEWER + // Disable dexing using artifact transform (it causes issues for ExoPlayer with Gradle plugin 3.5.0+) + gradlePropertiesUpdated.Add(PropertyDexingArtifactTransform + DisableProperty); +#endif + + try + { + File.WriteAllText(gradlePropertiesPath, string.Join("\n", gradlePropertiesUpdated.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to enable AndroidX and Jetifier. gradle.properties file write failed."); + Console.WriteLine(exception); + } + + ProcessAndroidManifest(path); + AddSdkSettings(path); + } + + public int callbackOrder + { + get { return int.MaxValue; } + } + + private static void ProcessAndroidManifest(string path) + { + var manifestPath = Path.Combine(path, "src/main/AndroidManifest.xml"); + XDocument manifest; + try + { + manifest = XDocument.Load(manifestPath); + } +#pragma warning disable 0168 + catch (IOException exception) +#pragma warning restore 0168 + { + MaxSdkLogger.UserWarning("[AppLovin MAX] AndroidManifest.xml is missing."); + return; + } + + // Get the `manifest` element. + var elementManifest = manifest.Element("manifest"); + if (elementManifest == null) + { + MaxSdkLogger.UserWarning("[AppLovin MAX] AndroidManifest.xml is invalid."); + return; + } + + var elementApplication = elementManifest.Element("application"); + if (elementApplication == null) + { + MaxSdkLogger.UserWarning("[AppLovin MAX] AndroidManifest.xml is invalid."); + return; + } + + var metaDataElements = elementApplication.Descendants().Where(element => element.Name.LocalName.Equals("meta-data")); + + EnableVerboseLoggingIfNeeded(elementApplication); + AddGoogleApplicationIdIfNeeded(elementApplication, metaDataElements); + AddGoogleOptimizationFlagsIfNeeded(elementApplication, metaDataElements); + DisableAutoInitIfNeeded(elementApplication, metaDataElements); + RemoveSdkKeyIfNeeded(metaDataElements); + + // Save the updated manifest file. + manifest.Save(manifestPath); + } + + private static void EnableVerboseLoggingIfNeeded(XElement elementApplication) + { + var enabled = EditorPrefs.GetBool(MaxSdkLogger.KeyVerboseLoggingEnabled, false); + + var descendants = elementApplication.Descendants(); + var verboseLoggingMetaData = descendants.FirstOrDefault(descendant => descendant.FirstAttribute != null && + descendant.FirstAttribute.Name.LocalName.Equals("name") && + descendant.FirstAttribute.Value.Equals(KeyMetaDataAppLovinVerboseLoggingOn) && + descendant.LastAttribute != null && + descendant.LastAttribute.Name.LocalName.Equals("value")); + + // check if applovin.sdk.verbose_logging meta data exists. + if (verboseLoggingMetaData != null) + { + if (enabled) + { + // update applovin.sdk.verbose_logging meta data value. + verboseLoggingMetaData.LastAttribute.Value = enabled.ToString(); + } + else + { + // remove applovin.sdk.verbose_logging meta data. + verboseLoggingMetaData.Remove(); + } + } + else + { + if (enabled) + { + // add applovin.sdk.verbose_logging meta data if it does not exist. + var metaData = CreateMetaDataElement(KeyMetaDataAppLovinVerboseLoggingOn, enabled.ToString()); + elementApplication.Add(metaData); + } + } + } + + private static void AddGoogleApplicationIdIfNeeded(XElement elementApplication, IEnumerable metaDataElements) + { + if (!AppLovinPackageManager.IsAdapterInstalled("Google") && !AppLovinPackageManager.IsAdapterInstalled("GoogleAdManager")) return; + + var googleApplicationIdMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataGoogleApplicationId); + var appId = AppLovinSettings.Instance.AdMobAndroidAppId; + // Log error if the App ID is not set. + if (string.IsNullOrEmpty(appId) || !appId.StartsWith("ca-app-pub-")) + { + MaxSdkLogger.UserError("Google App ID is not set. Please enter a valid app ID within the AppLovin Integration Manager window."); + return; + } + + // Check if the Google App ID meta data already exists. Update if it already exists. + if (googleApplicationIdMetaData != null) + { + googleApplicationIdMetaData.SetAttributeValue(AndroidNamespace + "value", appId); + } + // Meta data doesn't exist, add it. + else + { + elementApplication.Add(CreateMetaDataElement(KeyMetaDataGoogleApplicationId, appId)); + } + } + + private static void AddGoogleOptimizationFlagsIfNeeded(XElement elementApplication, IEnumerable metaDataElements) + { + if (!AppLovinPackageManager.IsAdapterInstalled("Google") && !AppLovinPackageManager.IsAdapterInstalled("GoogleAdManager")) return; + + var googleOptimizeInitializationMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataGoogleOptimizeInitialization); + // If meta data doesn't exist, add it + if (googleOptimizeInitializationMetaData == null) + { + elementApplication.Add(CreateMetaDataElement(KeyMetaDataGoogleOptimizeInitialization, true)); + } + + var googleOptimizeAdLoadingMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataGoogleOptimizeAdLoading); + // If meta data doesn't exist, add it + if (googleOptimizeAdLoadingMetaData == null) + { + elementApplication.Add(CreateMetaDataElement(KeyMetaDataGoogleOptimizeAdLoading, true)); + } + } + + private static void DisableAutoInitIfNeeded(XElement elementApplication, IEnumerable metaDataElements) + { + if (AppLovinPackageManager.IsAdapterInstalled("MobileFuse")) + { + var mobileFuseMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataMobileFuseAutoInit); + // If MobileFuse meta data doesn't exist, add it + if (mobileFuseMetaData == null) + { + elementApplication.Add(CreateMetaDataElement(KeyMetaDataMobileFuseAutoInit, true)); + } + } + + if (AppLovinPackageManager.IsAdapterInstalled("MyTarget")) + { + var myTargetMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataMyTargetAutoInit); + // If MyTarget meta data doesn't exist, add it + if (myTargetMetaData == null) + { + elementApplication.Add(CreateMetaDataElement(KeyMetaDataMyTargetAutoInit, 0)); + } + } + } + + private static void RemoveSdkKeyIfNeeded(IEnumerable metaDataElements) + { + var sdkKeyMetaData = GetMetaDataElement(metaDataElements, KeyMetaDataAppLovinSdkKey); + if (sdkKeyMetaData == null) return; + + sdkKeyMetaData.Remove(); + } + + private static void UpdateGradleVersionsIfNeeded(string gradleWrapperPropertiesPath, string rootGradleBuildFilePath) + { + var customGradleVersionUrl = AppLovinSettings.Instance.CustomGradleVersionUrl; + var customGradleToolsVersion = AppLovinSettings.Instance.CustomGradleToolsVersion; + + if (MaxSdkUtils.IsValidString(customGradleVersionUrl)) + { + var newDistributionUrl = string.Format("distributionUrl={0}", customGradleVersionUrl); + if (ReplaceStringInFile(gradleWrapperPropertiesPath, TokenDistributionUrl, newDistributionUrl)) + { + MaxSdkLogger.D("Distribution url set to " + newDistributionUrl); + } + else + { + MaxSdkLogger.E("Failed to set distribution URL"); + } + } + + if (MaxSdkUtils.IsValidString(customGradleToolsVersion)) + { +#if UNITY_2022_3_OR_NEWER + // Unity 2022.3+ requires Gradle Plugin version 7.1.2+. + if (MaxSdkUtils.CompareVersions(customGradleToolsVersion, "7.1.2") == MaxSdkUtils.VersionComparisonResult.Lesser) + { + MaxSdkLogger.E("Failed to set gradle plugin version. Unity 2022.3+ requires gradle plugin version 7.1.2+"); + return; + } + + var newGradleVersionLibraryLine = AppLovinProcessGradleBuildFile.GetFormattedBuildScriptLine(string.Format("id 'com.android.library' version '{0}' apply false", customGradleToolsVersion)); + if (ReplaceStringInFile(rootGradleBuildFilePath, TokenGradleVersionLibrary, newGradleVersionLibraryLine)) + { + MaxSdkLogger.D("Gradle library version set to " + newGradleVersionLibraryLine); + } + else + { + MaxSdkLogger.E("Failed to set gradle library version"); + } + + var newGradleVersionLine = AppLovinProcessGradleBuildFile.GetFormattedBuildScriptLine(string.Format("id 'com.android.application' version '{0}' apply false", customGradleToolsVersion)); +#else + var newGradleVersionLine = AppLovinProcessGradleBuildFile.GetFormattedBuildScriptLine(string.Format("classpath 'com.android.tools.build:gradle:{0}'", customGradleToolsVersion)); +#endif + if (ReplaceStringInFile(rootGradleBuildFilePath, TokenGradleVersion, newGradleVersionLine)) + { + MaxSdkLogger.D("Gradle version set to " + newGradleVersionLine); + } + else + { + MaxSdkLogger.E("Failed to set gradle plugin version"); + } + } + } + + private static void AddSdkSettings(string path) + { + var appLovinSdkSettings = new Dictionary(); + var rawResourceDirectory = Path.Combine(path, "src/main/res/raw"); + + // Add the SDK key to the SDK settings. + appLovinSdkSettings[KeySdkKey] = AppLovinSettings.Instance.SdkKey; + appLovinSdkSettings[KeyRenderOutsideSafeArea] = PlayerSettings.Android.renderOutsideSafeArea; + + // Add the Terms and Privacy Policy flow settings if needed. + EnableConsentFlowIfNeeded(rawResourceDirectory, appLovinSdkSettings); + + WriteAppLovinSettings(rawResourceDirectory, appLovinSdkSettings); + } + + private static void EnableConsentFlowIfNeeded(string rawResourceDirectory, Dictionary applovinSdkSettings) + { + // Check if consent flow is enabled. No need to create the applovin_consent_flow_settings.json if consent flow is disabled. + var consentFlowEnabled = AppLovinInternalSettings.Instance.ConsentFlowEnabled; + if (!consentFlowEnabled) + { + RemoveAppLovinSettingsRawResourceFileIfNeeded(rawResourceDirectory); + return; + } + + var privacyPolicyUrl = AppLovinInternalSettings.Instance.ConsentFlowPrivacyPolicyUrl; + if (string.IsNullOrEmpty(privacyPolicyUrl)) + { + AppLovinIntegrationManager.ShowBuildFailureDialog("You cannot use the AppLovin SDK's consent flow without defining a Privacy Policy URL in the AppLovin Integration Manager."); + + // No need to update the applovin_consent_flow_settings.json here. Default consent flow state will be determined on the SDK side. + return; + } + + var consentFlowSettings = new Dictionary(); + consentFlowSettings[KeyConsentFlowEnabled] = consentFlowEnabled; + consentFlowSettings[KeyConsentFlowPrivacyPolicy] = privacyPolicyUrl; + + var termsOfServiceUrl = AppLovinInternalSettings.Instance.ConsentFlowTermsOfServiceUrl; + if (MaxSdkUtils.IsValidString(termsOfServiceUrl)) + { + consentFlowSettings[KeyConsentFlowTermsOfService] = termsOfServiceUrl; + } + + var debugUserGeography = AppLovinInternalSettings.Instance.DebugUserGeography; + if (debugUserGeography == MaxSdkBase.ConsentFlowUserGeography.Gdpr) + { + consentFlowSettings[KeyConsentFlowDebugUserGeography] = "gdpr"; + } + + applovinSdkSettings[KeyConsentFlowSettings] = consentFlowSettings; + } + + private static void WriteAppLovinSettingsRawResourceFile(string applovinSdkSettingsJson, string rawResourceDirectory) + { + if (!Directory.Exists(rawResourceDirectory)) + { + Directory.CreateDirectory(rawResourceDirectory); + } + + var consentFlowSettingsFilePath = Path.Combine(rawResourceDirectory, AppLovinSettingsFileName); + try + { + File.WriteAllText(consentFlowSettingsFilePath, applovinSdkSettingsJson + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("applovin_settings.json file write failed due to: " + exception.Message); + Console.WriteLine(exception); + } + } + + /// + /// Removes the applovin_settings json file from the build if it exists. + /// + /// The raw resource directory that holds the json file + private static void RemoveAppLovinSettingsRawResourceFileIfNeeded(string rawResourceDirectory) + { + var consentFlowSettingsFilePath = Path.Combine(rawResourceDirectory, AppLovinSettingsFileName); + if (!File.Exists(consentFlowSettingsFilePath)) return; + + try + { + File.Delete(consentFlowSettingsFilePath); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Deleting applovin_settings.json failed due to: " + exception.Message); + Console.WriteLine(exception); + } + } + + private static void WriteAppLovinSettings(string rawResourceDirectory, Dictionary applovinSdkSettings) + { + var applovinSdkSettingsJson = Json.Serialize(applovinSdkSettings); + WriteAppLovinSettingsRawResourceFile(applovinSdkSettingsJson, rawResourceDirectory); + } + + /// + /// Creates and returns a meta-data element with the given name and value. + /// + private static XElement CreateMetaDataElement(string name, object value) + { + var metaData = new XElement("meta-data"); + metaData.Add(new XAttribute(AndroidNamespace + "name", name)); + metaData.Add(new XAttribute(AndroidNamespace + "value", value)); + + return metaData; + } + + /// + /// Looks through all the given meta-data elements to check if the required one exists. Returns null if it doesn't exist. + /// + private static XElement GetMetaDataElement(IEnumerable metaDataElements, string metaDataName) + { + foreach (var metaDataElement in metaDataElements) + { + var attributes = metaDataElement.Attributes(); + if (attributes.Any(attribute => attribute.Name.Namespace.Equals(AndroidNamespace) + && attribute.Name.LocalName.Equals("name") + && attribute.Value.Equals(metaDataName))) + { + return metaDataElement; + } + } + + return null; + } + + /// + /// Finds the first line that contains regexToMatch and replaces the whole line with replacement + /// + /// Path to the file you want to replace a line in + /// Regex to search for in the line you want to replace + /// String that you want as the new line + /// Returns whether the string was successfully replaced or not + private static bool ReplaceStringInFile(string path, Regex regexToMatch, string replacement) + { + if (!File.Exists(path)) return false; + + var lines = File.ReadAllLines(path); + for (var i = 0; i < lines.Length; i++) + { + if (regexToMatch.IsMatch(lines[i])) + { + lines[i] = replacement; + File.WriteAllLines(path, lines); + return true; + } + } + + return false; + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs.meta new file mode 100644 index 0000000..2877140 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: c01ea79d0cb2a43c093e2fd07201df9e +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroid.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs new file mode 100644 index 0000000..e3a0d2e --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs @@ -0,0 +1,70 @@ +// +// AppLovinBuildPostProcessor.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 8/29/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if UNITY_ANDROID + +using System.IO; +using UnityEditor.Android; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// Adds Quality Service plugin to the Gradle project once the project has been exported. See for more details. + /// + public class AppLovinPostProcessGradleProject : AppLovinProcessGradleBuildFile, IPostGenerateGradleAndroidProject + { + public void OnPostGenerateGradleAndroidProject(string path) + { + if (!AppLovinSettings.Instance.QualityServiceEnabled) return; + +#if UNITY_2019_3_OR_NEWER + // On Unity 2019.3+, the path returned is the path to the unityLibrary's module. + // The AppLovin Quality Service buildscript closure related lines need to be added to the root build.gradle file. + var rootGradleBuildFilePath = Path.Combine(path, "../build.gradle"); + var rootSettingsGradleFilePath = Path.Combine(path, "../settings.gradle"); + + // For 2022.2 and newer and 2021.3.41+ + var qualityServiceAdded = AddPluginToRootGradleBuildFile(rootGradleBuildFilePath); + var appLovinRepositoryAdded = AddAppLovinRepository(rootSettingsGradleFilePath); + + // For 2021.3.40 and older and 2022.0 - 2022.1.x + var buildScriptChangesAdded = AddQualityServiceBuildScriptLines(rootGradleBuildFilePath); + + var failedToAddPlugin = !buildScriptChangesAdded && !(qualityServiceAdded && appLovinRepositoryAdded); + if (failedToAddPlugin) + { + MaxSdkLogger.UserWarning("Failed to add AppLovin Quality Service plugin to the gradle project."); + return; + } + + // The plugin needs to be added to the application module (named launcher) + var applicationGradleBuildFilePath = Path.Combine(path, "../launcher/build.gradle"); +#else + // If Gradle template is enabled, we would have already updated the plugin. + if (AppLovinIntegrationManager.GradleTemplateEnabled) return; + + var applicationGradleBuildFilePath = Path.Combine(path, "build.gradle"); +#endif + + if (!File.Exists(applicationGradleBuildFilePath)) + { + MaxSdkLogger.UserWarning("Couldn't find build.gradle file. Failed to add AppLovin Quality Service plugin to the gradle project."); + return; + } + + AddAppLovinQualityServicePlugin(applicationGradleBuildFilePath); + } + + public int callbackOrder + { + get { return int.MaxValue; } + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs.meta new file mode 100644 index 0000000..c167f0c --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: f75e54e2eb78f427ca8643c97684387b +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessAndroidGradle.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs new file mode 100644 index 0000000..99eb59e --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs @@ -0,0 +1,724 @@ +// +// MaxIntegrationManager.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 8/29/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if UNITY_IOS || UNITY_IPHONE +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Callbacks; +#if UNITY_2019_3_OR_NEWER +using UnityEditor.iOS.Xcode.Extensions; +#endif +using UnityEditor.iOS.Xcode; +using UnityEditor.PackageManager; +using UnityEngine; +using UnityEngine.Networking; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + [Serializable] + public class SkAdNetworkData + { + [SerializeField] public string[] SkAdNetworkIds; + } + + public class AppLovinPostProcessiOS + { + private const string OutputFileName = "AppLovinQualityServiceSetup.rb"; + +#if !UNITY_2019_3_OR_NEWER + private const string UnityMainTargetName = "Unity-iPhone"; +#endif + // Use a priority of 90 to have AppLovin embed frameworks after Pods are installed (EDM finishes installing Pods at priority 60) and before Firebase Crashlytics runs their scripts (at priority 100). + private const int AppLovinEmbedFrameworksPriority = 90; + + private const string TargetUnityIphonePodfileLine = "target 'Unity-iPhone' do"; + private const string UseFrameworksPodfileLine = "use_frameworks!"; + private const string UseFrameworksDynamicPodfileLine = "use_frameworks! :linkage => :dynamic"; + private const string UseFrameworksStaticPodfileLine = "use_frameworks! :linkage => :static"; + + private const string ResourcesDirectoryName = "Resources"; + private const string AppLovinMaxResourcesDirectoryName = "AppLovinMAXResources"; + private const string AppLovinAdvertisingAttributionEndpoint = "https://postbacks-app.com"; + + private const string AppLovinSettingsPlistFileName = "AppLovin-Settings.plist"; + + private const string KeySdkKey = "SdkKey"; + + private const string AppLovinVerboseLoggingOnKey = "AppLovinVerboseLoggingOn"; + + private const string KeyConsentFlowInfo = "ConsentFlowInfo"; + private const string KeyConsentFlowEnabled = "ConsentFlowEnabled"; + private const string KeyConsentFlowTermsOfService = "ConsentFlowTermsOfService"; + private const string KeyConsentFlowPrivacyPolicy = "ConsentFlowPrivacyPolicy"; + private const string KeyConsentFlowDebugUserGeography = "ConsentFlowDebugUserGeography"; + + private const string KeyAppLovinSdkKeyToRemove = "AppLovinSdkKey"; + + private static readonly Regex PodfilePodLineRegex = new Regex("pod \'([^\']*)\'"); + + /// + /// Adds AppLovin Quality Service to the iOS project once the project has been exported. + /// + /// 1. Downloads the Quality Service ruby script. + /// 2. Runs the script using Ruby which integrates AppLovin Quality Service to the project. + /// + [PostProcessBuild(int.MaxValue)] // We want to run Quality Service script last. + public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath) + { + if (!AppLovinSettings.Instance.QualityServiceEnabled) return; + + var sdkKey = AppLovinSettings.Instance.SdkKey; + if (string.IsNullOrEmpty(sdkKey)) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. SDK Key is empty. Please enter the AppLovin SDK Key in the Integration Manager."); + return; + } + + var outputFilePath = Path.Combine(buildPath, OutputFileName); + + // Check if Quality Service is already installed. + if (File.Exists(outputFilePath) && Directory.Exists(Path.Combine(buildPath, "AppLovinQualityService"))) + { + // TODO: Check if there is a way to validate if the SDK key matches the script. Else the pub can't use append when/if they change the SDK Key. + return; + } + + // Download the ruby script needed to install Quality Service + var downloadHandler = new DownloadHandlerFile(outputFilePath); + var postJson = string.Format("{{\"sdk_key\" : \"{0}\"}}", sdkKey); + var bodyRaw = Encoding.UTF8.GetBytes(postJson); + var uploadHandler = new UploadHandlerRaw(bodyRaw); + uploadHandler.contentType = "application/json"; + + using (var unityWebRequest = new UnityWebRequest("https://api2.safedk.com/v1/build/ios_setup2")) + { + unityWebRequest.method = UnityWebRequest.kHttpVerbPOST; + unityWebRequest.downloadHandler = downloadHandler; + unityWebRequest.uploadHandler = uploadHandler; + var operation = unityWebRequest.SendWebRequest(); + + // Wait for the download to complete or the request to timeout. + while (!operation.isDone) { } + +#if UNITY_2020_1_OR_NEWER + if (unityWebRequest.result != UnityWebRequest.Result.Success) +#else + if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) +#endif + { + MaxSdkLogger.UserError("AppLovin Quality Service installation failed. Failed to download script with error: " + unityWebRequest.error); + return; + } + + // Check if Ruby is installed + var rubyVersion = AppLovinCommandLine.Run("ruby", "--version", buildPath); + if (rubyVersion.ExitCode != 0) + { + MaxSdkLogger.UserError("AppLovin Quality Service installation requires Ruby. Please install Ruby, export it to your system PATH and re-export the project."); + return; + } + + // Ruby is installed, run `ruby AppLovinQualityServiceSetup.rb` + var result = AppLovinCommandLine.Run("ruby", OutputFileName, buildPath); + + // Check if we have an error. + if (result.ExitCode != 0) MaxSdkLogger.UserError("Failed to set up AppLovin Quality Service"); + + MaxSdkLogger.UserDebug(result.Message); + } + } + + [PostProcessBuild(AppLovinEmbedFrameworksPriority)] + public static void MaxPostProcessPbxProject(BuildTarget buildTarget, string buildPath) + { + var projectPath = PBXProject.GetPBXProjectPath(buildPath); + var project = new PBXProject(); + project.ReadFromFile(projectPath); + +#if UNITY_2019_3_OR_NEWER + var unityMainTargetGuid = project.GetUnityMainTargetGuid(); + var unityFrameworkTargetGuid = project.GetUnityFrameworkTargetGuid(); +#else + var unityMainTargetGuid = project.TargetGuidByName(UnityMainTargetName); + var unityFrameworkTargetGuid = project.TargetGuidByName(UnityMainTargetName); +#endif + EmbedDynamicLibrariesIfNeeded(buildPath, project, unityMainTargetGuid); + + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionDe, "de", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEn, "en", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEs, "es", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionFr, "fr", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionJa, "ja", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionKo, "ko", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHans, "zh-Hans", buildPath, project, unityMainTargetGuid); + LocalizeUserTrackingDescriptionIfNeeded(AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionZhHant, "zh-Hant", buildPath, project, unityMainTargetGuid); + + AddSwiftSupport(buildPath, project, unityFrameworkTargetGuid, unityMainTargetGuid); + AddYandexSettingsIfNeeded(project, unityMainTargetGuid); + + project.WriteToFile(projectPath); + } + + private static void EmbedDynamicLibrariesIfNeeded(string buildPath, PBXProject project, string targetGuid) + { + // Check that the Pods directory exists (it might not if a publisher is building with Generate Podfile setting disabled in EDM). + var podsDirectory = Path.Combine(buildPath, "Pods"); + if (!Directory.Exists(podsDirectory) || !ShouldEmbedDynamicLibraries(buildPath)) return; + + var dynamicLibraryPathsToEmbed = GetDynamicLibraryPathsToEmbed(podsDirectory, buildPath); + if (dynamicLibraryPathsToEmbed == null || dynamicLibraryPathsToEmbed.Count == 0) return; + +#if UNITY_2019_3_OR_NEWER + foreach (var dynamicLibraryPath in dynamicLibraryPathsToEmbed) + { + var fileGuid = project.AddFile(dynamicLibraryPath, dynamicLibraryPath); + project.AddFileToEmbedFrameworks(targetGuid, fileGuid); + } +#else + string runpathSearchPaths; + runpathSearchPaths = project.GetBuildPropertyForAnyConfig(targetGuid, "LD_RUNPATH_SEARCH_PATHS"); + runpathSearchPaths += string.IsNullOrEmpty(runpathSearchPaths) ? "" : " "; + + // Check if runtime search paths already contains the required search paths for dynamic libraries. + if (runpathSearchPaths.Contains("@executable_path/Frameworks")) return; + + runpathSearchPaths += "@executable_path/Frameworks"; + project.SetBuildProperty(targetGuid, "LD_RUNPATH_SEARCH_PATHS", runpathSearchPaths); +#endif + } + + /// + /// |-----------------------------------------------------------------------------------------------------------------------------------------------------| + /// | embed | use_frameworks! (:linkage => :dynamic) | use_frameworks! :linkage => :static | `use_frameworks!` line not present | + /// |---------------------------|------------------------------------------|---------------------------------------|--------------------------------------| + /// | Unity-iPhone present | Do not embed dynamic libraries | Embed dynamic libraries | Do not embed dynamic libraries | + /// | Unity-iPhone not present | Embed dynamic libraries | Embed dynamic libraries | Embed dynamic libraries | + /// |-----------------------------------------------------------------------------------------------------------------------------------------------------| + /// + /// An iOS build path + /// Whether or not the dynamic libraries should be embedded. + private static bool ShouldEmbedDynamicLibraries(string buildPath) + { + var podfilePath = Path.Combine(buildPath, "Podfile"); + if (!File.Exists(podfilePath)) return false; + + // If the Podfile doesn't have a `Unity-iPhone` target, we should embed the dynamic libraries. + var lines = File.ReadAllLines(podfilePath); + var containsUnityIphoneTarget = lines.Any(line => line.Contains(TargetUnityIphonePodfileLine)); + if (!containsUnityIphoneTarget) return true; + + // If the Podfile does not have a `use_frameworks! :linkage => static` line, we should not embed the dynamic libraries. + var useFrameworksStaticLineIndex = Array.FindIndex(lines, line => line.Contains(UseFrameworksStaticPodfileLine)); + if (useFrameworksStaticLineIndex == -1) return false; + + // If more than one of the `use_frameworks!` lines are present, CocoaPods will use the last one. + var useFrameworksLineIndex = Array.FindIndex(lines, line => line.Trim() == UseFrameworksPodfileLine); // Check for exact line to avoid matching `use_frameworks! :linkage => static/dynamic` + var useFrameworksDynamicLineIndex = Array.FindIndex(lines, line => line.Contains(UseFrameworksDynamicPodfileLine)); + + // Check if `use_frameworks! :linkage => :static` is the last line of the three. If it is, we should embed the dynamic libraries. + return useFrameworksLineIndex < useFrameworksStaticLineIndex && useFrameworksDynamicLineIndex < useFrameworksStaticLineIndex; + } + + private static List GetDynamicLibraryPathsToEmbed(string podsDirectory, string buildPath) + { + var podfilePath = Path.Combine(buildPath, "Podfile"); + var dynamicLibraryFrameworksToEmbed = GetDynamicLibraryFrameworksToEmbed(podfilePath); + + return GetDynamicLibraryPathsInProjectToEmbed(podsDirectory, dynamicLibraryFrameworksToEmbed); + } + + private static List GetDynamicLibraryFrameworksToEmbed(string podfilePath) + { + var dynamicLibrariesToEmbed = GetDynamicLibrariesToEmbed(); + + var podsInUnityIphoneTarget = GetPodNamesInUnityIphoneTarget(podfilePath); + var dynamicLibrariesToIgnore = dynamicLibrariesToEmbed.Where(dynamicLibraryToEmbed => podsInUnityIphoneTarget.Contains(dynamicLibraryToEmbed.PodName)).ToList(); + + // Determine frameworks to embed based on the dynamic libraries to embed and ignore + var dynamicLibraryFrameworksToIgnore = dynamicLibrariesToIgnore.SelectMany(library => library.FrameworkNames).Distinct().ToList(); + return dynamicLibrariesToEmbed.SelectMany(library => library.FrameworkNames).Except(dynamicLibraryFrameworksToIgnore).Distinct().ToList(); + } + + private static List GetDynamicLibrariesToEmbed() + { + var pluginData = AppLovinIntegrationManager.LoadPluginDataSync(); + if (pluginData == null) + { + MaxSdkLogger.E("Failed to load plugin data. Dynamic libraries will not be embedded."); + return null; + } + + // Get the dynamic libraries to embed for each network + var librariesToAdd = pluginData.MediatedNetworks + .Where(network => network.DynamicLibrariesToEmbed != null) + .SelectMany(network => network.DynamicLibrariesToEmbed + .Where(libraryToEmbed => IsRequiredNetworkVersionInstalled(libraryToEmbed, network))) + .ToList(); + + // Get the dynamic libraries to embed for AppLovin MAX + if (pluginData.AppLovinMax.DynamicLibrariesToEmbed != null) + { + librariesToAdd.AddRange(pluginData.AppLovinMax.DynamicLibrariesToEmbed); + } + + // Get the dynamic libraries to embed for third parties + if (pluginData.ThirdPartyDynamicLibrariesToEmbed != null) + { + // TODO: Add version check for third party dynamic libraries. + librariesToAdd.AddRange(pluginData.ThirdPartyDynamicLibrariesToEmbed); + } + + return librariesToAdd; + } + + private static List GetPodNamesInUnityIphoneTarget(string podfilePath) + { + var lines = File.ReadAllLines(podfilePath); + var podNamesInUnityIphone = new List(); + + var insideUnityIphoneTarget = false; + foreach (var line in lines) + { + // Loop until we find the `target 'Unity-iPhone'` line + if (insideUnityIphoneTarget) + { + if (line.Trim() == "end") break; + + if (PodfilePodLineRegex.IsMatch(line)) + { + var podName = PodfilePodLineRegex.Match(line).Groups[1].Value; + podNamesInUnityIphone.Add(podName); + } + } + else if (line.Contains(TargetUnityIphonePodfileLine)) + { + insideUnityIphoneTarget = true; + } + } + + return podNamesInUnityIphone; + } + + private static bool IsRequiredNetworkVersionInstalled(DynamicLibraryToEmbed libraryToEmbed, Network network) + { + var currentIosVersion = network.CurrentVersions.Ios; + if (string.IsNullOrEmpty(currentIosVersion)) return false; + + var minIosVersion = libraryToEmbed.MinVersion; + var maxIosVersion = libraryToEmbed.MaxVersion; + + var greaterThanOrEqualToMinVersion = string.IsNullOrEmpty(minIosVersion) || MaxSdkUtils.CompareVersions(currentIosVersion, minIosVersion) != MaxSdkUtils.VersionComparisonResult.Lesser; + var lessThanOrEqualToMaxVersion = string.IsNullOrEmpty(maxIosVersion) || MaxSdkUtils.CompareVersions(currentIosVersion, maxIosVersion) != MaxSdkUtils.VersionComparisonResult.Greater; + + return greaterThanOrEqualToMinVersion && lessThanOrEqualToMaxVersion; + } + + private static List GetDynamicLibraryPathsInProjectToEmbed(string podsDirectory, List dynamicLibrariesToEmbed) + { + var dynamicLibraryPathsPresentInProject = new List(); + foreach (var dynamicLibraryToSearch in dynamicLibrariesToEmbed) + { + // both .framework and .xcframework are directories, not files + var directories = Directory.GetDirectories(podsDirectory, dynamicLibraryToSearch, SearchOption.AllDirectories); + if (directories.Length <= 0) continue; + + var dynamicLibraryAbsolutePath = directories[0]; + var relativePath = GetDynamicLibraryRelativePath(dynamicLibraryAbsolutePath); + dynamicLibraryPathsPresentInProject.Add(relativePath); + } + + return dynamicLibraryPathsPresentInProject; + } + + private static string GetDynamicLibraryRelativePath(string dynamicLibraryAbsolutePath) + { + var index = dynamicLibraryAbsolutePath.LastIndexOf("Pods", StringComparison.Ordinal); + return dynamicLibraryAbsolutePath.Substring(index); + } + + private static void LocalizeUserTrackingDescriptionIfNeeded(string localizedUserTrackingDescription, string localeCode, string buildPath, PBXProject project, string targetGuid) + { + var resourcesDirectoryPath = Path.Combine(buildPath, AppLovinMaxResourcesDirectoryName); + var localeSpecificDirectoryName = localeCode + ".lproj"; + var localeSpecificDirectoryPath = Path.Combine(resourcesDirectoryPath, localeSpecificDirectoryName); + var infoPlistStringsFilePath = Path.Combine(localeSpecificDirectoryPath, "InfoPlist.strings"); + + // Check if localization has been disabled between builds, and remove them as needed. + if (ShouldRemoveLocalization(localizedUserTrackingDescription)) + { + if (!File.Exists(infoPlistStringsFilePath)) return; + + File.Delete(infoPlistStringsFilePath); + return; + } + + // Log an error if we detect a localization file for this language in the `Resources` directory + var legacyResourcedDirectoryPath = Path.Combine(buildPath, ResourcesDirectoryName); + var localeSpecificLegacyDirectoryPath = Path.Combine(legacyResourcedDirectoryPath, localeSpecificDirectoryName); + if (Directory.Exists(localeSpecificLegacyDirectoryPath)) + { + MaxSdkLogger.UserError("Detected existing localization resource for \"" + localeCode + "\" locale. Skipping localization for User Tracking Usage Description. Please disable localization in AppLovin Integration manager and add the localizations to your existing resource."); + return; + } + + // Create intermediate directories as needed. + if (!Directory.Exists(resourcesDirectoryPath)) + { + Directory.CreateDirectory(resourcesDirectoryPath); + } + + if (!Directory.Exists(localeSpecificDirectoryPath)) + { + Directory.CreateDirectory(localeSpecificDirectoryPath); + } + + var localizedDescriptionLine = "\"NSUserTrackingUsageDescription\" = \"" + localizedUserTrackingDescription + "\";\n"; + // File already exists, update it in case the value changed between builds. + if (File.Exists(infoPlistStringsFilePath)) + { + var output = new List(); + var lines = File.ReadAllLines(infoPlistStringsFilePath); + var keyUpdated = false; + foreach (var line in lines) + { + if (line.Contains("NSUserTrackingUsageDescription")) + { + output.Add(localizedDescriptionLine); + keyUpdated = true; + } + else + { + output.Add(line); + } + } + + if (!keyUpdated) + { + output.Add(localizedDescriptionLine); + } + + File.WriteAllText(infoPlistStringsFilePath, string.Join("\n", output.ToArray()) + "\n"); + } + // File doesn't exist, create one. + else + { + File.WriteAllText(infoPlistStringsFilePath, "/* Localized versions of Info.plist keys - Generated by AL MAX plugin */\n" + localizedDescriptionLine); + } + + var localeSpecificDirectoryRelativePath = Path.Combine(AppLovinMaxResourcesDirectoryName, localeSpecificDirectoryName); + var guid = project.AddFolderReference(localeSpecificDirectoryRelativePath, localeSpecificDirectoryRelativePath); + project.AddFileToBuild(targetGuid, guid); + } + + private static bool ShouldRemoveLocalization(string localizedUserTrackingDescription) + { + if (string.IsNullOrEmpty(localizedUserTrackingDescription)) return true; + + var internalSettings = AppLovinInternalSettings.Instance; + return !internalSettings.ConsentFlowEnabled || !internalSettings.UserTrackingUsageLocalizationEnabled; + } + + private static void AddSwiftSupport(string buildPath, PBXProject project, string unityFrameworkTargetGuid, string unityMainTargetGuid) + { + var swiftFileRelativePath = "Classes/MAXSwiftSupport.swift"; + var swiftFilePath = Path.Combine(buildPath, swiftFileRelativePath); + + // Add Swift file + CreateSwiftFile(swiftFilePath); + var swiftFileGuid = project.AddFile(swiftFileRelativePath, swiftFileRelativePath); + project.AddFileToBuild(unityFrameworkTargetGuid, swiftFileGuid); + + // Add Swift version property if needed + var swiftVersion = project.GetBuildPropertyForAnyConfig(unityFrameworkTargetGuid, "SWIFT_VERSION"); + if (string.IsNullOrEmpty(swiftVersion)) + { + project.SetBuildProperty(unityFrameworkTargetGuid, "SWIFT_VERSION", "5.0"); + } + + // Enable Swift modules + project.AddBuildProperty(unityFrameworkTargetGuid, "CLANG_ENABLE_MODULES", "YES"); + project.AddBuildProperty(unityMainTargetGuid, "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES", "YES"); + } + + private static void CreateSwiftFile(string swiftFilePath) + { + if (File.Exists(swiftFilePath)) return; + + // Create a file to write to. + using (var writer = File.CreateText(swiftFilePath)) + { + writer.WriteLine("//\n// MAXSwiftSupport.swift\n//"); + writer.WriteLine("\nimport Foundation\n"); + writer.WriteLine("// This file ensures the project includes Swift support."); + writer.WriteLine("// It is automatically generated by the MAX Unity Plugin."); + writer.Close(); + } + } + + [PostProcessBuild(int.MaxValue)] + public static void MaxPostProcessPlist(BuildTarget buildTarget, string path) + { + var plistPath = Path.Combine(path, "Info.plist"); + var plist = new PlistDocument(); + plist.ReadFromFile(plistPath); + + SetAttributionReportEndpointIfNeeded(plist); + + EnableVerboseLoggingIfNeeded(plist); + AddGoogleApplicationIdIfNeeded(plist); + + AddSdkSettings(plist, path); + AddSkAdNetworksInfoIfNeeded(plist); + RemoveSdkKeyIfNeeded(plist); + + plist.WriteToFile(plistPath); + } + + private static void SetAttributionReportEndpointIfNeeded(PlistDocument plist) + { + if (AppLovinSettings.Instance.SetAttributionReportEndpoint) + { + plist.root.SetString("NSAdvertisingAttributionReportEndpoint", AppLovinAdvertisingAttributionEndpoint); + } + else + { + PlistElement attributionReportEndPoint; + plist.root.values.TryGetValue("NSAdvertisingAttributionReportEndpoint", out attributionReportEndPoint); + + // Check if we had previously set the attribution endpoint and un-set it. + if (attributionReportEndPoint != null && AppLovinAdvertisingAttributionEndpoint.Equals(attributionReportEndPoint.AsString())) + { + plist.root.values.Remove("NSAdvertisingAttributionReportEndpoint"); + } + } + } + + private static void EnableVerboseLoggingIfNeeded(PlistDocument plist) + { + if (!EditorPrefs.HasKey(MaxSdkLogger.KeyVerboseLoggingEnabled)) return; + + var enabled = EditorPrefs.GetBool(MaxSdkLogger.KeyVerboseLoggingEnabled); + if (enabled) + { + plist.root.SetBoolean(AppLovinVerboseLoggingOnKey, true); + } + else + { + plist.root.values.Remove(AppLovinVerboseLoggingOnKey); + } + } + + private static void AddGoogleApplicationIdIfNeeded(PlistDocument plist) + { + if (!AppLovinPackageManager.IsAdapterInstalled("Google") && !AppLovinPackageManager.IsAdapterInstalled("GoogleAdManager")) return; + + const string googleApplicationIdentifier = "GADApplicationIdentifier"; + var appId = AppLovinSettings.Instance.AdMobIosAppId; + // Log error if the App ID is not set. + if (string.IsNullOrEmpty(appId) || !appId.StartsWith("ca-app-pub-")) + { + MaxSdkLogger.UserError("[AppLovin MAX] Google App ID is not set. Please enter a valid app ID within the AppLovin Integration Manager window."); + return; + } + + plist.root.SetString(googleApplicationIdentifier, appId); + } + + private static void AddYandexSettingsIfNeeded(PBXProject project, string unityMainTargetGuid) + { + if (!AppLovinPackageManager.IsAdapterInstalled("Yandex")) return; + + if (MaxSdkUtils.CompareVersions(PlayerSettings.iOS.targetOSVersionString, "12.0") == MaxSdkUtils.VersionComparisonResult.Lesser) + { + MaxSdkLogger.UserWarning("Your iOS target version is under the minimum required version by Yandex. Please update it to 12.0 or newer in your ProjectSettings and rebuild your project."); + return; + } + + project.SetBuildProperty(unityMainTargetGuid, "GENERATE_INFOPLIST_FILE", "NO"); + } + + private static void AddSdkSettings(PlistDocument infoPlist, string buildPath) + { + var sdkSettingsPlistPath = Path.Combine(buildPath, AppLovinSettingsPlistFileName); + var sdkSettingsPlist = new PlistDocument(); + if (File.Exists(sdkSettingsPlistPath)) + { + sdkSettingsPlist.ReadFromFile(sdkSettingsPlistPath); + } + + // Add the SDK key to the SDK settings plist. + sdkSettingsPlist.root.SetString(KeySdkKey, AppLovinSettings.Instance.SdkKey); + + // Add consent flow settings if needed. + EnableConsentFlowIfNeeded(sdkSettingsPlist, infoPlist); + + sdkSettingsPlist.WriteToFile(sdkSettingsPlistPath); + + var projectPath = PBXProject.GetPBXProjectPath(buildPath); + var project = new PBXProject(); + project.ReadFromFile(projectPath); + +#if UNITY_2019_3_OR_NEWER + var unityMainTargetGuid = project.GetUnityMainTargetGuid(); +#else + var unityMainTargetGuid = project.TargetGuidByName(UnityMainTargetName); +#endif + + var guid = project.AddFile(AppLovinSettingsPlistFileName, AppLovinSettingsPlistFileName, PBXSourceTree.Source); + project.AddFileToBuild(unityMainTargetGuid, guid); + project.WriteToFile(projectPath); + } + + private static void EnableConsentFlowIfNeeded(PlistDocument applovinSettingsPlist, PlistDocument infoPlist) + { + var consentFlowEnabled = AppLovinInternalSettings.Instance.ConsentFlowEnabled; + if (!consentFlowEnabled) return; + + var userTrackingUsageDescription = AppLovinInternalSettings.Instance.UserTrackingUsageDescriptionEn; + var privacyPolicyUrl = AppLovinInternalSettings.Instance.ConsentFlowPrivacyPolicyUrl; + if (string.IsNullOrEmpty(userTrackingUsageDescription) || string.IsNullOrEmpty(privacyPolicyUrl)) + { + AppLovinIntegrationManager.ShowBuildFailureDialog("You cannot use the AppLovin SDK's consent flow without defining a Privacy Policy URL and the `User Tracking Usage Description` in the AppLovin Integration Manager. \n\n" + + "Both values must be included to enable the SDK's consent flow."); + + // No need to update the info.plist here. Default consent flow state will be determined on the SDK side. + return; + } + + var consentFlowInfoRoot = applovinSettingsPlist.root.CreateDict(KeyConsentFlowInfo); + consentFlowInfoRoot.SetBoolean(KeyConsentFlowEnabled, consentFlowEnabled); + consentFlowInfoRoot.SetString(KeyConsentFlowPrivacyPolicy, privacyPolicyUrl); + + var termsOfServiceUrl = AppLovinInternalSettings.Instance.ConsentFlowTermsOfServiceUrl; + if (MaxSdkUtils.IsValidString(termsOfServiceUrl)) + { + consentFlowInfoRoot.SetString(KeyConsentFlowTermsOfService, termsOfServiceUrl); + } + + var debugUserGeography = AppLovinInternalSettings.Instance.DebugUserGeography; + if (debugUserGeography == MaxSdkBase.ConsentFlowUserGeography.Gdpr) + { + consentFlowInfoRoot.SetString(KeyConsentFlowDebugUserGeography, "gdpr"); + } + + infoPlist.root.SetString("NSUserTrackingUsageDescription", userTrackingUsageDescription); + } + + private static void AddSkAdNetworksInfoIfNeeded(PlistDocument plist) + { + var skAdNetworkData = GetSkAdNetworkData(); + var skAdNetworkIds = skAdNetworkData.SkAdNetworkIds; + // Check if we have a valid list of SKAdNetworkIds that need to be added. + if (skAdNetworkIds == null || skAdNetworkIds.Length < 1) return; + + // + // Add the SKAdNetworkItems to the plist. It should look like following: + // + // SKAdNetworkItems + // + // + // SKAdNetworkIdentifier + // ABC123XYZ.skadnetwork + // + // + // SKAdNetworkIdentifier + // 123QWE456.skadnetwork + // + // + // SKAdNetworkIdentifier + // 987XYZ123.skadnetwork + // + // + // + PlistElement skAdNetworkItems; + plist.root.values.TryGetValue("SKAdNetworkItems", out skAdNetworkItems); + var existingSkAdNetworkIds = new HashSet(); + // Check if SKAdNetworkItems array is already in the Plist document and collect all the IDs that are already present. + if (skAdNetworkItems != null && skAdNetworkItems.GetType() == typeof(PlistElementArray)) + { + var plistElementDictionaries = skAdNetworkItems.AsArray().values.Where(plistElement => plistElement.GetType() == typeof(PlistElementDict)); + foreach (var plistElement in plistElementDictionaries) + { + PlistElement existingId; + plistElement.AsDict().values.TryGetValue("SKAdNetworkIdentifier", out existingId); + if (existingId == null || existingId.GetType() != typeof(PlistElementString) || string.IsNullOrEmpty(existingId.AsString())) continue; + + existingSkAdNetworkIds.Add(existingId.AsString()); + } + } + // Else, create an array of SKAdNetworkItems into which we will add our IDs. + else + { + skAdNetworkItems = plist.root.CreateArray("SKAdNetworkItems"); + } + + foreach (var skAdNetworkId in skAdNetworkIds) + { + // Skip adding IDs that are already in the array. + if (existingSkAdNetworkIds.Contains(skAdNetworkId)) continue; + + var skAdNetworkItemDict = skAdNetworkItems.AsArray().AddDict(); + skAdNetworkItemDict.SetString("SKAdNetworkIdentifier", skAdNetworkId); + } + } + + private static SkAdNetworkData GetSkAdNetworkData() + { + // Get the list of installed ad networks to be passed up + var installedNetworks = AppLovinPackageManager.GetInstalledMediationNetworks(); + var uriBuilder = new UriBuilder("https://unity.applovin.com/max/1.0/skadnetwork_ids"); + var adNetworks = string.Join(",", installedNetworks.ToArray()); + if (!string.IsNullOrEmpty(adNetworks)) + { + uriBuilder.Query += string.Format("ad_networks={0}", adNetworks); + } + + using (var unityWebRequest = UnityWebRequest.Get(uriBuilder.ToString())) + { + var operation = unityWebRequest.SendWebRequest(); + // Wait for the download to complete or the request to timeout. + while (!operation.isDone) { } + +#if UNITY_2020_1_OR_NEWER + if (unityWebRequest.result != UnityWebRequest.Result.Success) +#else + if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) +#endif + { + MaxSdkLogger.UserError("Failed to retrieve SKAdNetwork IDs with error: " + unityWebRequest.error); + return new SkAdNetworkData(); + } + + try + { + return JsonUtility.FromJson(unityWebRequest.downloadHandler.text); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to parse data '" + unityWebRequest.downloadHandler.text + "' with exception: " + exception); + return new SkAdNetworkData(); + } + } + } + + private static void RemoveSdkKeyIfNeeded(PlistDocument plist) + { + if (!plist.root.values.ContainsKey(KeyAppLovinSdkKeyToRemove)) return; + + plist.root.values.Remove(KeyAppLovinSdkKeyToRemove); + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs.meta new file mode 100644 index 0000000..8182708 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: d5d209f90444f4a90830b48b5f3f3ff4 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPostProcessiOS.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs new file mode 100644 index 0000000..95fb426 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs @@ -0,0 +1,140 @@ +// +// AppLovinPreProcess.cs +// AppLovin MAX Unity Plugin +// +// Created by Jonathan Liu on 10/19/2023. +// Copyright © 2023 AppLovin. All rights reserved. +// + +using System; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public abstract class AppLovinPreProcess + { + private const string AppLovinDependenciesFileExportPath = "MaxSdk/AppLovin/Editor/Dependencies.xml"; + + private static readonly XmlWriterSettings DependenciesFileXmlWriterSettings = new XmlWriterSettings + { + Indent = true, + IndentChars = " ", + NewLineChars = "\n", + NewLineHandling = NewLineHandling.Replace + }; + + private static string AppLovinDependenciesFilePath + { + get { return AppLovinIntegrationManager.IsPluginInPackageManager ? Path.Combine("Assets", AppLovinDependenciesFileExportPath) : MaxSdkUtils.GetAssetPathForExportPath(AppLovinDependenciesFileExportPath); } + } + + /// + /// Creates a Dependencies.xml file under Assets/MaxSdk/AppLovin/Editor/ directory if the plugin is in the package manager. + /// This is needed since the Dependencies.xml file in the package manager is immutable. + /// + protected static void CreateAppLovinDependenciesFileIfNeeded() + { + if (!AppLovinIntegrationManager.IsPluginInPackageManager) return; + + var dependenciesFilePath = AppLovinDependenciesFilePath; + if (File.Exists(dependenciesFilePath)) return; + + var directory = Path.GetDirectoryName(dependenciesFilePath); + Directory.CreateDirectory(directory); + + var dependencies = new XDocument( + new XDeclaration("1.0", "utf-8", "yes"), + new XElement("dependencies", + new XElement("androidPackages", ""), + new XElement("iosPods", "") + ) + ); + + using (var xmlWriter = XmlWriter.Create(dependenciesFilePath, DependenciesFileXmlWriterSettings)) + { + dependencies.Save(xmlWriter); + } + } + + /// + /// Adds a string into AppLovin's Dependencies.xml file inside the containerElementString if it doesn't exist + /// + /// The line you want to add into the xml file + /// The root XML element under which to add the line. For example, to add a new dependency to Android, pass in "androidPackages" + protected static void TryAddStringToDependencyFile(string lineToAdd, string containerElementString) + { + try + { + var dependenciesFilePath = AppLovinDependenciesFilePath; + var dependencies = XDocument.Load(dependenciesFilePath); + // Get the container where we are going to insert the line + var containerElement = dependencies.Descendants(containerElementString).FirstOrDefault(); + + if (containerElement == null) + { + MaxSdkLogger.E(containerElementString + " not found in Dependencies.xml file"); + return; + } + + var elementToAdd = XElement.Parse(lineToAdd); + + // Check if the xml file doesn't already contain the string. + if (containerElement.Elements().Any(element => XNode.DeepEquals(element, elementToAdd))) return; + + // Append the new element to the container element + containerElement.Add(elementToAdd); + + using (var xmlWriter = XmlWriter.Create(dependenciesFilePath, DependenciesFileXmlWriterSettings)) + { + dependencies.Save(xmlWriter); + } + } + catch (Exception exception) + { + MaxSdkLogger.UserWarning("Google CMP will not function. Unable to add string to dependency file due to exception: " + exception.Message); + } + } + + /// + /// Removes a string from AppLovin's Dependencies.xml file inside the containerElementString if it exists + /// + /// The line you want to remove from the xml file + /// The root XML element from which to remove the line. For example, to remove an Android dependency, pass in "androidPackages" + protected static void TryRemoveStringFromDependencyFile(string lineToRemove, string containerElementString) + { + try + { + var dependenciesFilePath = AppLovinDependenciesFilePath; + if (!File.Exists(dependenciesFilePath)) return; + + var dependencies = XDocument.Load(dependenciesFilePath); + var containerElement = dependencies.Descendants(containerElementString).FirstOrDefault(); + + if (containerElement == null) + { + MaxSdkLogger.E(containerElementString + " not found in Dependencies.xml file"); + return; + } + + // Check if the dependency line exists. + var elementToFind = XElement.Parse(lineToRemove); + var existingElement = containerElement.Elements().FirstOrDefault(element => XNode.DeepEquals(element, elementToFind)); + if (existingElement == null) return; + + existingElement.Remove(); + + using (var xmlWriter = XmlWriter.Create(dependenciesFilePath, DependenciesFileXmlWriterSettings)) + { + dependencies.Save(xmlWriter); + } + } + catch (Exception exception) + { + MaxSdkLogger.UserWarning("Unable to remove string from dependency file due to exception: " + exception.Message); + } + } + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs.meta new file mode 100644 index 0000000..f5e00db --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 0e6254f24e89548b3a7644fa7bf25f9d +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcess.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs new file mode 100644 index 0000000..9c35dbe --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs @@ -0,0 +1,68 @@ +// +// AppLovinBuildPreProcessor.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 8/27/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if UNITY_ANDROID + +using UnityEditor.Build; +using UnityEditor.Build.Reporting; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + /// + /// Adds the AppLovin Quality Service plugin to the gradle template file. See for more details. + /// + public class AppLovinPreProcessAndroid : AppLovinProcessGradleBuildFile, IPreprocessBuildWithReport + { + private const string UmpLegacyDependencyLine = ""; + private const string UmpDependencyLine = ""; + private const string AndroidPackagesContainerElementString = "androidPackages"; + + public void OnPreprocessBuild(BuildReport report) + { + PreprocessAppLovinQualityServicePlugin(); + AddGoogleCmpDependencyIfNeeded(); + } + + private static void PreprocessAppLovinQualityServicePlugin() + { + // We can only process gradle template file here. If it is not available, we will try again in post build on Unity IDEs newer than 2018_2 (see AppLovinPostProcessGradleProject). + if (!AppLovinIntegrationManager.GradleTemplateEnabled) return; + +#if UNITY_2019_3_OR_NEWER + // The publisher could be migrating from older Unity versions to 2019_3 or newer. + // If so, we should delete the plugin from the template. The plugin will be added to the project's application module in the post processing script (AppLovinPostProcessGradleProject). + RemoveAppLovinQualityServiceOrSafeDkPlugin(AppLovinIntegrationManager.GradleTemplatePath); +#else + AddAppLovinQualityServicePlugin(AppLovinIntegrationManager.GradleTemplatePath); +#endif + } + + private static void AddGoogleCmpDependencyIfNeeded() + { + // Remove the legacy fixed UMP version if it exists, we'll add the dependency with a dynamic version below. + TryRemoveStringFromDependencyFile(UmpLegacyDependencyLine, AndroidPackagesContainerElementString); + + if (AppLovinInternalSettings.Instance.ConsentFlowEnabled) + { + CreateAppLovinDependenciesFileIfNeeded(); + TryAddStringToDependencyFile(UmpDependencyLine, AndroidPackagesContainerElementString); + } + else + { + TryRemoveStringFromDependencyFile(UmpDependencyLine, AndroidPackagesContainerElementString); + } + } + + public int callbackOrder + { + get { return int.MaxValue; } + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs.meta new file mode 100644 index 0000000..4dd79e8 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 8ccaf444d0d4f4cadb5debe7c41b20c4 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessAndroid.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs new file mode 100644 index 0000000..cffb232 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs @@ -0,0 +1,50 @@ +// +// AppLovinBuildPreProcessiOS.cs +// AppLovin MAX Unity Plugin +// +// Created by Jonathan Liu on 10/17/2023. +// Copyright © 2023 AppLovin. All rights reserved. +// + +#if UNITY_IOS + +using UnityEditor.Build; +using UnityEditor.Build.Reporting; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public class AppLovinPreProcessiOS : AppLovinPreProcess, IPreprocessBuildWithReport + { + public void OnPreprocessBuild(BuildReport report) + { + AddGoogleCmpDependencyIfNeeded(); + } + + private const string UmpLegacyDependencyLine = ""; + private const string UmpDependencyLine = ""; + private const string IosPodsContainerElementString = "iosPods"; + + private static void AddGoogleCmpDependencyIfNeeded() + { + // Remove the legacy fixed UMP version if it exists, we'll add the dependency with a dynamic version below. + TryRemoveStringFromDependencyFile(UmpLegacyDependencyLine, IosPodsContainerElementString); + + if (AppLovinInternalSettings.Instance.ConsentFlowEnabled) + { + CreateAppLovinDependenciesFileIfNeeded(); + TryAddStringToDependencyFile(UmpDependencyLine, IosPodsContainerElementString); + } + else + { + TryRemoveStringFromDependencyFile(UmpDependencyLine, IosPodsContainerElementString); + } + } + + public int callbackOrder + { + get { return int.MaxValue; } + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs.meta new file mode 100644 index 0000000..33bdffb --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: ee45537a5833240d7afcfac4a38df1b9 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinPreProcessiOS.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs new file mode 100644 index 0000000..166524c --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs @@ -0,0 +1,602 @@ +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 9/3/19. +// Copyright © 2019 AppLovin. All rights reserved. +// + +#if UNITY_ANDROID + +using System.Text; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Networking; +using Debug = UnityEngine.Debug; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + [Serializable] + public class AppLovinQualityServiceData + { + public string api_key; + } + + /// + /// Adds or updates the AppLovin Quality Service plugin to the provided build.gradle file. + /// If the gradle file already has the plugin, the API key is updated. + /// + public abstract class AppLovinProcessGradleBuildFile : AppLovinPreProcess + { + private static readonly Regex TokenBuildScriptRepositories = new Regex(".*repositories.*"); + private static readonly Regex TokenBuildScriptDependencies = new Regex(".*classpath \'com.android.tools.build:gradle.*"); + private static readonly Regex TokenApplicationPlugin = new Regex(".*apply plugin: \'com.android.application\'.*"); + private static readonly Regex TokenApiKey = new Regex(".*apiKey.*"); + private static readonly Regex TokenAppLovinPlugin = new Regex(".*apply plugin:.+?(?=applovin-quality-service).*"); + + private const string PluginsMatcher = "plugins"; + private const string PluginManagementMatcher = "pluginManagement"; + private const string QualityServicePluginRoot = " id 'com.applovin.quality' version '+' apply false // NOTE: Requires version 4.8.3+ for Gradle version 7.2+"; + + private const string BuildScriptMatcher = "buildscript"; + private const string QualityServiceMavenRepo = "maven { url 'https://artifacts.applovin.com/android'; content { includeGroupByRegex 'com.applovin.*' } }"; + private const string QualityServiceDependencyClassPath = "classpath 'com.applovin.quality:AppLovinQualityServiceGradlePlugin:+'"; + private const string QualityServiceApplyPlugin = "apply plugin: 'applovin-quality-service'"; + private const string QualityServicePlugin = "applovin {"; + private const string QualityServiceApiKey = " apiKey '{0}'"; + private const string QualityServiceBintrayMavenRepo = "https://applovin.bintray.com/Quality-Service"; + private const string QualityServiceNoRegexMavenRepo = "maven { url 'https://artifacts.applovin.com/android' }"; + + // Legacy plugin detection variables + private const string QualityServiceDependencyClassPathV3 = "classpath 'com.applovin.quality:AppLovinQualityServiceGradlePlugin:3.+'"; + private static readonly Regex TokenSafeDkLegacyApplyPlugin = new Regex(".*apply plugin:.+?(?=safedk).*"); + private const string SafeDkLegacyPlugin = "safedk {"; + private const string SafeDkLegacyMavenRepo = "http://download.safedk.com"; + private const string SafeDkLegacyDependencyClassPath = "com.safedk:SafeDKGradlePlugin:"; + + /// + /// Updates the provided Gradle script to add Quality Service plugin. + /// + /// The gradle file to update. + protected static void AddAppLovinQualityServicePlugin(string applicationGradleBuildFilePath) + { + if (!AppLovinSettings.Instance.QualityServiceEnabled) return; + + var sdkKey = AppLovinSettings.Instance.SdkKey; + if (string.IsNullOrEmpty(sdkKey)) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. SDK Key is empty. Please enter the AppLovin SDK Key in the Integration Manager."); + return; + } + + // Retrieve the API Key using the SDK Key. + var qualityServiceData = RetrieveQualityServiceData(sdkKey); + var apiKey = qualityServiceData.api_key; + if (string.IsNullOrEmpty(apiKey)) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. API Key is empty."); + return; + } + + // Generate the updated Gradle file that needs to be written. + var lines = File.ReadAllLines(applicationGradleBuildFilePath).ToList(); + var sanitizedLines = RemoveLegacySafeDkPlugin(lines); + var outputLines = GenerateUpdatedBuildFileLines( + sanitizedLines, + apiKey, +#if UNITY_2019_3_OR_NEWER + false // On Unity 2019.3+, the buildscript closure related lines will to be added to the root build.gradle file. +#else + true +#endif + ); + // outputLines can be null if we couldn't add the plugin. + if (outputLines == null) return; + + try + { + File.WriteAllText(applicationGradleBuildFilePath, string.Join("\n", outputLines.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. Gradle file write failed."); + Console.WriteLine(exception); + } + } + + /// + /// Adds AppLovin Quality Service plugin DSL element to the project's root build.gradle file. + /// Sample build.gradle file after adding quality service: + /// plugins { + /// id 'com.android.application' version '7.4.2' apply false + /// id 'com.android.library' version '7.4.2' apply false + /// id 'com.applovin.quality' version '+' apply false + /// } + /// tasks.register('clean', Delete) { + /// delete rootProject.layout.buildDirectory + /// } + /// + /// + /// The path to project's root build.gradle file. + /// true when the plugin was added successfully. + protected bool AddPluginToRootGradleBuildFile(string rootGradleBuildFile) + { + var lines = File.ReadAllLines(rootGradleBuildFile).ToList(); + + // Check if the plugin is already added to the file. + var pluginAdded = lines.Any(line => line.Contains(QualityServicePluginRoot)); + if (pluginAdded) return true; + + var outputLines = new List(); + var insidePluginsClosure = false; + foreach (var line in lines) + { + if (line.Contains(PluginsMatcher)) + { + insidePluginsClosure = true; + } + + if (!pluginAdded && insidePluginsClosure && line.Contains("}")) + { + outputLines.Add(QualityServicePluginRoot); + pluginAdded = true; + insidePluginsClosure = false; + } + + outputLines.Add(line); + } + + if (!pluginAdded) return false; + + try + { + File.WriteAllText(rootGradleBuildFile, string.Join("\n", outputLines.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. Root Gradle file write failed."); + Console.WriteLine(exception); + return false; + } + + return true; + } + + /// + /// Adds the AppLovin maven repository to the project's settings.gradle file. + /// Sample settings.gradle file after adding AppLovin Repository: + /// pluginManagement { + /// repositories { + /// maven { url 'https://artifacts.applovin.com/android'; content { includeGroupByRegex 'com.applovin.*' } } + /// + /// gradlePluginPortal() + /// google() + /// mavenCentral() + /// } + /// } + /// ... + /// + /// + /// The path to the project's settings.gradle file. + /// true if the repository was added successfully. + protected bool AddAppLovinRepository(string settingsGradleFile) + { + var lines = File.ReadLines(settingsGradleFile).ToList(); + var outputLines = new List(); + var mavenRepoAdded = false; + var pluginManagementClosureDepth = 0; + var insidePluginManagementClosure = false; + var pluginManagementMatched = false; + foreach (var line in lines) + { + outputLines.Add(line); + + if (!pluginManagementMatched && line.Contains(PluginManagementMatcher)) + { + pluginManagementMatched = true; + insidePluginManagementClosure = true; + } + + if (insidePluginManagementClosure) + { + if (line.Contains("{")) + { + pluginManagementClosureDepth++; + } + + if (line.Contains("}")) + { + pluginManagementClosureDepth--; + } + + if (pluginManagementClosureDepth == 0) + { + insidePluginManagementClosure = false; + } + } + + if (insidePluginManagementClosure) + { + if (!mavenRepoAdded && TokenBuildScriptRepositories.IsMatch(line)) + { + outputLines.Add(GetFormattedBuildScriptLine(QualityServiceMavenRepo)); + mavenRepoAdded = true; + } + } + } + + if (!mavenRepoAdded) return false; + + try + { + File.WriteAllText(settingsGradleFile, string.Join("\n", outputLines.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. Setting Gradle file write failed."); + Console.WriteLine(exception); + return false; + } + + return true; + } + +#if UNITY_2019_3_OR_NEWER + /// + /// Adds the necessary AppLovin Quality Service dependency and maven repo lines to the provided root build.gradle file. + /// Sample build.gradle file after adding quality service: + /// allprojects { + /// buildscript { + /// repositories { + /// maven { url 'https://artifacts.applovin.com/android'; content { includeGroupByRegex 'com.applovin.*' } } + /// google() + /// jcenter() + /// } + /// + /// dependencies { + /// classpath 'com.android.tools.build:gradle:4.0.1' + /// classpath 'com.applovin.quality:AppLovinQualityServiceGradlePlugin:+' + /// } + /// ... + /// + /// + /// The root build.gradle file path + /// true if the build script lines were applied correctly. + protected bool AddQualityServiceBuildScriptLines(string rootGradleBuildFile) + { + var lines = File.ReadAllLines(rootGradleBuildFile).ToList(); + var outputLines = GenerateUpdatedBuildFileLines(lines, null, true); + + // outputLines will be null if we couldn't add the build script lines. + if (outputLines == null) return false; + + try + { + File.WriteAllText(rootGradleBuildFile, string.Join("\n", outputLines.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to install AppLovin Quality Service plugin. Root Gradle file write failed."); + Console.WriteLine(exception); + return false; + } + + return true; + } + + /// + /// Removes the AppLovin Quality Service Plugin or Legacy SafeDK plugin from the given gradle template file if either of them are present. + /// + /// The gradle template file from which to remove the plugin from + protected static void RemoveAppLovinQualityServiceOrSafeDkPlugin(string gradleTemplateFile) + { + var lines = File.ReadAllLines(gradleTemplateFile).ToList(); + lines = RemoveLegacySafeDkPlugin(lines); + lines = RemoveAppLovinQualityServicePlugin(lines); + + try + { + File.WriteAllText(gradleTemplateFile, string.Join("\n", lines.ToArray()) + "\n"); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to remove AppLovin Quality Service Plugin from mainTemplate.gradle. Please remove the Quality Service plugin from the mainTemplate.gradle manually."); + Console.WriteLine(exception); + } + } +#endif + + private static AppLovinQualityServiceData RetrieveQualityServiceData(string sdkKey) + { + var postJson = string.Format("{{\"sdk_key\" : \"{0}\"}}", sdkKey); + var bodyRaw = Encoding.UTF8.GetBytes(postJson); + // Upload handler is automatically disposed when UnityWebRequest is disposed + var uploadHandler = new UploadHandlerRaw(bodyRaw); + uploadHandler.contentType = "application/json"; + + using (var unityWebRequest = new UnityWebRequest("https://api2.safedk.com/v1/build/cred")) + { + unityWebRequest.method = UnityWebRequest.kHttpVerbPOST; + unityWebRequest.uploadHandler = uploadHandler; + unityWebRequest.downloadHandler = new DownloadHandlerBuffer(); + + var operation = unityWebRequest.SendWebRequest(); + + // Wait for the download to complete or the request to timeout. + while (!operation.isDone) { } + +#if UNITY_2020_1_OR_NEWER + if (unityWebRequest.result != UnityWebRequest.Result.Success) +#else + if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) +#endif + { + MaxSdkLogger.UserError("Failed to retrieve API Key for SDK Key: " + sdkKey + "with error: " + unityWebRequest.error); + return new AppLovinQualityServiceData(); + } + + try + { + return JsonUtility.FromJson(unityWebRequest.downloadHandler.text); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Failed to parse API Key." + exception); + return new AppLovinQualityServiceData(); + } + } + } + + private static List RemoveLegacySafeDkPlugin(List lines) + { + return RemovePlugin(lines, SafeDkLegacyPlugin, SafeDkLegacyMavenRepo, SafeDkLegacyDependencyClassPath, TokenSafeDkLegacyApplyPlugin); + } + + private static List RemoveAppLovinQualityServicePlugin(List lines) + { + return RemovePlugin(lines, QualityServicePlugin, QualityServiceMavenRepo, QualityServiceDependencyClassPath, TokenAppLovinPlugin); + } + + private static List RemovePlugin(List lines, string pluginLine, string mavenRepo, string dependencyClassPath, Regex applyPluginToken) + { + var sanitizedLines = new List(); + var legacyRepoRemoved = false; + var legacyDependencyClassPathRemoved = false; + var legacyPluginRemoved = false; + var legacyPluginMatched = false; + var insideLegacySafeDkClosure = false; + foreach (var line in lines) + { + if (!legacyPluginMatched && line.Contains(pluginLine)) + { + legacyPluginMatched = true; + insideLegacySafeDkClosure = true; + } + + if (insideLegacySafeDkClosure && line.Contains("}")) + { + insideLegacySafeDkClosure = false; + continue; + } + + if (insideLegacySafeDkClosure) + { + continue; + } + + if (!legacyRepoRemoved && line.Contains(mavenRepo)) + { + legacyRepoRemoved = true; + continue; + } + + if (!legacyDependencyClassPathRemoved && line.Contains(dependencyClassPath)) + { + legacyDependencyClassPathRemoved = true; + continue; + } + + if (!legacyPluginRemoved && applyPluginToken.IsMatch(line)) + { + legacyPluginRemoved = true; + continue; + } + + sanitizedLines.Add(line); + } + + return sanitizedLines; + } + + private static List GenerateUpdatedBuildFileLines(List lines, string apiKey, bool addBuildScriptLines) + { + var addPlugin = !string.IsNullOrEmpty(apiKey); + // A sample of the template file. + // ... + // allprojects { + // repositories {**ARTIFACTORYREPOSITORY** + // google() + // jcenter() + // flatDir { + // dirs 'libs' + // } + // } + // } + // + // apply plugin: 'com.android.application' + // **APPLY_PLUGINS** + // + // dependencies { + // implementation fileTree(dir: 'libs', include: ['*.jar']) + // **DEPS**} + // ... + var outputLines = new List(); + // Check if the plugin exists, if so, update the SDK Key. + var pluginExists = lines.Any(line => TokenAppLovinPlugin.IsMatch(line)); + if (pluginExists) + { + var pluginMatched = false; + var insideAppLovinClosure = false; + var updatedApiKey = false; + var mavenRepoUpdated = false; + var dependencyClassPathUpdated = false; + foreach (var line in lines) + { + // Bintray maven repo is no longer being used. Update to s3 maven repo with regex check + if (!mavenRepoUpdated && (line.Contains(QualityServiceBintrayMavenRepo) || line.Contains(QualityServiceNoRegexMavenRepo))) + { + outputLines.Add(GetFormattedBuildScriptLine(QualityServiceMavenRepo)); + mavenRepoUpdated = true; + continue; + } + + // We no longer use version specific dependency class path. Just use + for version to always pull the latest. + if (!dependencyClassPathUpdated && line.Contains(QualityServiceDependencyClassPathV3)) + { + outputLines.Add(GetFormattedBuildScriptLine(QualityServiceDependencyClassPath)); + dependencyClassPathUpdated = true; + continue; + } + + if (!pluginMatched && line.Contains(QualityServicePlugin)) + { + insideAppLovinClosure = true; + pluginMatched = true; + } + + if (insideAppLovinClosure && line.Contains("}")) + { + insideAppLovinClosure = false; + } + + // Update the API key. + if (insideAppLovinClosure && !updatedApiKey && TokenApiKey.IsMatch(line)) + { + outputLines.Add(string.Format(QualityServiceApiKey, apiKey)); + updatedApiKey = true; + } + // Keep adding the line until we find and update the plugin. + else + { + outputLines.Add(line); + } + } + } + // Plugin hasn't been added yet, add it. + else + { + var buildScriptClosureDepth = 0; + var insideBuildScriptClosure = false; + var buildScriptMatched = false; + var qualityServiceRepositoryAdded = false; + var qualityServiceDependencyClassPathAdded = false; + var qualityServicePluginAdded = false; + foreach (var line in lines) + { + // Add the line to the output lines. + outputLines.Add(line); + + // Check if we need to add the build script lines and add them. + if (addBuildScriptLines) + { + if (!buildScriptMatched && line.Contains(BuildScriptMatcher)) + { + buildScriptMatched = true; + insideBuildScriptClosure = true; + } + + // Match the parenthesis to track if we are still inside the buildscript closure. + if (insideBuildScriptClosure) + { + if (line.Contains("{")) + { + buildScriptClosureDepth++; + } + + if (line.Contains("}")) + { + buildScriptClosureDepth--; + } + + if (buildScriptClosureDepth == 0) + { + insideBuildScriptClosure = false; + + // There may be multiple buildscript closures and we need to keep looking until we added both the repository and classpath. + buildScriptMatched = qualityServiceRepositoryAdded && qualityServiceDependencyClassPathAdded; + } + } + + if (insideBuildScriptClosure) + { + // Add the build script dependency repositories. + if (!qualityServiceRepositoryAdded && TokenBuildScriptRepositories.IsMatch(line)) + { + outputLines.Add(GetFormattedBuildScriptLine(QualityServiceMavenRepo)); + qualityServiceRepositoryAdded = true; + } + // Add the build script dependencies. + else if (!qualityServiceDependencyClassPathAdded && TokenBuildScriptDependencies.IsMatch(line)) + { + outputLines.Add(GetFormattedBuildScriptLine(QualityServiceDependencyClassPath)); + qualityServiceDependencyClassPathAdded = true; + } + } + } + + // Check if we need to add the plugin and add it. + if (addPlugin) + { + // Add the plugin. + if (!qualityServicePluginAdded && TokenApplicationPlugin.IsMatch(line)) + { + outputLines.Add(QualityServiceApplyPlugin); + outputLines.AddRange(GenerateAppLovinPluginClosure(apiKey)); + qualityServicePluginAdded = true; + } + } + } + + if ((addBuildScriptLines && (!qualityServiceRepositoryAdded || !qualityServiceDependencyClassPathAdded)) || (addPlugin && !qualityServicePluginAdded)) + { + return null; + } + } + + return outputLines; + } + + public static string GetFormattedBuildScriptLine(string buildScriptLine) + { +#if UNITY_2022_2_OR_NEWER + return " " +#elif UNITY_2019_3_OR_NEWER + return " " +#else + return " " +#endif + + buildScriptLine; + } + + private static IEnumerable GenerateAppLovinPluginClosure(string apiKey) + { + // applovin { + // // NOTE: DO NOT CHANGE - this is NOT your AppLovin MAX SDK key - this is a derived key. + // apiKey "456...a1b" + // } + var linesToInject = new List(5); + linesToInject.Add(""); + linesToInject.Add("applovin {"); + linesToInject.Add(" // NOTE: DO NOT CHANGE - this is NOT your AppLovin MAX SDK key - this is a derived key."); + linesToInject.Add(string.Format(QualityServiceApiKey, apiKey)); + linesToInject.Add("}"); + + return linesToInject; + } + } +} + +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs.meta new file mode 100644 index 0000000..5e49844 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 732b7510bc9c94aafb3fd3b8c0dc5d2d +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinProcessGradleBuildFile.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs new file mode 100644 index 0000000..4ce66cf --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs @@ -0,0 +1,181 @@ +// +// AppLovinSettings.cs +// AppLovin MAX Unity Plugin +// +// Created by Santosh Bagadi on 1/27/20. +// Copyright © 2019 AppLovin. All rights reserved. +// + +using AppLovinMax.Scripts.IntegrationManager.Editor; +using System.IO; +using UnityEditor; +using UnityEngine; +using UnityEngine.Serialization; + +/// +/// A representing the AppLovin Settings that can be set in the Integration Manager Window. +/// +/// The scriptable object asset is created with the name AppLovinSettings.asset and is placed under the directory Assets/MaxSdk/Resources. +/// +/// NOTE: Not name spacing this class since it is reflected upon by the Google adapter and will break compatibility. +/// +public class AppLovinSettings : ScriptableObject +{ + public const string SettingsExportPath = "MaxSdk/Resources/AppLovinSettings.asset"; + + private static AppLovinSettings instance; + + [SerializeField] private bool qualityServiceEnabled = true; + [SerializeField] private string sdkKey; + + [SerializeField] private bool setAttributionReportEndpoint; + [SerializeField] private bool addApsSkAdNetworkIds; + + [SerializeField] private string customGradleVersionUrl; + [SerializeField] private string customGradleToolsVersion; + + [SerializeField] private string adMobAndroidAppId = string.Empty; + [SerializeField] private string adMobIosAppId = string.Empty; + + /// + /// An instance of AppLovin Setting. + /// + public static AppLovinSettings Instance + { + get + { + if (instance == null) + { + // Check for an existing AppLovinSettings somewhere in the project + var guids = AssetDatabase.FindAssets("AppLovinSettings t:ScriptableObject"); + if (guids.Length > 1) + { + MaxSdkLogger.UserWarning("Multiple AppLovinSettings found. This may cause unexpected results."); + } + + if (guids.Length != 0) + { + var path = AssetDatabase.GUIDToAssetPath(guids[0]); + instance = AssetDatabase.LoadAssetAtPath(path); + return instance; + } + + // If there is no existing AppLovinSettings asset, create one in the default location + string settingsFilePath; + // The settings file should be under the Assets/ folder so that it can be version controlled and cannot be overriden when updating. + // If the plugin is outside the Assets folder, create the settings asset at the default location. + if (AppLovinIntegrationManager.IsPluginInPackageManager) + { + // Note: Can't use absolute path when calling `CreateAsset`. Should use relative path to Assets/ directory. + settingsFilePath = Path.Combine("Assets", SettingsExportPath); + + var maxSdkDir = Path.Combine(Application.dataPath, "MaxSdk"); + if (!Directory.Exists(maxSdkDir)) + { + Directory.CreateDirectory(maxSdkDir); + } + } + else + { + settingsFilePath = Path.Combine(AppLovinIntegrationManager.PluginParentDirectory, SettingsExportPath); + } + + var settingsDir = Path.GetDirectoryName(settingsFilePath); + if (!Directory.Exists(settingsDir)) + { + Directory.CreateDirectory(settingsDir); + } + + // On script reload AssetDatabase.FindAssets() can fail and will overwrite AppLovinSettings without this check + if (!File.Exists(settingsFilePath)) + { + instance = CreateInstance(); + AssetDatabase.CreateAsset(instance, settingsFilePath); + MaxSdkLogger.D("Creating new AppLovinSettings asset at path: " + settingsFilePath); + } + } + + return instance; + } + } + + /// + /// Whether or not to install Quality Service plugin. + /// + public bool QualityServiceEnabled + { + get { return Instance.qualityServiceEnabled; } + set { Instance.qualityServiceEnabled = value; } + } + + /// + /// AppLovin SDK Key. + /// + public string SdkKey + { + get { return Instance.sdkKey; } + set { Instance.sdkKey = value; } + } + + /// + /// Whether or not to set `NSAdvertisingAttributionReportEndpoint` in Info.plist. + /// + public bool SetAttributionReportEndpoint + { + get { return Instance.setAttributionReportEndpoint; } + set { Instance.setAttributionReportEndpoint = value; } + } + + /// + /// Whether or not to add Amazon Publisher Services SKAdNetworkID's. + /// + public bool AddApsSkAdNetworkIds + { + get { return Instance.addApsSkAdNetworkIds; } + set { Instance.addApsSkAdNetworkIds = value; } + } + + /// + /// A URL to set the distributionUrl in the gradle-wrapper.properties file (ex: https\://services.gradle.org/distributions/gradle-6.9.3-bin.zip) + /// + public string CustomGradleVersionUrl + { + get { return Instance.customGradleVersionUrl; } + set { Instance.customGradleVersionUrl = value; } + } + + /// + /// A string to set the custom gradle tools version (ex: com.android.tools.build:gradle:4.2.0) + /// + public string CustomGradleToolsVersion + { + get { return Instance.customGradleToolsVersion; } + set { Instance.customGradleToolsVersion = value; } + } + + /// + /// AdMob Android App ID. + /// + public string AdMobAndroidAppId + { + get { return Instance.adMobAndroidAppId; } + set { Instance.adMobAndroidAppId = value; } + } + + /// + /// AdMob iOS App ID. + /// + public string AdMobIosAppId + { + get { return Instance.adMobIosAppId; } + set { Instance.adMobIosAppId = value; } + } + + /// + /// Saves the instance of the settings. + /// + public void SaveAsync() + { + EditorUtility.SetDirty(instance); + } +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs.meta new file mode 100644 index 0000000..7e40d73 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: ebc0ba1b5ef6b4a6b9dd53d7eadfea16 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinSettings.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs new file mode 100644 index 0000000..38aab79 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs @@ -0,0 +1,192 @@ +#if UNITY_2019_2_OR_NEWER +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using AppLovinMax.ThirdParty.MiniJson; + +namespace AppLovinMax.Scripts.IntegrationManager.Editor +{ + public class AppLovinUpmManifest + { + private const string KeyUrl = "url"; + private const string KeyName = "name"; + private const string KeyScopes = "scopes"; + private const string KeyScopedRegistry = "scopedRegistries"; + + private Dictionary manifest; + + private static string ManifestPath + { + get { return Path.Combine(Directory.GetCurrentDirectory(), "Packages/manifest.json"); } + } + + // Private constructor to enforce the use of the Load() method + private AppLovinUpmManifest() { } + + /// + /// Creates a new instance of AppLovinUpmManifest and loads the manifest.json file. + /// + /// An instance of AppLovinUpmManifest + public static AppLovinUpmManifest Load() + { + return new AppLovinUpmManifest { manifest = GetManifest() }; + } + + /// + /// Adds or updates a scoped registry in the manifest. + /// + /// The name of the registry + /// The url of the registry + /// The scopes of the registry + public void AddOrUpdateRegistry(string name, string url, List scopes) + { + var registry = GetRegistry(name); + if (registry == null) + { + var registries = GetRegistries(); + if (registries == null) return; + + registries.Add(new Dictionary + { + {KeyName, name}, + {KeyUrl, url}, + {KeyScopes, scopes} + }); + + return; + } + + UpdateRegistry(registry, scopes); + } + + /// + /// Saves the manifest by serializing it back to JSON and writing to file. + /// + public void Save() + { + var content = Json.Serialize(manifest, true); + File.WriteAllText(ManifestPath, content); + } + + /// + /// Adds a dependency to the manifest. + /// + /// The name of the package to add + /// The version of the package to add + public void AddPackageDependency(string packageName, string version) + { + var manifestDependencies = GetDependencies(); + manifestDependencies[packageName] = version; + } + + /// + /// Removes a dependency from the manifest. + /// + /// The name of the package to remove + public void RemovePackageDependency(string packageName) + { + var manifestDependencies = GetDependencies(); + manifestDependencies.Remove(packageName); + } + + #region Utility + + /// + /// Returns the manifest.json file as a dictionary. + /// + private static Dictionary GetManifest() + { + if (!File.Exists(ManifestPath)) + { + throw new Exception("Manifest not Found!"); + } + + var manifestJson = File.ReadAllText(ManifestPath); + if (string.IsNullOrEmpty(manifestJson)) + { + throw new Exception("Manifest is empty!"); + } + + var deserializedManifest = Json.Deserialize(manifestJson) as Dictionary; + if (deserializedManifest == null) + { + throw new Exception("Failed to deserialize manifest"); + } + + return deserializedManifest; + } + + /// + /// Gets the manifest's dependencies section. + /// + /// The dependencies section of the manifest. + private Dictionary GetDependencies() + { + var dependencies = manifest["dependencies"] as Dictionary; + if (dependencies == null) + { + throw new Exception("No dependencies found in manifest."); + } + + return dependencies; + } + + /// + /// Gets the manifest's registries section. Creates a new registries section if one does not exist. + /// + /// The registries section of the manifest. + private List GetRegistries() + { + EnsureScopedRegistryExists(); + return manifest[KeyScopedRegistry] as List; + } + + /// + /// Gets a scoped registry with the given name. + /// + /// The name of the registry + /// Returns the registry, or null if it can't be found + private Dictionary GetRegistry(string name) + { + var registries = GetRegistries(); + if (registries == null) return null; + + return registries + .OfType>() + .FirstOrDefault(registry => MaxSdkUtils.GetStringFromDictionary(registry, KeyName).Equals(name)); + } + + /// + /// Creates the section for scoped registries in the manifest.json file if it doesn't exist. + /// + private void EnsureScopedRegistryExists() + { + if (manifest.ContainsKey(KeyScopedRegistry)) return; + + manifest.Add(KeyScopedRegistry, new List()); + } + + /// + /// Updates a registry to make sure it contains the new scopes. + /// + /// The registry to update + /// The scopes we want added to the registry + private static void UpdateRegistry(Dictionary registry, List newScopes) + { + var scopes = MaxSdkUtils.GetListFromDictionary(registry, KeyScopes); + if (scopes == null) + { + registry[KeyScopes] = new List(newScopes); + return; + } + + // Only add scopes that are not already in the list + var uniqueNewScopes = newScopes.Where(scope => !scopes.Contains(scope)).ToList(); + scopes.AddRange(uniqueNewScopes); + } + + #endregion + } +} +#endif diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs.meta new file mode 100644 index 0000000..3970bba --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs.meta @@ -0,0 +1,15 @@ +fileFormatVersion: 2 +guid: 40e2ad4a252104688b8627f82e806b2e +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/AppLovinUpmManifest.cs +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/AppLovinUpmManifest.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef new file mode 100644 index 0000000..1cc80b7 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef @@ -0,0 +1,10 @@ +{ + "name": "MaxSdk.Scripts.IntegrationManager.Editor", + "references": [ + "MaxSdk.Scripts" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef.meta b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef.meta new file mode 100644 index 0000000..272b872 --- /dev/null +++ b/Assets/MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef.meta @@ -0,0 +1,6 @@ +fileFormatVersion: 2 +guid: a10a05a8449c42519fd80f2b8b580de3 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/IntegrationManager/Editor/MaxSdk.IntegrationManager.Editor.asmdef +timeCreated: 1591749873 diff --git a/Assets/MaxSdk/Scripts/MaxCmpService.cs b/Assets/MaxSdk/Scripts/MaxCmpService.cs new file mode 100644 index 0000000..c142439 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxCmpService.cs @@ -0,0 +1,170 @@ +// +// MaxCmpService.cs +// AppLovin User Engagement Unity Plugin +// +// Created by Santosh Bagadi on 10/1/23. +// Copyright © 2023 AppLovin. All rights reserved. +// + +using System; +using System.Collections.Generic; + +#if UNITY_EDITOR +#elif UNITY_ANDROID +using UnityEngine; +#elif UNITY_IOS +using System.Runtime.InteropServices; +#endif + +/// +/// This class provides direct APIs for interfacing with the Google-certified CMP installed, if any. +/// +public class MaxCmpService +{ + private static readonly MaxCmpService _instance = new MaxCmpService(); + + private MaxCmpService() { } + + private static Action OnCompletedAction; + +#if UNITY_EDITOR +#elif UNITY_ANDROID + private static readonly AndroidJavaClass MaxUnityPluginClass = new AndroidJavaClass("com.applovin.mediation.unity.MaxUnityPlugin"); +#elif UNITY_IOS + [DllImport("__Internal")] + private static extern void _MaxShowCmpForExistingUser(); + + [DllImport("__Internal")] + private static extern bool _MaxHasSupportedCmp(); +#endif + + internal static MaxCmpService Instance + { + get { return _instance; } + } + + /// + /// Shows the CMP flow to an existing user. + /// Note that the user's current consent will be reset before the CMP alert is shown. + /// + /// Called when the CMP flow finishes showing. + public void ShowCmpForExistingUser(Action onCompletedAction) + { + OnCompletedAction = onCompletedAction; + +#if UNITY_EDITOR + var errorProps = new Dictionary + { + {"code", (int) MaxCmpError.ErrorCode.FormUnavailable}, + {"message", "CMP is not supported in Unity editor"} + }; + + NotifyCompletedIfNeeded(errorProps); +#elif UNITY_ANDROID + MaxUnityPluginClass.CallStatic("showCmpForExistingUser"); +#elif UNITY_IOS + _MaxShowCmpForExistingUser(); +#endif + } + + /// + /// Returns true if a supported CMP SDK is detected. + /// + public bool HasSupportedCmp + { + get + { +#if UNITY_EDITOR + return false; +#elif UNITY_ANDROID + return MaxUnityPluginClass.CallStatic("hasSupportedCmp"); +#elif UNITY_IOS + return _MaxHasSupportedCmp(); +#else + return false; +#endif + } + } + + internal static void NotifyCompletedIfNeeded(Dictionary errorProps) + { + if (OnCompletedAction == null) return; + + var error = (errorProps == null) ? null : MaxCmpError.Create(errorProps); + OnCompletedAction(error); + } +} + +public class MaxCmpError +{ + public enum ErrorCode + { + /// + /// Indicates that an unspecified error has occurred. + /// + Unspecified = -1, + + /// + /// Indicates that the CMP has not been integrated correctly. + /// + IntegrationError = 1, + + /// + /// Indicates that the CMP form is unavailable. + /// + FormUnavailable = 2, + + /// + /// Indicates that the CMP form is not required. + /// + FormNotRequired = 3 + } + + public static MaxCmpError Create(IDictionary error) + { + return new MaxCmpError() + { + Code = GetCode(MaxSdkUtils.GetIntFromDictionary(error, "code")), + Message = MaxSdkUtils.GetStringFromDictionary(error, "message"), + CmpCode = MaxSdkUtils.GetIntFromDictionary(error, "cmpCode", -1), + CmpMessage = MaxSdkUtils.GetStringFromDictionary(error, "cmpMessage") + }; + } + + private static ErrorCode GetCode(int code) + { + switch (code) + { + case 1: + return ErrorCode.IntegrationError; + case 2: + return ErrorCode.FormUnavailable; + case 3: + return ErrorCode.FormNotRequired; + default: + return ErrorCode.Unspecified; + } + } + + private MaxCmpError() { } + + /// + /// The error code for this error. + /// + public ErrorCode Code { get; private set; } + + /// + /// The error message for this error. + /// + public string Message { get; private set; } + + /// + /// The error code returned by the CMP. + /// + public int CmpCode { get; private set; } + + /// + /// The error message returned by the CMP. + /// + public string CmpMessage { get; private set; } +} diff --git a/Assets/MaxSdk/Scripts/MaxCmpService.cs.meta b/Assets/MaxSdk/Scripts/MaxCmpService.cs.meta new file mode 100644 index 0000000..598fc90 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxCmpService.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: f2e895983b04846af81b59189de0310c +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxCmpService.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxEventExecutor.cs b/Assets/MaxSdk/Scripts/MaxEventExecutor.cs new file mode 100644 index 0000000..6b893ad --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEventExecutor.cs @@ -0,0 +1,108 @@ +// +// MaxEventExecutor.cs +// Max Unity Plugin +// +// Created by Jonathan Liu on 1/22/2024. +// Copyright © 2024 AppLovin. All rights reserved. +// + +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Events; + +namespace AppLovinMax.Internal +{ + public class MaxEventExecutor : MonoBehaviour + { + private static MaxEventExecutor instance; + private static List adEventsQueue = new List(); + + private static volatile bool adEventsQueueEmpty = true; + + struct MaxAction + { + public Action action; + public string eventName; + + public MaxAction(Action actionToExecute, string nameOfEvent) + { + action = actionToExecute; + eventName = nameOfEvent; + } + } + + public static void InitializeIfNeeded() + { + if (instance != null) return; + + var executor = new GameObject("MaxEventExecutor"); + executor.hideFlags = HideFlags.HideAndDontSave; + DontDestroyOnLoad(executor); + instance = executor.AddComponent(); + } + + #region Public API + +#if UNITY_EDITOR || !(UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS) + public static MaxEventExecutor Instance + { + get + { + InitializeIfNeeded(); + return instance; + } + } +#endif + + public static void ExecuteOnMainThread(Action action, string eventName) + { + lock (adEventsQueue) + { + adEventsQueue.Add(new MaxAction(action, eventName)); + adEventsQueueEmpty = false; + } + } + + public static void InvokeOnMainThread(UnityEvent unityEvent, string eventName) + { + ExecuteOnMainThread(() => unityEvent.Invoke(), eventName); + } + + #endregion + + public void Update() + { + if (adEventsQueueEmpty) return; + + var actionsToExecute = new List(); + lock (adEventsQueue) + { + actionsToExecute.AddRange(adEventsQueue); + adEventsQueue.Clear(); + adEventsQueueEmpty = true; + } + + foreach (var maxAction in actionsToExecute) + { + if (maxAction.action.Target != null) + { + try + { + maxAction.action.Invoke(); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Caught exception in publisher event: " + maxAction.eventName + ", exception: " + exception); + MaxSdkLogger.LogException(exception); + } + } + } + } + + public void Disable() + { + instance = null; + } + } +} diff --git a/Assets/MaxSdk/Scripts/MaxEventExecutor.cs.meta b/Assets/MaxSdk/Scripts/MaxEventExecutor.cs.meta new file mode 100644 index 0000000..18ba126 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEventExecutor.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 4715dd62632564dc4810a4dc98243f4a +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxEventExecutor.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs b/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs new file mode 100644 index 0000000..19a082f --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs @@ -0,0 +1,37 @@ +// +// EventSystemChecker.cs +// AppLovin MAX Unity Plugin +// +// Created by Jonathan Liu on 10/23/2022. +// Copyright © 2022 AppLovin. All rights reserved. +// + +#if UNITY_EDITOR +using UnityEngine; +using UnityEngine.EventSystems; + +namespace AppLovinMax.Scripts +{ + /// + /// A script to check and enable event system as needed for the AppLovin MAX ad prefabs. + /// + [RequireComponent(typeof(EventSystem))] + public class MaxEventSystemChecker : MonoBehaviour + { + private void Awake() + { + // Enable the EventSystem if there is no other EventSystem in the scene + var eventSystem = GetComponent(); + var currentSystem = UnityEngine.EventSystems.EventSystem.current; + if (currentSystem == null || currentSystem == eventSystem) + { + eventSystem.enabled = true; + } + else + { + eventSystem.enabled = false; + } + } + } +} +#endif diff --git a/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs.meta b/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs.meta new file mode 100644 index 0000000..12874b6 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEventSystemChecker.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: e0acf281ba86b4929a6942ecd998395b +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxEventSystemChecker.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxEvents.cs b/Assets/MaxSdk/Scripts/MaxEvents.cs new file mode 100644 index 0000000..b0a9ad6 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEvents.cs @@ -0,0 +1,21 @@ +/** + * Class containing pre-defined constants to use with AppLovin event tracking APIs. + */ +public static class MaxEvents +{ + /** + * Nested class representing pre-defined AppLovin events to be fired with AppLovin event tracking APIs. + */ + public class AppLovin + { + public const string UserLoggedIn = "login"; + public const string UserCreatedAccount = "registration"; + public const string UserCompletedTutorial = "tutorial"; + public const string UserCompletedLevel = "level"; + public const string UserCompletedAchievement = "achievement"; + public const string UserSpentVirtualCurrency = "vcpurchase"; + public const string UserCompletedInAppPurchase = "iap"; + public const string UserSentInvitation = "invite"; + public const string UserSharedLink = "share"; + } +} \ No newline at end of file diff --git a/Assets/MaxSdk/Scripts/MaxEvents.cs.meta b/Assets/MaxSdk/Scripts/MaxEvents.cs.meta new file mode 100644 index 0000000..bfb6ad5 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxEvents.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 67ec2f620c6b0405ba16ea2c032dc9a2 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxEvents.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef b/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef new file mode 100644 index 0000000..99e1d22 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef @@ -0,0 +1,6 @@ + { + "name": "MaxSdk.Scripts", + "references": [], + "includePlatforms": [], + "excludePlatforms": [] +} diff --git a/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef.meta b/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef.meta new file mode 100644 index 0000000..b55da72 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdk.Scripts.asmdef.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: a4cfc1a18fa3a469b96d885db522f42e +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdk.Scripts.asmdef +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdk.cs b/Assets/MaxSdk/Scripts/MaxSdk.cs new file mode 100644 index 0000000..ce3745e --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdk.cs @@ -0,0 +1,30 @@ +/** + * AppLovin MAX Unity Plugin C# Wrapper + */ + +using UnityEngine; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +public class MaxSdk : +#if UNITY_EDITOR + // Check for Unity Editor first since the editor also responds to the currently selected platform. + MaxSdkUnityEditor +#elif UNITY_ANDROID + MaxSdkAndroid +#elif UNITY_IPHONE || UNITY_IOS + MaxSdkiOS +#else + MaxSdkUnityEditor +#endif +{ + private const string _version = "8.0.1"; + + /// + /// Returns the current plugin version. + /// + public static string Version + { + get { return _version; } + } +} diff --git a/Assets/MaxSdk/Scripts/MaxSdk.cs.meta b/Assets/MaxSdk/Scripts/MaxSdk.cs.meta new file mode 100644 index 0000000..c1c32f4 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdk.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 2fc7aa576843c44e68c7ab14b475bb82 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdk.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs b/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs new file mode 100644 index 0000000..8a87832 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs @@ -0,0 +1,1065 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using AppLovinMax.ThirdParty.MiniJson; + +/// +/// Android AppLovin MAX Unity Plugin implementation +/// +public class MaxSdkAndroid : MaxSdkBase +{ + private static readonly AndroidJavaClass MaxUnityPluginClass = + new AndroidJavaClass("com.applovin.mediation.unity.MaxUnityPlugin"); + + private static BackgroundCallbackProxy BackgroundCallback = new BackgroundCallbackProxy(); + + static MaxSdkAndroid() + { + InitializeEventExecutor(); + + MaxUnityPluginClass.CallStatic("setBackgroundCallback", BackgroundCallback); + } + + #region Initialization + + /// + /// Initialize the default instance of AppLovin SDK. + /// + /// Please make sure that application's Android manifest or Info.plist includes the AppLovin SDK key. + /// + /// OPTIONAL: Set the MAX ad unit ids to be used for this instance of the SDK. 3rd-party SDKs will be initialized with the credentials configured for these ad unit ids. + /// This should only be used if you have different sets of ad unit ids / credentials for the same package name. + /// + public static void InitializeSdk(string[] adUnitIds = null) + { + var serializedAdUnitIds = (adUnitIds != null) ? string.Join(",", adUnitIds) : ""; + MaxUnityPluginClass.CallStatic("initializeSdk", serializedAdUnitIds, GenerateMetaData()); + } + + /// + /// Check if the SDK has been initialized + /// + /// True if SDK has been initialized + public static bool IsInitialized() + { + return MaxUnityPluginClass.CallStatic("isInitialized"); + } + + #endregion + + #region User Info + + /// + /// Set an identifier for the current user. This identifier will be tied to SDK events and our optional S2S postbacks. + /// + /// If you're using reward validation, you can optionally set an identifier to be included with currency validation postbacks. + /// For example, a username or email. We'll include this in the postback when we ping your currency endpoint from our server. + /// + /// + /// The user identifier to be set. Must not be null. + public static void SetUserId(string userId) + { + MaxUnityPluginClass.CallStatic("setUserId", userId); + } + + /// + /// Set the . + /// + /// The segment collection to be set. Must not be {@code null} + public static void SetSegmentCollection(MaxSegmentCollection segmentCollection) + { + MaxUnityPluginClass.CallStatic("setSegmentCollection", JsonUtility.ToJson(segmentCollection)); + } + + #endregion + + #region MAX + + /// + /// Returns the list of available mediation networks. + /// + /// Please call this method after the SDK has initialized. + /// + public static List GetAvailableMediatedNetworks() + { + var serializedNetworks = MaxUnityPluginClass.CallStatic("getAvailableMediatedNetworks"); + return MaxSdkUtils.PropsStringsToList(serializedNetworks); + } + + /// + /// Present the mediation debugger UI. + /// This debugger tool provides the status of your integration for each third-party ad network. + /// + /// Please call this method after the SDK has initialized. + /// + public static void ShowMediationDebugger() + { + MaxUnityPluginClass.CallStatic("showMediationDebugger"); + } + + /// + /// Present the creative debugger UI. + /// This debugger tool provides information for recently displayed ads. + /// + /// Please call this method after the SDK has initialized. + /// + public static void ShowCreativeDebugger() + { + MaxUnityPluginClass.CallStatic("showCreativeDebugger"); + } + + /// + /// Returns the arbitrary ad value for a given ad unit identifier with key. Returns null if no ad is loaded. + /// + /// Ad unit identifier for which to get the ad value for. Must not be null. + /// Ad value key. Must not be null. + /// Arbitrary ad value for a given key, or null if no ad is loaded. + public static string GetAdValue(string adUnitIdentifier, string key) + { + var value = MaxUnityPluginClass.CallStatic("getAdValue", adUnitIdentifier, key); + + if (string.IsNullOrEmpty(value)) return null; + + return value; + } + + #endregion + + #region Privacy + + /// + /// Get the SDK configuration for this user. + /// + /// Note: This method should be called only after SDK has been initialized. + /// + public static SdkConfiguration GetSdkConfiguration() + { + var sdkConfigurationStr = MaxUnityPluginClass.CallStatic("getSdkConfiguration"); + var sdkConfigurationDict = Json.Deserialize(sdkConfigurationStr) as Dictionary; + return SdkConfiguration.Create(sdkConfigurationDict); + } + + /// + /// Set whether or not user has provided consent for information sharing with AppLovin and other providers. + /// + /// true if the user has provided consent for information sharing with AppLovin. false by default. + public static void SetHasUserConsent(bool hasUserConsent) + { + MaxUnityPluginClass.CallStatic("setHasUserConsent", hasUserConsent); + } + + /// + /// Check if user has provided consent for information sharing with AppLovin and other providers. + /// + /// true if user has provided consent for information sharing. false if the user declined to share information or the consent value has not been set . + public static bool HasUserConsent() + { + return MaxUnityPluginClass.CallStatic("hasUserConsent"); + } + + /// + /// Check if user has set consent for information sharing. + /// + /// true if user has set a value of consent for information sharing. + public static bool IsUserConsentSet() + { + return MaxUnityPluginClass.CallStatic("isUserConsentSet"); + } + + /// + /// Set whether or not user has opted out of the sale of their personal information. + /// + /// true if the user has opted out of the sale of their personal information. + public static void SetDoNotSell(bool doNotSell) + { + MaxUnityPluginClass.CallStatic("setDoNotSell", doNotSell); + } + + /// + /// Check if the user has opted out of the sale of their personal information. + /// + /// true if the user has opted out of the sale of their personal information. false if the user opted in to the sell of their personal information or the value has not been set . + public static bool IsDoNotSell() + { + return MaxUnityPluginClass.CallStatic("isDoNotSell"); + } + + /// + /// Check if the user has set the option to sell their personal information. + /// + /// true if user has chosen an option to sell their personal information. + public static bool IsDoNotSellSet() + { + return MaxUnityPluginClass.CallStatic("isDoNotSellSet"); + } + + #endregion + + #region Banners + + /// + /// Create a new banner. + /// + /// Ad unit identifier of the banner to create. Must not be null. + /// Banner position. Must not be null. + public static void CreateBanner(string adUnitIdentifier, BannerPosition bannerPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create banner"); + MaxUnityPluginClass.CallStatic("createBanner", adUnitIdentifier, bannerPosition.ToSnakeCaseString()); + } + + /// + /// Create a new banner with a custom position. + /// + /// Ad unit identifier of the banner to create. Must not be null. + /// The X coordinate (horizontal position) of the banner relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the banner relative to the top left corner of the screen. + /// + /// The banner is placed within the safe area of the screen. You can use this to get the absolute position of the banner on screen. + /// + public static void CreateBanner(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create banner"); + MaxUnityPluginClass.CallStatic("createBanner", adUnitIdentifier, x, y); + } + + /// + /// Load a new banner ad. + /// NOTE: The method loads the first banner ad and initiates an automated banner refresh process. + /// You only need to call this method if you pause banner refresh. + /// + /// Ad unit identifier of the banner to load. Must not be null. + public static void LoadBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load banner"); + MaxUnityPluginClass.CallStatic("loadBanner", adUnitIdentifier); + } + + /// + /// Set the banner placement for an ad unit identifier to tie the future ad events to. + /// + /// Ad unit identifier of the banner to set the placement for. Must not be null. + /// Placement to set + public static void SetBannerPlacement(string adUnitIdentifier, string placement) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner placement"); + MaxUnityPluginClass.CallStatic("setBannerPlacement", adUnitIdentifier, placement); + } + + /// + /// Starts or resumes auto-refreshing of the banner for the given ad unit identifier. + /// + /// Ad unit identifier of the banner for which to start auto-refresh. Must not be null. + public static void StartBannerAutoRefresh(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "start banner auto-refresh"); + MaxUnityPluginClass.CallStatic("startBannerAutoRefresh", adUnitIdentifier); + } + + /// + /// Pauses auto-refreshing of the banner for the given ad unit identifier. + /// + /// Ad unit identifier of the banner for which to stop auto-refresh. Must not be null. + public static void StopBannerAutoRefresh(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "stop banner auto-refresh"); + MaxUnityPluginClass.CallStatic("stopBannerAutoRefresh", adUnitIdentifier); + } + + /// + /// Updates the position of the banner to the new position provided. + /// + /// The ad unit identifier of the banner for which to update the position. Must not be null. + /// A new position for the banner. Must not be null. + public static void UpdateBannerPosition(string adUnitIdentifier, BannerPosition bannerPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "update banner position"); + MaxUnityPluginClass.CallStatic("updateBannerPosition", adUnitIdentifier, bannerPosition.ToSnakeCaseString()); + } + + /// + /// Updates the position of the banner to the new coordinates provided. + /// + /// The ad unit identifier of the banner for which to update the position. Must not be null. + /// The X coordinate (horizontal position) of the banner relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the banner relative to the top left corner of the screen. + /// + /// The banner is placed within the safe area of the screen. You can use this to get the absolute position of the banner on screen. + /// + public static void UpdateBannerPosition(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "update banner position"); + MaxUnityPluginClass.CallStatic("updateBannerPosition", adUnitIdentifier, x, y); + } + + /// + /// Overrides the width of the banner in dp. + /// + /// The ad unit identifier of the banner for which to override the width for. Must not be null. + /// The desired width of the banner in dp + public static void SetBannerWidth(string adUnitIdentifier, float width) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner width"); + MaxUnityPluginClass.CallStatic("setBannerWidth", adUnitIdentifier, width); + } + + /// + /// Show banner at a position determined by the 'CreateBanner' call. + /// + /// Ad unit identifier of the banner to show. Must not be null. + public static void ShowBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show banner"); + MaxUnityPluginClass.CallStatic("showBanner", adUnitIdentifier); + } + + /// + /// Remove banner from the ad view and destroy it. + /// + /// Ad unit identifier of the banner to destroy. Must not be null. + public static void DestroyBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "destroy banner"); + MaxUnityPluginClass.CallStatic("destroyBanner", adUnitIdentifier); + } + + /// + /// Hide banner. + /// + /// Ad unit identifier of the banner to hide. Must not be null. + public static void HideBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "hide banner"); + MaxUnityPluginClass.CallStatic("hideBanner", adUnitIdentifier); + } + + /// + /// Set non-transparent background color for banners to be fully functional. + /// + /// Ad unit identifier of the banner to set background color for. Must not be null. + /// A background color to set for the ad. Must not be null. + public static void SetBannerBackgroundColor(string adUnitIdentifier, Color color) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set background color"); + MaxUnityPluginClass.CallStatic("setBannerBackgroundColor", adUnitIdentifier, MaxSdkUtils.ParseColor(color)); + } + + /// + /// Set an extra parameter for the banner ad. + /// + /// Ad unit identifier of the banner to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetBannerExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner extra parameter"); + MaxUnityPluginClass.CallStatic("setBannerExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the banner ad. + /// + /// Ad unit identifier of the banner to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetBannerLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setBannerLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setBannerLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + /// + /// The custom data to tie the showing banner ad to, for ILRD and rewarded postbacks via the {CUSTOM_DATA} macro. Maximum size is 8KB. + /// + /// Banner ad unit identifier of the banner to set the custom data for. Must not be null. + /// The custom data to be set. + public static void SetBannerCustomData(string adUnitIdentifier, string customData) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner custom data"); + MaxUnityPluginClass.CallStatic("setBannerCustomData", adUnitIdentifier, customData); + } + + /// + /// The banner position on the screen. When setting the banner position via or , + /// the banner is placed within the safe area of the screen. This returns the absolute position of the banner on screen. + /// + /// Ad unit identifier of the banner for which to get the position on screen. Must not be null. + /// A representing the banner position on screen. + public static Rect GetBannerLayout(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "get banner layout"); + var positionRect = MaxUnityPluginClass.CallStatic("getBannerLayout", adUnitIdentifier); + return GetRectFromString(positionRect); + } + + #endregion + + #region MRECs + + /// + /// Create a new MREC. + /// + /// Ad unit identifier of the MREC to create. Must not be null. + /// MREC position. Must not be null. + public static void CreateMRec(string adUnitIdentifier, AdViewPosition mrecPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create MREC"); + MaxUnityPluginClass.CallStatic("createMRec", adUnitIdentifier, mrecPosition.ToSnakeCaseString()); + } + + /// + /// Create a new MREC with a custom position. + /// + /// Ad unit identifier of the MREC to create. Must not be null. + /// The X coordinate (horizontal position) of the MREC relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the MREC relative to the top left corner of the screen. + /// + /// The MREC is placed within the safe area of the screen. You can use this to get the absolute position Rect of the MREC on screen. + /// + public static void CreateMRec(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create MREC"); + MaxUnityPluginClass.CallStatic("createMRec", adUnitIdentifier, x, y); + } + + /// + /// Load a new MREC ad. + /// NOTE: The method loads the first MREC ad and initiates an automated MREC refresh process. + /// You only need to call this method if you pause MREC refresh. + /// + /// Ad unit identifier of the MREC to load. Must not be null. + public static void LoadMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load MREC"); + MaxUnityPluginClass.CallStatic("loadMRec", adUnitIdentifier); + } + + /// + /// Set the MREC placement for an ad unit identifier to tie the future ad events to. + /// + /// Ad unit identifier of the MREC to set the placement for. Must not be null. + /// Placement to set + public static void SetMRecPlacement(string adUnitIdentifier, string placement) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC placement"); + MaxUnityPluginClass.CallStatic("setMRecPlacement", adUnitIdentifier, placement); + } + + /// + /// Starts or resumes auto-refreshing of the MREC for the given ad unit identifier. + /// + /// Ad unit identifier of the MREC for which to start auto-refresh. Must not be null. + public static void StartMRecAutoRefresh(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "start MREC auto-refresh"); + MaxUnityPluginClass.CallStatic("startMRecAutoRefresh", adUnitIdentifier); + } + + /// + /// Pauses auto-refreshing of the MREC for the given ad unit identifier. + /// + /// Ad unit identifier of the MREC for which to stop auto-refresh. Must not be null. + public static void StopMRecAutoRefresh(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "stop MREC auto-refresh"); + MaxUnityPluginClass.CallStatic("stopMRecAutoRefresh", adUnitIdentifier); + } + + /// + /// Updates the position of the MREC to the new position provided. + /// + /// The ad unit identifier of the MREC for which to update the position. Must not be null. + /// A new position for the MREC. Must not be null. + public static void UpdateMRecPosition(string adUnitIdentifier, AdViewPosition mrecPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "update MREC position"); + MaxUnityPluginClass.CallStatic("updateMRecPosition", adUnitIdentifier, mrecPosition.ToSnakeCaseString()); + } + + /// + /// Updates the position of the MREC to the new coordinates provided. + /// + /// The ad unit identifier of the MREC for which to update the position. Must not be null. + /// The X coordinate (horizontal position) of the MREC relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the MREC relative to the top left corner of the screen. + /// + /// The MREC is placed within the safe area of the screen. You can use this to get the absolute position Rect of the MREC on screen. + /// + public static void UpdateMRecPosition(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "update MREC position"); + MaxUnityPluginClass.CallStatic("updateMRecPosition", adUnitIdentifier, x, y); + } + + /// + /// Show MREC at a position determined by the 'CreateMRec' call. + /// + /// Ad unit identifier of the MREC to show. Must not be null. + public static void ShowMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show MREC"); + MaxUnityPluginClass.CallStatic("showMRec", adUnitIdentifier); + } + + /// + /// Remove MREC from the ad view and destroy it. + /// + /// Ad unit identifier of the MREC to destroy. Must not be null. + public static void DestroyMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "destroy MREC"); + MaxUnityPluginClass.CallStatic("destroyMRec", adUnitIdentifier); + } + + /// + /// Hide MREC. + /// + /// Ad unit identifier of the MREC to hide. Must not be null. + public static void HideMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "hide MREC"); + MaxUnityPluginClass.CallStatic("hideMRec", adUnitIdentifier); + } + + /// + /// Set an extra parameter for the MREC ad. + /// + /// Ad unit identifier of the MREC to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetMRecExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC extra parameter"); + MaxUnityPluginClass.CallStatic("setMRecExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the MREC ad. + /// + /// Ad unit identifier of the MREC to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetMRecLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setMRecLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setMRecLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + /// + /// The custom data to tie the showing MREC ad to, for ILRD and rewarded postbacks via the {CUSTOM_DATA} macro. Maximum size is 8KB. + /// + /// MREC Ad unit identifier of the banner to set the custom data for. Must not be null. + /// The custom data to be set. + public static void SetMRecCustomData(string adUnitIdentifier, string customData) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC custom data"); + MaxUnityPluginClass.CallStatic("setMRecCustomData", adUnitIdentifier, customData); + } + + /// + /// The MREC position on the screen. When setting the banner position via or , + /// the banner is placed within the safe area of the screen. This returns the absolute position of the MREC on screen. + /// + /// Ad unit identifier of the MREC for which to get the position on screen. Must not be null. + /// A representing the banner position on screen. + public static Rect GetMRecLayout(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "get MREC layout"); + var positionRect = MaxUnityPluginClass.CallStatic("getMRecLayout", adUnitIdentifier); + return GetRectFromString(positionRect); + } + + #endregion + + #region Interstitials + + /// + /// Start loading an interstitial. + /// + /// Ad unit identifier of the interstitial to load. Must not be null. + public static void LoadInterstitial(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load interstitial"); + MaxUnityPluginClass.CallStatic("loadInterstitial", adUnitIdentifier); + } + + /// + /// Check if interstitial ad is loaded and ready to be displayed. + /// + /// Ad unit identifier of the interstitial to load. Must not be null. + /// True if the ad is ready to be displayed + public static bool IsInterstitialReady(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "check interstitial loaded"); + return MaxUnityPluginClass.CallStatic("isInterstitialReady", adUnitIdentifier); + } + + /// + /// Present loaded interstitial for a given placement to tie ad events to. Note: if the interstitial is not ready to be displayed nothing will happen. + /// + /// Ad unit identifier of the interstitial to load. Must not be null. + /// The placement to tie the showing ad's events to + /// The custom data to tie the showing ad's events to. Maximum size is 8KB. + public static void ShowInterstitial(string adUnitIdentifier, string placement = null, string customData = null) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show interstitial"); + + if (IsInterstitialReady(adUnitIdentifier)) + { + MaxUnityPluginClass.CallStatic("showInterstitial", adUnitIdentifier, placement, customData); + } + else + { + MaxSdkLogger.UserWarning("Not showing MAX Ads interstitial: ad not ready"); + } + } + + /// + /// Set an extra parameter for the ad. + /// + /// Ad unit identifier of the interstitial to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetInterstitialExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set interstitial extra parameter"); + MaxUnityPluginClass.CallStatic("setInterstitialExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the ad. + /// + /// Ad unit identifier of the interstitial to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetInterstitialLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set interstitial local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setInterstitialLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setInterstitialLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + #endregion + + #region App Open + + /// + /// Start loading an app open ad. + /// + /// Ad unit identifier of the app open ad to load. Must not be null. + public static void LoadAppOpenAd(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load app open ad"); + MaxUnityPluginClass.CallStatic("loadAppOpenAd", adUnitIdentifier); + } + + /// + /// Check if app open ad ad is loaded and ready to be displayed. + /// + /// Ad unit identifier of the app open ad to load. Must not be null. + /// True if the ad is ready to be displayed + public static bool IsAppOpenAdReady(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "check app open ad loaded"); + return MaxUnityPluginClass.CallStatic("isAppOpenAdReady", adUnitIdentifier); + } + + /// + /// Present loaded app open ad for a given placement to tie ad events to. Note: if the app open ad is not ready to be displayed nothing will happen. + /// + /// Ad unit identifier of the app open ad to load. Must not be null. + /// The placement to tie the showing ad's events to + /// The custom data to tie the showing ad's events to. Maximum size is 8KB. + public static void ShowAppOpenAd(string adUnitIdentifier, string placement = null, string customData = null) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show app open ad"); + + if (IsAppOpenAdReady(adUnitIdentifier)) + { + MaxUnityPluginClass.CallStatic("showAppOpenAd", adUnitIdentifier, placement, customData); + } + else + { + MaxSdkLogger.UserWarning("Not showing MAX Ads app open ad: ad not ready"); + } + } + + /// + /// Set an extra parameter for the ad. + /// + /// Ad unit identifier of the app open ad to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetAppOpenAdExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set app open ad extra parameter"); + MaxUnityPluginClass.CallStatic("setAppOpenAdExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the ad. + /// + /// Ad unit identifier of the app open ad to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetAppOpenAdLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set app open ad local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setAppOpenAdLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setAppOpenAdLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + #endregion + + #region Rewarded + + /// + /// Start loading an rewarded ad. + /// + /// Ad unit identifier of the rewarded ad to load. Must not be null. + public static void LoadRewardedAd(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load rewarded ad"); + MaxUnityPluginClass.CallStatic("loadRewardedAd", adUnitIdentifier); + } + + /// + /// Check if rewarded ad ad is loaded and ready to be displayed. + /// + /// Ad unit identifier of the rewarded ad to load. Must not be null. + /// True if the ad is ready to be displayed + public static bool IsRewardedAdReady(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "check rewarded ad loaded"); + return MaxUnityPluginClass.CallStatic("isRewardedAdReady", adUnitIdentifier); + } + + /// ready to be + /// Present loaded rewarded ad for a given placement to tie ad events to. Note: if the rewarded ad is not ready to be displayed nothing will happen. + /// + /// Ad unit identifier of the interstitial to load. Must not be null. + /// The placement to tie the showing ad's events to + /// The custom data to tie the showing ad's events to. Maximum size is 8KB. + public static void ShowRewardedAd(string adUnitIdentifier, string placement = null, string customData = null) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show rewarded ad"); + + if (IsRewardedAdReady(adUnitIdentifier)) + { + MaxUnityPluginClass.CallStatic("showRewardedAd", adUnitIdentifier, placement, customData); + } + else + { + MaxSdkLogger.UserWarning("Not showing MAX Ads rewarded ad: ad not ready"); + } + } + + /// + /// Set an extra parameter for the ad. + /// + /// Ad unit identifier of the rewarded to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetRewardedAdExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set rewarded ad extra parameter"); + MaxUnityPluginClass.CallStatic("setRewardedAdExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the ad. + /// + /// Ad unit identifier of the rewarded to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetRewardedAdLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set rewarded ad local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setRewardedAdLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setRewardedAdLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + #endregion + + #region Rewarded Interstitial + + /// + /// Start loading an rewarded interstitial ad. + /// + /// Ad unit identifier of the rewarded interstitial ad to load. Must not be null. + public static void LoadRewardedInterstitialAd(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load rewarded interstitial ad"); + MaxUnityPluginClass.CallStatic("loadRewardedInterstitialAd", adUnitIdentifier); + } + + /// + /// Check if rewarded interstitial ad ad is loaded and ready to be displayed. + /// + /// Ad unit identifier of the rewarded interstitial ad to load. Must not be null. + /// True if the ad is ready to be displayed + public static bool IsRewardedInterstitialAdReady(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "check rewarded interstitial ad loaded"); + return MaxUnityPluginClass.CallStatic("isRewardedInterstitialAdReady", adUnitIdentifier); + } + + /// + /// Present loaded rewarded interstitial ad for a given placement to tie ad events to. Note: if the rewarded interstitial ad is not ready to be displayed nothing will happen. + /// + /// Ad unit identifier of the rewarded interstitial to show. Must not be null. + /// The placement to tie the showing ad's events to + /// The custom data to tie the showing ad's events to. Maximum size is 8KB. + public static void ShowRewardedInterstitialAd(string adUnitIdentifier, string placement = null, string customData = null) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show rewarded interstitial ad"); + + if (IsRewardedInterstitialAdReady(adUnitIdentifier)) + { + MaxUnityPluginClass.CallStatic("showRewardedInterstitialAd", adUnitIdentifier, placement, customData); + } + else + { + MaxSdkLogger.UserWarning("Not showing MAX Ads rewarded interstitial ad: ad not ready"); + } + } + + /// + /// Set an extra parameter for the ad. + /// + /// Ad unit identifier of the rewarded interstitial to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetRewardedInterstitialAdExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set rewarded interstitial ad extra parameter"); + MaxUnityPluginClass.CallStatic("setRewardedInterstitialAdExtraParameter", adUnitIdentifier, key, value); + } + + /// + /// Set a local extra parameter for the ad. + /// + /// Ad unit identifier of the rewarded interstitial to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the extra parameter. Accepts the following types: , null, IList, IDictionary, string, primitive types + public static void SetRewardedInterstitialAdLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set rewarded interstitial ad local extra parameter"); + + if (value == null || value is AndroidJavaObject) + { + MaxUnityPluginClass.CallStatic("setRewardedInterstitialAdLocalExtraParameter", adUnitIdentifier, key, (AndroidJavaObject) value); + } + else + { + MaxUnityPluginClass.CallStatic("setRewardedInterstitialAdLocalExtraParameterJson", adUnitIdentifier, key, SerializeLocalExtraParameterValue(value)); + } + } + + #endregion + + #region Event Tracking + + /// + /// Track an event using AppLovin. + /// + /// An event from the list of pre-defined events may be found in MaxEvents.cs as part of the AppLovin SDK framework. Must not be null. + /// A dictionary containing key-value pairs further describing this event. + public static void TrackEvent(string name, IDictionary parameters = null) + { + MaxUnityPluginClass.CallStatic("trackEvent", name, Json.Serialize(parameters)); + } + + #endregion + + #region Settings + + /// + /// Set whether to begin video ads in a muted state or not. + /// + /// Please call this method after the SDK has initialized. + /// + /// true if video ads should being in muted state. + public static void SetMuted(bool muted) + { + MaxUnityPluginClass.CallStatic("setMuted", muted); + } + + /// + /// Whether video ads begin in a muted state or not. Defaults to false. + /// + /// Note: Returns false if the SDK is not initialized. + /// + /// true if video ads begin in muted state. + public static bool IsMuted() + { + return MaxUnityPluginClass.CallStatic("isMuted"); + } + + /// + /// Toggle verbose logging of AppLovin SDK. If enabled AppLovin messages will appear in standard application log accessible via logcat. All log messages will have "AppLovinSdk" tag. + /// + /// true if verbose logging should be enabled. + public static void SetVerboseLogging(bool enabled) + { + MaxUnityPluginClass.CallStatic("setVerboseLogging", enabled); + } + + /// + /// Whether or not verbose logging is enabled. + /// + /// true if verbose logging is enabled. + public static bool IsVerboseLoggingEnabled() + { + return MaxUnityPluginClass.CallStatic("isVerboseLoggingEnabled"); + } + + /// + /// Whether the creative debugger will be displayed on fullscreen ads after flipping the device screen down twice. Defaults to true. + /// + /// true if the creative debugger should be enabled. + public static void SetCreativeDebuggerEnabled(bool enabled) + { + MaxUnityPluginClass.CallStatic("setCreativeDebuggerEnabled", enabled); + } + + /// + /// Enable devices to receive test ads, by passing in the advertising identifier (IDFA/GAID) of each test device. + /// Refer to AppLovin logs for the IDFA/GAID of your current device. + /// + /// String list of advertising identifiers from devices to receive test ads. + public static void SetTestDeviceAdvertisingIdentifiers(string[] advertisingIdentifiers) + { + if (IsInitialized()) + { + MaxSdkLogger.UserError("Test Device Advertising Identifiers must be set before SDK initialization."); + return; + } + + // Wrap the string array in an object array, so the compiler does not split into multiple strings. + object[] arguments = {advertisingIdentifiers}; + MaxUnityPluginClass.CallStatic("setTestDeviceAdvertisingIds", arguments); + } + + /// + /// Whether or not the native AppLovin SDKs listen to exceptions. Defaults to true. + /// + /// true if the native AppLovin SDKs should not listen to exceptions. + public static void SetExceptionHandlerEnabled(bool enabled) + { + MaxUnityPluginClass.CallStatic("setExceptionHandlerEnabled", enabled); + } + + /// + /// Set an extra parameter to pass to the AppLovin server. + /// + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. May be null. + public static void SetExtraParameter(string key, string value) + { + HandleExtraParameter(key, value); + + MaxUnityPluginClass.CallStatic("setExtraParameter", key, value); + } + + /// + /// Get the native insets in pixels for the safe area. + /// These insets are used to position ads within the safe area of the screen. + /// + public static SafeAreaInsets GetSafeAreaInsets() + { + // Use an int array instead of json serialization for performance + var insets = MaxUnityPluginClass.CallStatic("getSafeAreaInsets"); + + // Convert from points to pixels + var screenDensity = MaxSdkUtils.GetScreenDensity(); + for (var i = 0; i < insets.Length; i++) + { + insets[i] *= (int) screenDensity; + } + + return new SafeAreaInsets(insets); + } + + #endregion + + #region Obsolete + + [Obsolete("This API has been deprecated and will be removed in a future release. Please set your SDK key in the AppLovin Integration Manager.")] + public static void SetSdkKey(string sdkKey) + { + MaxUnityPluginClass.CallStatic("setSdkKey", sdkKey); + MaxSdkLogger.UserWarning("MaxSdk.SetSdkKey() has been deprecated and will be removed in a future release. Please set your SDK key in the AppLovin Integration Manager."); + } + + [Obsolete("This method has been deprecated. Please use `GetSdkConfiguration().ConsentDialogState`")] + public static ConsentDialogState GetConsentDialogState() + { + if (!IsInitialized()) + { + MaxSdkLogger.UserWarning("MAX Ads SDK has not been initialized yet. GetConsentDialogState() may return ConsentDialogState.Unknown"); + } + + return (ConsentDialogState) MaxUnityPluginClass.CallStatic("getConsentDialogState"); + } + + [Obsolete("This method has been deprecated. The AdInfo object is returned with ad callbacks.")] + public static AdInfo GetAdInfo(string adUnitIdentifier) + { + var adInfoString = MaxUnityPluginClass.CallStatic("getAdInfo", adUnitIdentifier); + + if (string.IsNullOrEmpty(adInfoString)) return null; + + var adInfoDictionary = Json.Deserialize(adInfoString) as Dictionary; + return new AdInfo(adInfoDictionary); + } + + #endregion + + internal class BackgroundCallbackProxy : AndroidJavaProxy + { + public BackgroundCallbackProxy() : base("com.applovin.mediation.unity.MaxUnityAdManager$BackgroundCallback") { } + + public void onEvent(string propsStr) + { + HandleBackgroundCallback(propsStr); + } + } +} diff --git a/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs.meta b/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs.meta new file mode 100644 index 0000000..2cf5448 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkAndroid.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 10335fad6bfef47b8819a411aa591dc8 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdkAndroid.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdkBase.cs b/Assets/MaxSdk/Scripts/MaxSdkBase.cs new file mode 100644 index 0000000..b32e508 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkBase.cs @@ -0,0 +1,767 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using AppLovinMax.ThirdParty.MiniJson; +using AppLovinMax.Internal; +using UnityEngine; + +#if UNITY_IOS && !UNITY_EDITOR +using System.Runtime.InteropServices; +#endif + +public abstract class MaxSdkBase +{ + /// + /// This enum represents the user's geography used to determine the type of consent flow shown to the user. + /// + public enum ConsentFlowUserGeography + { + /// + /// User's geography is unknown. + /// + Unknown, + + /// + /// The user is in GDPR region. + /// + Gdpr, + + /// + /// The user is in a non-GDPR region. + /// + Other + } + +#if UNITY_EDITOR || UNITY_IPHONE || UNITY_IOS + /// + /// App tracking status values. Primarily used in conjunction with iOS14's AppTrackingTransparency.framework. + /// + public enum AppTrackingStatus + { + /// + /// Device is on < iOS14, AppTrackingTransparency.framework is not available. + /// + Unavailable, + + /// + /// The value returned if a user has not yet received an authorization request to authorize access to app-related data that can be used for tracking the user or the device. + /// + NotDetermined, + + /// + /// The value returned if authorization to access app-related data that can be used for tracking the user or the device is restricted. + /// + Restricted, + + /// + /// The value returned if the user denies authorization to access app-related data that can be used for tracking the user or the device. + /// + Denied, + + /// + /// The value returned if the user authorizes access to app-related data that can be used for tracking the user or the device. + /// + Authorized, + } +#endif + + public enum AdViewPosition + { + TopLeft, + TopCenter, + TopRight, + Centered, + CenterLeft, + CenterRight, + BottomLeft, + BottomCenter, + BottomRight + } + + public enum BannerPosition + { + TopLeft, + TopCenter, + TopRight, + Centered, + CenterLeft, + CenterRight, + BottomLeft, + BottomCenter, + BottomRight + } + + public class SdkConfiguration + { + /// + /// Whether or not the SDK has been initialized successfully. + /// + public bool IsSuccessfullyInitialized { get; private set; } + + /// + /// Get the country code for this user. + /// + public string CountryCode { get; private set; } + +#if UNITY_EDITOR || UNITY_IPHONE || UNITY_IOS + /// + /// App tracking status values. Primarily used in conjunction with iOS14's AppTrackingTransparency.framework. + /// + public AppTrackingStatus AppTrackingStatus { get; private set; } +#endif + + public bool IsTestModeEnabled { get; private set; } + + /// + /// Get the user's geography used to determine the type of consent flow shown to the user. + /// If no such determination could be made, will be returned. + /// + public ConsentFlowUserGeography ConsentFlowUserGeography { get; private set; } + + [Obsolete("This API has been deprecated and will be removed in a future release.")] + public ConsentDialogState ConsentDialogState { get; private set; } + +#if UNITY_EDITOR || !(UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS) + public static SdkConfiguration CreateEmpty() + { + var sdkConfiguration = new SdkConfiguration(); + sdkConfiguration.IsSuccessfullyInitialized = true; +#pragma warning disable 0618 + sdkConfiguration.ConsentDialogState = ConsentDialogState.Unknown; +#pragma warning restore 0618 +#if UNITY_EDITOR + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.Authorized; +#endif + sdkConfiguration.CountryCode = TryGetCountryCode(); + sdkConfiguration.IsTestModeEnabled = false; + + return sdkConfiguration; + } + + private static string TryGetCountryCode() + { + try + { + return RegionInfo.CurrentRegion.TwoLetterISORegionName; + } +#pragma warning disable 0168 + catch (Exception ignored) +#pragma warning restore 0168 + { + // Ignored + } + + return "US"; + } +#endif + + public static SdkConfiguration Create(IDictionary eventProps) + { + var sdkConfiguration = new SdkConfiguration(); + + sdkConfiguration.IsSuccessfullyInitialized = MaxSdkUtils.GetBoolFromDictionary(eventProps, "isSuccessfullyInitialized"); + sdkConfiguration.CountryCode = MaxSdkUtils.GetStringFromDictionary(eventProps, "countryCode", ""); + sdkConfiguration.IsTestModeEnabled = MaxSdkUtils.GetBoolFromDictionary(eventProps, "isTestModeEnabled"); + + var consentFlowUserGeographyStr = MaxSdkUtils.GetStringFromDictionary(eventProps, "consentFlowUserGeography", ""); + if ("1".Equals(consentFlowUserGeographyStr)) + { + sdkConfiguration.ConsentFlowUserGeography = ConsentFlowUserGeography.Gdpr; + } + else if ("2".Equals(consentFlowUserGeographyStr)) + { + sdkConfiguration.ConsentFlowUserGeography = ConsentFlowUserGeography.Other; + } + else + { + sdkConfiguration.ConsentFlowUserGeography = ConsentFlowUserGeography.Unknown; + } + +#pragma warning disable 0618 + var consentDialogStateStr = MaxSdkUtils.GetStringFromDictionary(eventProps, "consentDialogState", ""); + if ("1".Equals(consentDialogStateStr)) + { + sdkConfiguration.ConsentDialogState = ConsentDialogState.Applies; + } + else if ("2".Equals(consentDialogStateStr)) + { + sdkConfiguration.ConsentDialogState = ConsentDialogState.DoesNotApply; + } + else + { + sdkConfiguration.ConsentDialogState = ConsentDialogState.Unknown; + } +#pragma warning restore 0618 + +#if UNITY_IPHONE || UNITY_IOS + var appTrackingStatusStr = MaxSdkUtils.GetStringFromDictionary(eventProps, "appTrackingStatus", "-1"); + if ("-1".Equals(appTrackingStatusStr)) + { + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.Unavailable; + } + else if ("0".Equals(appTrackingStatusStr)) + { + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.NotDetermined; + } + else if ("1".Equals(appTrackingStatusStr)) + { + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.Restricted; + } + else if ("2".Equals(appTrackingStatusStr)) + { + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.Denied; + } + else // "3" is authorized + { + sdkConfiguration.AppTrackingStatus = AppTrackingStatus.Authorized; + } +#endif + + return sdkConfiguration; + } + } + + public struct Reward + { + public string Label; + public int Amount; + + public override string ToString() + { + return "Reward: " + Amount + " " + Label; + } + + public bool IsValid() + { + return !string.IsNullOrEmpty(Label) && Amount > 0; + } + } + + /** + * This enum contains various error codes that the SDK can return when a MAX ad fails to load or display. + */ + public enum ErrorCode + { + /// + /// This error code represents an error that could not be categorized into one of the other defined errors. See the message field in the error object for more details. + /// + Unspecified = -1, + + /// + /// This error code indicates that MAX returned no eligible ads from any mediated networks for this app/device. + /// + NoFill = 204, + + /// + /// This error code indicates that MAX returned eligible ads from mediated networks, but all ads failed to load. See the adLoadFailureInfo field in the error object for more details. + /// + AdLoadFailed = -5001, + + /// + /// This error code represents an error that was encountered when showing an ad. + /// + AdDisplayFailed = -4205, + + /// + /// This error code indicates that the ad request failed due to a generic network error. See the message field in the error object for more details. + /// + NetworkError = -1000, + + /// + /// This error code indicates that the ad request timed out due to a slow internet connection. + /// + NetworkTimeout = -1001, + + /// + /// This error code indicates that the ad request failed because the device is not connected to the internet. + /// + NoNetwork = -1009, + + /// + /// This error code indicates that you attempted to show a fullscreen ad while another fullscreen ad is still showing. + /// + FullscreenAdAlreadyShowing = -23, + + /// + /// This error code indicates you are attempting to show a fullscreen ad before the one has been loaded. + /// + FullscreenAdNotReady = -24, + +#if UNITY_IOS || UNITY_IPHONE + /// + /// This error code indicates you attempted to present a fullscreen ad from an invalid view controller. + /// + FullscreenAdInvalidViewController = -25, +#endif + + /// + /// This error code indicates you are attempting to load a fullscreen ad while another fullscreen ad is already loading. + /// + FullscreenAdAlreadyLoading = -26, + + /// + /// This error code indicates you are attempting to load a fullscreen ad while another fullscreen ad is still showing. + /// + FullscreenAdLoadWhileShowing = -27, + +#if UNITY_ANDROID + /// + /// This error code indicates that the SDK failed to display an ad because the user has the "Don't Keep Activities" developer setting enabled. + /// + DontKeepActivitiesEnabled = -5602, +#endif + + /// + /// This error code indicates that the SDK failed to load an ad because the publisher provided an invalid ad unit identifier. + /// Possible reasons for an invalid ad unit identifier: + /// 1. Ad unit identifier is malformed or does not exist + /// 2. Ad unit is disabled + /// 3. Ad unit is not associated with the current app's package name + /// 4. Ad unit was created within the last 30-60 minutes + /// + InvalidAdUnitId = -5603 + } + + /** + * This enum contains possible states of an ad in the waterfall the adapter response info could represent. + */ + public enum MaxAdLoadState + { + /// + /// The AppLovin Max SDK did not attempt to load an ad from this network in the waterfall because an ad higher + /// in the waterfall loaded successfully. + /// + AdLoadNotAttempted, + + /// + /// An ad successfully loaded from this network. + /// + AdLoaded, + + /// + /// An ad failed to load from this network. + /// + FailedToLoad + } + + public class AdInfo + { + public string AdUnitIdentifier { get; private set; } + public string AdFormat { get; private set; } + public string NetworkName { get; private set; } + public string NetworkPlacement { get; private set; } + public string Placement { get; private set; } + public string CreativeIdentifier { get; private set; } + public double Revenue { get; private set; } + public string RevenuePrecision { get; private set; } + public WaterfallInfo WaterfallInfo { get; private set; } + public long LatencyMillis { get; private set; } + public string DspName { get; private set; } + + public AdInfo(IDictionary adInfoDictionary) + { + AdUnitIdentifier = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "adUnitId"); + AdFormat = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "adFormat"); + NetworkName = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "networkName"); + NetworkPlacement = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "networkPlacement"); + CreativeIdentifier = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "creativeId"); + Placement = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "placement"); + Revenue = MaxSdkUtils.GetDoubleFromDictionary(adInfoDictionary, "revenue", -1); + RevenuePrecision = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "revenuePrecision"); + WaterfallInfo = new WaterfallInfo(MaxSdkUtils.GetDictionaryFromDictionary(adInfoDictionary, "waterfallInfo", new Dictionary())); + LatencyMillis = MaxSdkUtils.GetLongFromDictionary(adInfoDictionary, "latencyMillis"); + DspName = MaxSdkUtils.GetStringFromDictionary(adInfoDictionary, "dspName"); + } + + public override string ToString() + { + return "[AdInfo adUnitIdentifier: " + AdUnitIdentifier + + ", adFormat: " + AdFormat + + ", networkName: " + NetworkName + + ", networkPlacement: " + NetworkPlacement + + ", creativeIdentifier: " + CreativeIdentifier + + ", placement: " + Placement + + ", revenue: " + Revenue + + ", revenuePrecision: " + RevenuePrecision + + ", latency: " + LatencyMillis + + ", dspName: " + DspName + "]"; + } + } + + /// + /// Returns information about the ad response in a waterfall. + /// + public class WaterfallInfo + { + public String Name { get; private set; } + public String TestName { get; private set; } + public List NetworkResponses { get; private set; } + public long LatencyMillis { get; private set; } + + public WaterfallInfo(IDictionary waterfallInfoDict) + { + Name = MaxSdkUtils.GetStringFromDictionary(waterfallInfoDict, "name"); + TestName = MaxSdkUtils.GetStringFromDictionary(waterfallInfoDict, "testName"); + + var networkResponsesList = MaxSdkUtils.GetListFromDictionary(waterfallInfoDict, "networkResponses", new List()); + NetworkResponses = new List(); + foreach (var networkResponseObject in networkResponsesList) + { + var networkResponseDict = networkResponseObject as Dictionary; + if (networkResponseDict == null) continue; + + var networkResponse = new NetworkResponseInfo(networkResponseDict); + NetworkResponses.Add(networkResponse); + } + + LatencyMillis = MaxSdkUtils.GetLongFromDictionary(waterfallInfoDict, "latencyMillis"); + } + + public override string ToString() + { + return "[MediatedNetworkInfo: name = " + Name + + ", testName = " + TestName + + ", latency = " + LatencyMillis + + ", networkResponse = " + string.Join(", ", NetworkResponses.Select(networkResponseInfo => networkResponseInfo.ToString()).ToArray()) + "]"; + } + } + + public class NetworkResponseInfo + { + public MaxAdLoadState AdLoadState { get; private set; } + public MediatedNetworkInfo MediatedNetwork { get; private set; } + public Dictionary Credentials { get; private set; } + public bool IsBidding { get; private set; } + public long LatencyMillis { get; private set; } + public ErrorInfo Error { get; private set; } + + public NetworkResponseInfo(IDictionary networkResponseInfoDict) + { + var mediatedNetworkInfoDict = MaxSdkUtils.GetDictionaryFromDictionary(networkResponseInfoDict, "mediatedNetwork"); + MediatedNetwork = mediatedNetworkInfoDict != null ? new MediatedNetworkInfo(mediatedNetworkInfoDict) : null; + + Credentials = MaxSdkUtils.GetDictionaryFromDictionary(networkResponseInfoDict, "credentials", new Dictionary()); + IsBidding = MaxSdkUtils.GetBoolFromDictionary(networkResponseInfoDict, "isBidding"); + LatencyMillis = MaxSdkUtils.GetLongFromDictionary(networkResponseInfoDict, "latencyMillis"); + AdLoadState = (MaxAdLoadState) MaxSdkUtils.GetIntFromDictionary(networkResponseInfoDict, "adLoadState"); + + var errorInfoDict = MaxSdkUtils.GetDictionaryFromDictionary(networkResponseInfoDict, "error"); + Error = errorInfoDict != null ? new ErrorInfo(errorInfoDict) : null; + } + + public override string ToString() + { + var stringBuilder = new StringBuilder("[NetworkResponseInfo: adLoadState = ").Append(AdLoadState); + stringBuilder.Append(", mediatedNetwork = ").Append(MediatedNetwork); + stringBuilder.Append(", credentials = ").Append(string.Join(", ", Credentials.Select(keyValuePair => keyValuePair.ToString()).ToArray())); + + switch (AdLoadState) + { + case MaxAdLoadState.FailedToLoad: + stringBuilder.Append(", error = ").Append(Error); + break; + case MaxAdLoadState.AdLoaded: + stringBuilder.Append(", latency = ").Append(LatencyMillis); + break; + } + + return stringBuilder.Append("]").ToString(); + } + } + + public class MediatedNetworkInfo + { + public string Name { get; private set; } + public string AdapterClassName { get; private set; } + public string AdapterVersion { get; private set; } + public string SdkVersion { get; private set; } + + public MediatedNetworkInfo(IDictionary mediatedNetworkDictionary) + { + // NOTE: Unity Editor creates empty string + Name = MaxSdkUtils.GetStringFromDictionary(mediatedNetworkDictionary, "name", ""); + AdapterClassName = MaxSdkUtils.GetStringFromDictionary(mediatedNetworkDictionary, "adapterClassName", ""); + AdapterVersion = MaxSdkUtils.GetStringFromDictionary(mediatedNetworkDictionary, "adapterVersion", ""); + SdkVersion = MaxSdkUtils.GetStringFromDictionary(mediatedNetworkDictionary, "sdkVersion", ""); + } + + public override string ToString() + { + return "[MediatedNetworkInfo name: " + Name + + ", adapterClassName: " + AdapterClassName + + ", adapterVersion: " + AdapterVersion + + ", sdkVersion: " + SdkVersion + "]"; + } + } + + public class ErrorInfo + { + public ErrorCode Code { get; private set; } + public string Message { get; private set; } + public int MediatedNetworkErrorCode { get; private set; } + public string MediatedNetworkErrorMessage { get; private set; } + public string AdLoadFailureInfo { get; private set; } + public WaterfallInfo WaterfallInfo { get; private set; } + public long LatencyMillis { get; private set; } + + public ErrorInfo(IDictionary errorInfoDictionary) + { + Code = (ErrorCode) MaxSdkUtils.GetIntFromDictionary(errorInfoDictionary, "errorCode", -1); + Message = MaxSdkUtils.GetStringFromDictionary(errorInfoDictionary, "errorMessage", ""); + MediatedNetworkErrorCode = MaxSdkUtils.GetIntFromDictionary(errorInfoDictionary, "mediatedNetworkErrorCode", (int) ErrorCode.Unspecified); + MediatedNetworkErrorMessage = MaxSdkUtils.GetStringFromDictionary(errorInfoDictionary, "mediatedNetworkErrorMessage", ""); + AdLoadFailureInfo = MaxSdkUtils.GetStringFromDictionary(errorInfoDictionary, "adLoadFailureInfo", ""); + WaterfallInfo = new WaterfallInfo(MaxSdkUtils.GetDictionaryFromDictionary(errorInfoDictionary, "waterfallInfo", new Dictionary())); + LatencyMillis = MaxSdkUtils.GetLongFromDictionary(errorInfoDictionary, "latencyMillis"); + } + + public override string ToString() + { + var stringbuilder = new StringBuilder("[ErrorInfo code: ").Append(Code); + stringbuilder.Append(", message: ").Append(Message); + + if (Code == ErrorCode.AdDisplayFailed) + { + stringbuilder.Append(", mediatedNetworkCode: ").Append(MediatedNetworkErrorCode); + stringbuilder.Append(", mediatedNetworkMessage: ").Append(MediatedNetworkErrorMessage); + } + + stringbuilder.Append(", latency: ").Append(LatencyMillis); + return stringbuilder.Append(", adLoadFailureInfo: ").Append(AdLoadFailureInfo).Append("]").ToString(); + } + } + + /// + /// Inset values for the safe area on the screen used to render banner ads. + /// + public class SafeAreaInsets + { + public int Left { get; private set; } + public int Top { get; private set; } + public int Right { get; private set; } + public int Bottom { get; private set; } + + /// + /// Creates a new instance of . + /// + /// An integer array with insets values in the order of left, top, right, and bottom + internal SafeAreaInsets(int[] insets) + { + Left = insets[0]; + Top = insets[1]; + Right = insets[2]; + Bottom = insets[3]; + } + + public override string ToString() + { + return "[SafeAreaInsets: Left: " + Left + + ", Top: " + Top + + ", Right: " + Right + + ", Bottom: " + Bottom + "]"; + } + } + + /// + /// Determines whether ad events raised by the AppLovin's Unity plugin should be invoked on the Unity main thread. + /// + public static bool? InvokeEventsOnUnityMainThread { get; set; } + + /// + /// The CMP service, which provides direct APIs for interfacing with the Google-certified CMP installed, if any. + /// + public static MaxCmpService CmpService + { + get { return MaxCmpService.Instance; } + } + + internal static bool DisableAllLogs + { + get; private set; + } + + protected static void ValidateAdUnitIdentifier(string adUnitIdentifier, string debugPurpose) + { + if (string.IsNullOrEmpty(adUnitIdentifier)) + { + MaxSdkLogger.UserError("No MAX Ads Ad Unit ID specified for: " + debugPurpose); + } + } + + // Allocate the MaxEventExecutor singleton which handles pushing callbacks from the background to the main thread. + protected static void InitializeEventExecutor() + { + MaxEventExecutor.InitializeIfNeeded(); + } + + /// + /// Generates serialized Unity meta data to be passed to the SDK. + /// + /// Serialized Unity meta data. + protected static string GenerateMetaData() + { + var metaData = new Dictionary(2); + metaData.Add("UnityVersion", Application.unityVersion); + + return Json.Serialize(metaData); + } + + /// + /// Parses the prop string provided to a . + /// + /// A prop string representing a Rect + /// A the prop string represents. + protected static Rect GetRectFromString(string rectPropString) + { + var rectDict = Json.Deserialize(rectPropString) as Dictionary; + var originX = MaxSdkUtils.GetFloatFromDictionary(rectDict, "origin_x", 0); + var originY = MaxSdkUtils.GetFloatFromDictionary(rectDict, "origin_y", 0); + var width = MaxSdkUtils.GetFloatFromDictionary(rectDict, "width", 0); + var height = MaxSdkUtils.GetFloatFromDictionary(rectDict, "height", 0); + + return new Rect(originX, originY, width, height); + } + + protected static void HandleExtraParameter(string key, string value) + { + bool disableAllLogs; + if ("disable_all_logs".Equals(key) && bool.TryParse(value, out disableAllLogs)) + { + DisableAllLogs = disableAllLogs; + } + } + + /// + /// Handles forwarding callbacks from native to C#. + /// + /// A prop string with the event data + protected static void HandleBackgroundCallback(string propsStr) + { + try + { + MaxSdkCallbacks.ForwardEvent(propsStr); + } + catch (Exception exception) + { + var eventProps = Json.Deserialize(propsStr) as Dictionary; + if (eventProps == null) return; + + var eventName = MaxSdkUtils.GetStringFromDictionary(eventProps, "name", ""); + MaxSdkLogger.UserError("Unable to notify ad delegate due to an error in the publisher callback '" + eventName + "' due to exception: " + exception.Message); + MaxSdkLogger.LogException(exception); + } + } + + protected static string SerializeLocalExtraParameterValue(object value) + { + if (!(value.GetType().IsPrimitive || value is string || value is IList || value is IDictionary)) + { + MaxSdkLogger.UserError("Local extra parameters must be an IList, IDictionary, string, or a primitive type"); + return ""; + } + + Dictionary data = new Dictionary + { + {"value", value} + }; + + return Json.Serialize(data); + } + + [Obsolete("This API has been deprecated and will be removed in a future release.")] + public enum ConsentDialogState + { + Unknown, + Applies, + DoesNotApply + } +} + +/// +/// An extension class for and enums. +/// +internal static class AdPositionExtenstion +{ + public static string ToSnakeCaseString(this MaxSdkBase.BannerPosition position) + { + if (position == MaxSdkBase.BannerPosition.TopLeft) + { + return "top_left"; + } + else if (position == MaxSdkBase.BannerPosition.TopCenter) + { + return "top_center"; + } + else if (position == MaxSdkBase.BannerPosition.TopRight) + { + return "top_right"; + } + else if (position == MaxSdkBase.BannerPosition.Centered) + { + return "centered"; + } + else if (position == MaxSdkBase.BannerPosition.CenterLeft) + { + return "center_left"; + } + else if (position == MaxSdkBase.BannerPosition.CenterRight) + { + return "center_right"; + } + else if (position == MaxSdkBase.BannerPosition.BottomLeft) + { + return "bottom_left"; + } + else if (position == MaxSdkBase.BannerPosition.BottomCenter) + { + return "bottom_center"; + } + else // position == MaxSdkBase.BannerPosition.BottomRight + { + return "bottom_right"; + } + } + + public static string ToSnakeCaseString(this MaxSdkBase.AdViewPosition position) + { + if (position == MaxSdkBase.AdViewPosition.TopLeft) + { + return "top_left"; + } + else if (position == MaxSdkBase.AdViewPosition.TopCenter) + { + return "top_center"; + } + else if (position == MaxSdkBase.AdViewPosition.TopRight) + { + return "top_right"; + } + else if (position == MaxSdkBase.AdViewPosition.Centered) + { + return "centered"; + } + else if (position == MaxSdkBase.AdViewPosition.CenterLeft) + { + return "center_left"; + } + else if (position == MaxSdkBase.AdViewPosition.CenterRight) + { + return "center_right"; + } + else if (position == MaxSdkBase.AdViewPosition.BottomLeft) + { + return "bottom_left"; + } + else if (position == MaxSdkBase.AdViewPosition.BottomCenter) + { + return "bottom_center"; + } + else // position == MaxSdkBase.AdViewPosition.BottomRight + { + return "bottom_right"; + } + } +} diff --git a/Assets/MaxSdk/Scripts/MaxSdkBase.cs.meta b/Assets/MaxSdk/Scripts/MaxSdkBase.cs.meta new file mode 100644 index 0000000..f27f769 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkBase.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 893e4e55a7e394274957f1034f7afc45 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdkBase.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs b/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs new file mode 100644 index 0000000..3aac80e --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs @@ -0,0 +1,1716 @@ +/** + * This is is a global Unity object that is used to forward callbacks from native iOS / Android Max code to the application. + */ + +using System; +using System.Collections.Generic; +using System.Globalization; +using UnityEngine; +using AppLovinMax.ThirdParty.MiniJson; +using AppLovinMax.Internal; + +public static class MaxSdkCallbacks +{ + // Fired when the SDK has finished initializing + private static Action _onSdkInitializedEvent; + public static event Action OnSdkInitializedEvent + { + add + { + LogSubscribedToEvent("OnSdkInitializedEvent"); + _onSdkInitializedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnSdkInitializedEvent"); + _onSdkInitializedEvent -= value; + } + } + + private static Action _onApplicationStateChangedEvent; + /// + /// Fired when the application is paused or resumed. + /// + public static event Action OnApplicationStateChangedEvent + { + add + { + LogSubscribedToEvent("OnApplicationStateChangedEvent"); + _onApplicationStateChangedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnApplicationStateChangedEvent"); + _onApplicationStateChangedEvent -= value; + } + } + + private static Action _onInterstitialAdLoadedEventV2; + private static Action _onInterstitialAdLoadFailedEventV2; + private static Action _onInterstitialAdDisplayedEventV2; + private static Action _onInterstitialAdFailedToDisplayEventV2; + private static Action _onInterstitialAdClickedEventV2; + private static Action _onInterstitialAdRevenuePaidEvent; + private static Action _onInterstitialAdReviewCreativeIdGeneratedEvent; + private static Action _onInterstitialAdHiddenEventV2; + + public class Interstitial + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdLoadedEvent"); + _onInterstitialAdLoadedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdLoadedEvent"); + _onInterstitialAdLoadedEventV2 -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdLoadFailedEvent"); + _onInterstitialAdLoadFailedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdLoadFailedEvent"); + _onInterstitialAdLoadFailedEventV2 -= value; + } + } + + /** + * Fired when an interstitial ad is displayed (may not be received by Unity until the interstitial ad closes). + */ + public static event Action OnAdDisplayedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdDisplayedEvent"); + _onInterstitialAdDisplayedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdDisplayedEvent"); + _onInterstitialAdDisplayedEventV2 -= value; + } + } + + public static event Action OnAdDisplayFailedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdDisplayFailedEvent"); + _onInterstitialAdFailedToDisplayEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdDisplayFailedEvent"); + _onInterstitialAdFailedToDisplayEventV2 -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdClickedEvent"); + _onInterstitialAdClickedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdClickedEvent"); + _onInterstitialAdClickedEventV2 -= value; + } + } + + /// + /// Fired when an interstitial ad impression was validated and revenue will be paid. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdRevenuePaidEvent"); + _onInterstitialAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdRevenuePaidEvent"); + _onInterstitialAdRevenuePaidEvent -= value; + } + } + + /// + /// Fired when an Ad Review Creative ID has been generated. + /// The parameters returned are the adUnitIdentifier, adReviewCreativeId, and adInfo in that respective order. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdReviewCreativeIdGeneratedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdReviewCreativeIdGeneratedEvent"); + _onInterstitialAdReviewCreativeIdGeneratedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdReviewCreativeIdGeneratedEvent"); + _onInterstitialAdReviewCreativeIdGeneratedEvent -= value; + } + } + + public static event Action OnAdHiddenEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdHiddenEvent"); + _onInterstitialAdHiddenEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdHiddenEvent"); + _onInterstitialAdHiddenEventV2 -= value; + } + } + } + + private static Action _onAppOpenAdLoadedEvent; + private static Action _onAppOpenAdLoadFailedEvent; + private static Action _onAppOpenAdDisplayedEvent; + private static Action _onAppOpenAdFailedToDisplayEvent; + private static Action _onAppOpenAdClickedEvent; + private static Action _onAppOpenAdRevenuePaidEvent; + private static Action _onAppOpenAdHiddenEvent; + + public class AppOpen + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdLoadedEvent"); + _onAppOpenAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdLoadedEvent"); + _onAppOpenAdLoadedEvent -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdLoadFailedEvent"); + _onAppOpenAdLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdLoadFailedEvent"); + _onAppOpenAdLoadFailedEvent -= value; + } + } + + /** + * Fired when an app open ad is displayed (may not be received by Unity until the app open ad closes). + */ + public static event Action OnAdDisplayedEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdDisplayedEvent"); + _onAppOpenAdDisplayedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdDisplayedEvent"); + _onAppOpenAdDisplayedEvent -= value; + } + } + + public static event Action OnAdDisplayFailedEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdDisplayFailedEvent"); + _onAppOpenAdFailedToDisplayEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdDisplayFailedEvent"); + _onAppOpenAdFailedToDisplayEvent -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdClickedEvent"); + _onAppOpenAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdClickedEvent"); + _onAppOpenAdClickedEvent -= value; + } + } + + /// + /// Fired when an app open ad impression was validated and revenue will be paid. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdRevenuePaidEvent"); + _onAppOpenAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdRevenuePaidEvent"); + _onAppOpenAdRevenuePaidEvent -= value; + } + } + + public static event Action OnAdHiddenEvent + { + add + { + LogSubscribedToEvent("OnAppOpenAdHiddenEvent"); + _onAppOpenAdHiddenEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnAppOpenAdHiddenEvent"); + _onAppOpenAdHiddenEvent -= value; + } + } + } + + private static Action _onRewardedAdLoadedEventV2; + private static Action _onRewardedAdLoadFailedEventV2; + private static Action _onRewardedAdDisplayedEventV2; + private static Action _onRewardedAdFailedToDisplayEventV2; + private static Action _onRewardedAdClickedEventV2; + private static Action _onRewardedAdRevenuePaidEvent; + private static Action _onRewardedAdReviewCreativeIdGeneratedEvent; + private static Action _onRewardedAdReceivedRewardEventV2; + private static Action _onRewardedAdHiddenEventV2; + + public class Rewarded + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdLoadedEvent"); + _onRewardedAdLoadedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdLoadedEvent"); + _onRewardedAdLoadedEventV2 -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdLoadFailedEvent"); + _onRewardedAdLoadFailedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdLoadFailedEvent"); + _onRewardedAdLoadFailedEventV2 -= value; + } + } + + /** + * Fired when a rewarded ad is displayed (may not be received by Unity until the rewarded ad closes). + */ + public static event Action OnAdDisplayedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdDisplayedEvent"); + _onRewardedAdDisplayedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdDisplayedEvent"); + _onRewardedAdDisplayedEventV2 -= value; + } + } + + public static event Action OnAdDisplayFailedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdDisplayFailedEvent"); + _onRewardedAdFailedToDisplayEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdDisplayFailedEvent"); + _onRewardedAdFailedToDisplayEventV2 -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdClickedEvent"); + _onRewardedAdClickedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdClickedEvent"); + _onRewardedAdClickedEventV2 -= value; + } + } + + /// + /// Fired when a rewarded ad impression was validated and revenue will be paid. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdRevenuePaidEvent"); + _onRewardedAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdRevenuePaidEvent"); + _onRewardedAdRevenuePaidEvent -= value; + } + } + + /// + /// Fired when an Ad Review Creative ID has been generated. + /// The parameters returned are the adUnitIdentifier, adReviewCreativeId, and adInfo in that respective order. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdReviewCreativeIdGeneratedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdReviewCreativeIdGeneratedEvent"); + _onRewardedAdReviewCreativeIdGeneratedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdReviewCreativeIdGeneratedEvent"); + _onRewardedAdReviewCreativeIdGeneratedEvent -= value; + } + } + + public static event Action OnAdReceivedRewardEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdReceivedRewardEvent"); + _onRewardedAdReceivedRewardEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdReceivedRewardEvent"); + _onRewardedAdReceivedRewardEventV2 -= value; + } + } + + public static event Action OnAdHiddenEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdHiddenEvent"); + _onRewardedAdHiddenEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdHiddenEvent"); + _onRewardedAdHiddenEventV2 -= value; + } + } + } + + private static Action _onRewardedInterstitialAdLoadedEvent; + private static Action _onRewardedInterstitialAdLoadFailedEvent; + private static Action _onRewardedInterstitialAdDisplayedEvent; + private static Action _onRewardedInterstitialAdFailedToDisplayEvent; + private static Action _onRewardedInterstitialAdClickedEvent; + private static Action _onRewardedInterstitialAdRevenuePaidEvent; + private static Action _onRewardedInterstitialAdReviewCreativeIdGeneratedEvent; + private static Action _onRewardedInterstitialAdReceivedRewardEvent; + private static Action _onRewardedInterstitialAdHiddenEvent; + + public class RewardedInterstitial + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdLoadedEvent"); + _onRewardedInterstitialAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdLoadedEvent"); + _onRewardedInterstitialAdLoadedEvent -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdLoadFailedEvent"); + _onRewardedInterstitialAdLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdLoadFailedEvent"); + _onRewardedInterstitialAdLoadFailedEvent -= value; + } + } + + /** + * Fired when a rewarded interstitial ad is displayed (may not be received by Unity until + * the rewarded interstitial ad closes). + */ + public static event Action OnAdDisplayedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdDisplayedEvent"); + _onRewardedInterstitialAdDisplayedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdDisplayedEvent"); + _onRewardedInterstitialAdDisplayedEvent -= value; + } + } + + public static event Action OnAdDisplayFailedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdDisplayFailedEvent"); + _onRewardedInterstitialAdFailedToDisplayEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdDisplayFailedEvent"); + _onRewardedInterstitialAdFailedToDisplayEvent -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdClickedEvent"); + _onRewardedInterstitialAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdClickedEvent"); + _onRewardedInterstitialAdClickedEvent -= value; + } + } + + /// + /// Fired when a rewarded interstitial ad impression was validated and revenue will be paid. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdRevenuePaidEvent"); + _onRewardedInterstitialAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdRevenuePaidEvent"); + _onRewardedInterstitialAdRevenuePaidEvent -= value; + } + } + + /// + /// Fired when an Ad Review Creative ID has been generated. + /// The parameters returned are the adUnitIdentifier, adReviewCreativeId, and adInfo in that respective order. + /// Executed on a background thread to avoid any delays in execution. + /// + public static event Action OnAdReviewCreativeIdGeneratedEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdReviewCreativeIdGeneratedEvent"); + _onRewardedInterstitialAdReviewCreativeIdGeneratedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdReviewCreativeIdGeneratedEvent"); + _onRewardedInterstitialAdReviewCreativeIdGeneratedEvent -= value; + } + } + + public static event Action OnAdReceivedRewardEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdReceivedRewardEvent"); + _onRewardedInterstitialAdReceivedRewardEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdReceivedRewardEvent"); + _onRewardedInterstitialAdReceivedRewardEvent -= value; + } + } + + public static event Action OnAdHiddenEvent + { + add + { + LogSubscribedToEvent("OnRewardedInterstitialAdHiddenEvent"); + _onRewardedInterstitialAdHiddenEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedInterstitialAdHiddenEvent"); + _onRewardedInterstitialAdHiddenEvent -= value; + } + } + } + + private static Action _onBannerAdLoadedEventV2; + private static Action _onBannerAdLoadFailedEventV2; + private static Action _onBannerAdClickedEventV2; + private static Action _onBannerAdRevenuePaidEvent; + private static Action _onBannerAdReviewCreativeIdGeneratedEvent; + private static Action _onBannerAdExpandedEventV2; + private static Action _onBannerAdCollapsedEventV2; + + public class Banner + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdLoadedEvent"); + _onBannerAdLoadedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdLoadedEvent"); + _onBannerAdLoadedEventV2 -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdLoadFailedEvent"); + _onBannerAdLoadFailedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdLoadFailedEvent"); + _onBannerAdLoadFailedEventV2 -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdClickedEvent"); + _onBannerAdClickedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdClickedEvent"); + _onBannerAdClickedEventV2 -= value; + } + } + + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnBannerAdRevenuePaidEvent"); + _onBannerAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdRevenuePaidEvent"); + _onBannerAdRevenuePaidEvent -= value; + } + } + + /// + /// Fired when an Ad Review Creative ID has been generated. + /// The parameters returned are the adUnitIdentifier, adReviewCreativeId, and adInfo in that respective order. + /// + public static event Action OnAdReviewCreativeIdGeneratedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdReviewCreativeIdGeneratedEvent"); + _onBannerAdReviewCreativeIdGeneratedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdReviewCreativeIdGeneratedEvent"); + _onBannerAdReviewCreativeIdGeneratedEvent -= value; + } + } + + public static event Action OnAdExpandedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdExpandedEvent"); + _onBannerAdExpandedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdExpandedEvent"); + _onBannerAdExpandedEventV2 -= value; + } + } + + public static event Action OnAdCollapsedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdCollapsedEvent"); + _onBannerAdCollapsedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdCollapsedEvent"); + _onBannerAdCollapsedEventV2 -= value; + } + } + } + + private static Action _onMRecAdLoadedEventV2; + private static Action _onMRecAdLoadFailedEventV2; + private static Action _onMRecAdClickedEventV2; + private static Action _onMRecAdRevenuePaidEvent; + private static Action _onMRecAdReviewCreativeIdGeneratedEvent; + private static Action _onMRecAdExpandedEventV2; + private static Action _onMRecAdCollapsedEventV2; + + public class MRec + { + public static event Action OnAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdLoadedEvent"); + _onMRecAdLoadedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdLoadedEvent"); + _onMRecAdLoadedEventV2 -= value; + } + } + + public static event Action OnAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdLoadFailedEvent"); + _onMRecAdLoadFailedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdLoadFailedEvent"); + _onMRecAdLoadFailedEventV2 -= value; + } + } + + public static event Action OnAdClickedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdClickedEvent"); + _onMRecAdClickedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdClickedEvent"); + _onMRecAdClickedEventV2 -= value; + } + } + + public static event Action OnAdRevenuePaidEvent + { + add + { + LogSubscribedToEvent("OnMRecAdRevenuePaidEvent"); + _onMRecAdRevenuePaidEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdRevenuePaidEvent"); + _onMRecAdRevenuePaidEvent -= value; + } + } + + /// + /// Fired when an Ad Review Creative ID has been generated. + /// The parameters returned are the adUnitIdentifier, adReviewCreativeId, and adInfo in that respective order. + /// + public static event Action OnAdReviewCreativeIdGeneratedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdReviewCreativeIdGeneratedEvent"); + _onMRecAdReviewCreativeIdGeneratedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdReviewCreativeIdGeneratedEvent"); + _onMRecAdReviewCreativeIdGeneratedEvent -= value; + } + } + + public static event Action OnAdExpandedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdExpandedEvent"); + _onMRecAdExpandedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdExpandedEvent"); + _onMRecAdExpandedEventV2 -= value; + } + } + + public static event Action OnAdCollapsedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdCollapsedEvent"); + _onMRecAdCollapsedEventV2 += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdCollapsedEvent"); + _onMRecAdCollapsedEventV2 -= value; + } + } + } + + private static Action _onBannerAdLoadedEvent; + private static Action _onBannerAdLoadFailedEvent; + private static Action _onBannerAdClickedEvent; + private static Action _onBannerAdExpandedEvent; + private static Action _onBannerAdCollapsedEvent; + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Banner.OnAdLoadedEvent` instead.")] + public static event Action OnBannerAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdLoadedEvent"); + _onBannerAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdLoadedEvent"); + _onBannerAdLoadedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Banner.OnAdLoadFailedEvent` instead.")] + public static event Action OnBannerAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdLoadFailedEvent"); + _onBannerAdLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdLoadFailedEvent"); + _onBannerAdLoadFailedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Banner.OnAdClickedEvent` instead.")] + public static event Action OnBannerAdClickedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdClickedEvent"); + _onBannerAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdClickedEvent"); + _onBannerAdClickedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Banner.OnAdExpandedEvent` instead.")] + public static event Action OnBannerAdExpandedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdExpandedEvent"); + _onBannerAdExpandedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdExpandedEvent"); + _onBannerAdExpandedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Banner.OnAdCollapsedEvent` instead.")] + public static event Action OnBannerAdCollapsedEvent + { + add + { + LogSubscribedToEvent("OnBannerAdCollapsedEvent"); + _onBannerAdCollapsedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnBannerAdCollapsedEvent"); + _onBannerAdCollapsedEvent -= value; + } + } + + private static Action _onMRecAdLoadedEvent; + private static Action _onMRecAdLoadFailedEvent; + private static Action _onMRecAdClickedEvent; + private static Action _onMRecAdExpandedEvent; + private static Action _onMRecAdCollapsedEvent; + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.MRec.OnAdLoadedEvent` instead.")] + public static event Action OnMRecAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdLoadedEvent"); + _onMRecAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdLoadedEvent"); + _onMRecAdLoadedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.MRec.OnAdLoadFailedEvent` instead.")] + public static event Action OnMRecAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdLoadFailedEvent"); + _onMRecAdLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdLoadFailedEvent"); + _onMRecAdLoadFailedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.MRec.OnAdClickedEvent` instead.")] + public static event Action OnMRecAdClickedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdClickedEvent"); + _onMRecAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdClickedEvent"); + _onMRecAdClickedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.MRec.OnAdExpandedEvent` instead.")] + public static event Action OnMRecAdExpandedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdExpandedEvent"); + _onMRecAdExpandedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdExpandedEvent"); + _onMRecAdExpandedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.MRec.OnAdCollapsedEvent` instead.")] + public static event Action OnMRecAdCollapsedEvent + { + add + { + LogSubscribedToEvent("OnMRecAdCollapsedEvent"); + _onMRecAdCollapsedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnMRecAdCollapsedEvent"); + _onMRecAdCollapsedEvent -= value; + } + } + + private static Action _onInterstitialAdLoadedEvent; + private static Action _onInterstitialLoadFailedEvent; + private static Action _onInterstitialAdDisplayedEvent; + private static Action _onInterstitialAdFailedToDisplayEvent; + private static Action _onInterstitialAdClickedEvent; + private static Action _onInterstitialAdHiddenEvent; + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdLoadedEvent` instead.")] + public static event Action OnInterstitialLoadedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialLoadedEvent"); + _onInterstitialAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialLoadedEvent"); + _onInterstitialAdLoadedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent` instead.")] + public static event Action OnInterstitialLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialLoadFailedEvent"); + _onInterstitialLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialLoadFailedEvent"); + _onInterstitialLoadFailedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdHiddenEvent` instead.")] + public static event Action OnInterstitialHiddenEvent + { + add + { + LogSubscribedToEvent("OnInterstitialHiddenEvent"); + _onInterstitialAdHiddenEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialHiddenEvent"); + _onInterstitialAdHiddenEvent -= value; + } + } + + // Fired when an interstitial ad is displayed (may not be received by Unity until the interstitial closes) + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdDisplayedEvent` instead.")] + public static event Action OnInterstitialDisplayedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialDisplayedEvent"); + _onInterstitialAdDisplayedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialDisplayedEvent"); + _onInterstitialAdDisplayedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent` instead.")] + public static event Action OnInterstitialAdFailedToDisplayEvent + { + add + { + LogSubscribedToEvent("OnInterstitialAdFailedToDisplayEvent"); + _onInterstitialAdFailedToDisplayEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialAdFailedToDisplayEvent"); + _onInterstitialAdFailedToDisplayEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Interstitial.OnAdClickedEvent` instead.")] + public static event Action OnInterstitialClickedEvent + { + add + { + LogSubscribedToEvent("OnInterstitialClickedEvent"); + _onInterstitialAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnInterstitialClickedEvent"); + _onInterstitialAdClickedEvent -= value; + } + } + + private static Action _onRewardedAdLoadedEvent; + private static Action _onRewardedAdLoadFailedEvent; + private static Action _onRewardedAdDisplayedEvent; + private static Action _onRewardedAdFailedToDisplayEvent; + private static Action _onRewardedAdClickedEvent; + private static Action _onRewardedAdReceivedRewardEvent; + private static Action _onRewardedAdHiddenEvent; + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdLoadedEvent` instead.")] + public static event Action OnRewardedAdLoadedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdLoadedEvent"); + _onRewardedAdLoadedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdLoadedEvent"); + _onRewardedAdLoadedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent` instead.")] + public static event Action OnRewardedAdLoadFailedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdLoadFailedEvent"); + _onRewardedAdLoadFailedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdLoadFailedEvent"); + _onRewardedAdLoadFailedEvent -= value; + } + } + + // Fired when an rewarded ad is displayed (may not be received by Unity until the rewarded ad closes) + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent` instead.")] + public static event Action OnRewardedAdDisplayedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdDisplayedEvent"); + _onRewardedAdDisplayedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdDisplayedEvent"); + _onRewardedAdDisplayedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdHiddenEvent` instead.")] + public static event Action OnRewardedAdHiddenEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdHiddenEvent"); + _onRewardedAdHiddenEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdHiddenEvent"); + _onRewardedAdHiddenEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdClickedEvent` instead.")] + public static event Action OnRewardedAdClickedEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdClickedEvent"); + _onRewardedAdClickedEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdClickedEvent"); + _onRewardedAdClickedEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent` instead.")] + public static event Action OnRewardedAdFailedToDisplayEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdFailedToDisplayEvent"); + _onRewardedAdFailedToDisplayEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdFailedToDisplayEvent"); + _onRewardedAdFailedToDisplayEvent -= value; + } + } + + [Obsolete("This callback has been deprecated. Please use `MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent` instead.")] + public static event Action OnRewardedAdReceivedRewardEvent + { + add + { + LogSubscribedToEvent("OnRewardedAdReceivedRewardEvent"); + _onRewardedAdReceivedRewardEvent += value; + } + remove + { + LogUnsubscribedToEvent("OnRewardedAdReceivedRewardEvent"); + _onRewardedAdReceivedRewardEvent -= value; + } + } + + public static void ForwardEvent(string eventPropsStr) + { + var eventProps = Json.Deserialize(eventPropsStr) as Dictionary; + if (eventProps == null) + { + MaxSdkLogger.E("Failed to forward event due to invalid event data"); + return; + } + + var keepInBackground = MaxSdkUtils.GetBoolFromDictionary(eventProps, "keepInBackground", false); + var eventName = MaxSdkUtils.GetStringFromDictionary(eventProps, "name", ""); + if (eventName == "OnInitialCallbackEvent") + { + MaxSdkLogger.D("Initial background callback."); + } + else if (eventName == "OnSdkInitializedEvent") + { + var sdkConfiguration = MaxSdkBase.SdkConfiguration.Create(eventProps); + InvokeEvent(_onSdkInitializedEvent, sdkConfiguration, eventName, keepInBackground); + } + else if (eventName == "OnCmpCompletedEvent") + { + var errorProps = MaxSdkUtils.GetDictionaryFromDictionary(eventProps, "error"); + MaxCmpService.NotifyCompletedIfNeeded(errorProps); + } + else if (eventName == "OnApplicationStateChanged") + { + var isPaused = MaxSdkUtils.GetBoolFromDictionary(eventProps, "isPaused"); + InvokeEvent(_onApplicationStateChangedEvent, isPaused, eventName, keepInBackground); + } + // Ad Events + else + { + var adInfo = new MaxSdkBase.AdInfo(eventProps); + var adUnitIdentifier = MaxSdkUtils.GetStringFromDictionary(eventProps, "adUnitId", ""); + if (eventName == "OnBannerAdLoadedEvent") + { + InvokeEvent(_onBannerAdLoadedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onBannerAdLoadedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdLoadFailedEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onBannerAdLoadFailedEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onBannerAdLoadFailedEventV2, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdClickedEvent") + { + InvokeEvent(_onBannerAdClickedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onBannerAdClickedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdRevenuePaidEvent") + { + InvokeEvent(_onBannerAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdReviewCreativeIdGeneratedEvent") + { + var adReviewCreativeId = MaxSdkUtils.GetStringFromDictionary(eventProps, "adReviewCreativeId", ""); + InvokeEvent(_onBannerAdReviewCreativeIdGeneratedEvent, adUnitIdentifier, adReviewCreativeId, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdExpandedEvent") + { + InvokeEvent(_onBannerAdExpandedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onBannerAdExpandedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnBannerAdCollapsedEvent") + { + InvokeEvent(_onBannerAdCollapsedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onBannerAdCollapsedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdLoadedEvent") + { + InvokeEvent(_onMRecAdLoadedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onMRecAdLoadedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdLoadFailedEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onMRecAdLoadFailedEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onMRecAdLoadFailedEventV2, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdClickedEvent") + { + InvokeEvent(_onMRecAdClickedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onMRecAdClickedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdRevenuePaidEvent") + { + InvokeEvent(_onMRecAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdReviewCreativeIdGeneratedEvent") + { + var adReviewCreativeId = MaxSdkUtils.GetStringFromDictionary(eventProps, "adReviewCreativeId", ""); + InvokeEvent(_onMRecAdReviewCreativeIdGeneratedEvent, adUnitIdentifier, adReviewCreativeId, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdExpandedEvent") + { + InvokeEvent(_onMRecAdExpandedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onMRecAdExpandedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnMRecAdCollapsedEvent") + { + InvokeEvent(_onMRecAdCollapsedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onMRecAdCollapsedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialLoadedEvent") + { + InvokeEvent(_onInterstitialAdLoadedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onInterstitialAdLoadedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialLoadFailedEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onInterstitialLoadFailedEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onInterstitialAdLoadFailedEventV2, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialHiddenEvent") + { + InvokeEvent(_onInterstitialAdHiddenEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onInterstitialAdHiddenEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialDisplayedEvent") + { + InvokeEvent(_onInterstitialAdDisplayedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onInterstitialAdDisplayedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialAdFailedToDisplayEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onInterstitialAdFailedToDisplayEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onInterstitialAdFailedToDisplayEventV2, adUnitIdentifier, errorInfo, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialClickedEvent") + { + InvokeEvent(_onInterstitialAdClickedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onInterstitialAdClickedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialAdRevenuePaidEvent") + { + InvokeEvent(_onInterstitialAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnInterstitialAdReviewCreativeIdGeneratedEvent") + { + var adReviewCreativeId = MaxSdkUtils.GetStringFromDictionary(eventProps, "adReviewCreativeId", ""); + InvokeEvent(_onInterstitialAdReviewCreativeIdGeneratedEvent, adUnitIdentifier, adReviewCreativeId, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdLoadedEvent") + { + InvokeEvent(_onAppOpenAdLoadedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdLoadFailedEvent") + { + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onAppOpenAdLoadFailedEvent, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdHiddenEvent") + { + InvokeEvent(_onAppOpenAdHiddenEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdDisplayedEvent") + { + InvokeEvent(_onAppOpenAdDisplayedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdFailedToDisplayEvent") + { + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onAppOpenAdFailedToDisplayEvent, adUnitIdentifier, errorInfo, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdClickedEvent") + { + InvokeEvent(_onAppOpenAdClickedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnAppOpenAdRevenuePaidEvent") + { + InvokeEvent(_onAppOpenAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdLoadedEvent") + { + InvokeEvent(_onRewardedAdLoadedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onRewardedAdLoadedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdLoadFailedEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onRewardedAdLoadFailedEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onRewardedAdLoadFailedEventV2, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdDisplayedEvent") + { + InvokeEvent(_onRewardedAdDisplayedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onRewardedAdDisplayedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdHiddenEvent") + { + InvokeEvent(_onRewardedAdHiddenEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onRewardedAdHiddenEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdClickedEvent") + { + InvokeEvent(_onRewardedAdClickedEvent, adUnitIdentifier, eventName, keepInBackground); + InvokeEvent(_onRewardedAdClickedEventV2, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdRevenuePaidEvent") + { + InvokeEvent(_onRewardedAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdReviewCreativeIdGeneratedEvent") + { + var adReviewCreativeId = MaxSdkUtils.GetStringFromDictionary(eventProps, "adReviewCreativeId", ""); + InvokeEvent(_onRewardedAdReviewCreativeIdGeneratedEvent, adUnitIdentifier, adReviewCreativeId, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdFailedToDisplayEvent") + { + var errorCode = MaxSdkUtils.GetIntFromDictionary(eventProps, "errorCode", -1); + InvokeEvent(_onRewardedAdFailedToDisplayEvent, adUnitIdentifier, errorCode, eventName, keepInBackground); + + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + InvokeEvent(_onRewardedAdFailedToDisplayEventV2, adUnitIdentifier, errorInfo, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedAdReceivedRewardEvent") + { + var reward = new MaxSdkBase.Reward + { + Label = MaxSdkUtils.GetStringFromDictionary(eventProps, "rewardLabel", ""), + Amount = MaxSdkUtils.GetIntFromDictionary(eventProps, "rewardAmount", 0) + }; + + InvokeEvent(_onRewardedAdReceivedRewardEvent, adUnitIdentifier, reward, eventName, keepInBackground); + InvokeEvent(_onRewardedAdReceivedRewardEventV2, adUnitIdentifier, reward, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdLoadedEvent") + { + InvokeEvent(_onRewardedInterstitialAdLoadedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdLoadFailedEvent") + { + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + + InvokeEvent(_onRewardedInterstitialAdLoadFailedEvent, adUnitIdentifier, errorInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdDisplayedEvent") + { + InvokeEvent(_onRewardedInterstitialAdDisplayedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdHiddenEvent") + { + InvokeEvent(_onRewardedInterstitialAdHiddenEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdClickedEvent") + { + InvokeEvent(_onRewardedInterstitialAdClickedEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdRevenuePaidEvent") + { + InvokeEvent(_onRewardedInterstitialAdRevenuePaidEvent, adUnitIdentifier, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdReviewCreativeIdGeneratedEvent") + { + var adReviewCreativeId = MaxSdkUtils.GetStringFromDictionary(eventProps, "adReviewCreativeId", ""); + InvokeEvent(_onRewardedInterstitialAdReviewCreativeIdGeneratedEvent, adUnitIdentifier, adReviewCreativeId, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdFailedToDisplayEvent") + { + var errorInfo = new MaxSdkBase.ErrorInfo(eventProps); + + InvokeEvent(_onRewardedInterstitialAdFailedToDisplayEvent, adUnitIdentifier, errorInfo, adInfo, eventName, keepInBackground); + } + else if (eventName == "OnRewardedInterstitialAdReceivedRewardEvent") + { + var reward = new MaxSdkBase.Reward + { + Label = MaxSdkUtils.GetStringFromDictionary(eventProps, "rewardLabel", ""), + Amount = MaxSdkUtils.GetIntFromDictionary(eventProps, "rewardAmount", 0) + }; + + InvokeEvent(_onRewardedInterstitialAdReceivedRewardEvent, adUnitIdentifier, reward, adInfo, eventName, keepInBackground); + } + else + { + MaxSdkLogger.UserWarning("Unknown MAX Ads event fired: " + eventName); + } + } + } + +#if UNITY_EDITOR + public static void EmitSdkInitializedEvent() + { + if (_onSdkInitializedEvent == null) return; + + _onSdkInitializedEvent(MaxSdkBase.SdkConfiguration.CreateEmpty()); + } +#endif + + private static void InvokeEvent(Action evt, string eventName, bool keepInBackground) + { + if (!CanInvokeEvent(evt)) return; + + MaxSdkLogger.UserDebug("Invoking event: " + eventName); + if (ShouldInvokeInBackground(keepInBackground)) + { + try + { + evt(); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Caught exception in publisher event: " + eventName + ", exception: " + exception); + MaxSdkLogger.LogException(exception); + } + } + else + { + MaxEventExecutor.ExecuteOnMainThread(evt, eventName); + } + } + + private static void InvokeEvent(Action evt, T param, string eventName, bool keepInBackground) + { + if (!CanInvokeEvent(evt)) return; + + MaxSdkLogger.UserDebug("Invoking event: " + eventName + ". Param: " + param); + if (ShouldInvokeInBackground(keepInBackground)) + { + try + { + evt(param); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Caught exception in publisher event: " + eventName + ", exception: " + exception); + MaxSdkLogger.LogException(exception); + } + } + else + { + MaxEventExecutor.ExecuteOnMainThread(() => evt(param), eventName); + } + } + + private static void InvokeEvent(Action evt, T1 param1, T2 param2, string eventName, bool keepInBackground) + { + if (!CanInvokeEvent(evt)) return; + + MaxSdkLogger.UserDebug("Invoking event: " + eventName + ". Params: " + param1 + ", " + param2); + if (ShouldInvokeInBackground(keepInBackground)) + { + try + { + evt(param1, param2); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Caught exception in publisher event: " + eventName + ", exception: " + exception); + MaxSdkLogger.LogException(exception); + } + } + else + { + MaxEventExecutor.ExecuteOnMainThread(() => evt(param1, param2), eventName); + } + } + + private static void InvokeEvent(Action evt, T1 param1, T2 param2, T3 param3, string eventName, bool keepInBackground) + { + if (!CanInvokeEvent(evt)) return; + + MaxSdkLogger.UserDebug("Invoking event: " + eventName + ". Params: " + param1 + ", " + param2 + ", " + param3); + if (ShouldInvokeInBackground(keepInBackground)) + { + try + { + evt(param1, param2, param3); + } + catch (Exception exception) + { + MaxSdkLogger.UserError("Caught exception in publisher event: " + eventName + ", exception: " + exception); + MaxSdkLogger.LogException(exception); + } + } + else + { + MaxEventExecutor.ExecuteOnMainThread(() => evt(param1, param2, param3), eventName); + } + } + + private static bool CanInvokeEvent(Delegate evt) + { + if (evt == null) return false; + + // Check that publisher is not over-subscribing + if (evt.GetInvocationList().Length > 5) + { + MaxSdkLogger.UserWarning("Ads Event (" + evt + ") has over 5 subscribers. Please make sure you are properly un-subscribing to actions!!!"); + } + + return true; + } + + private static bool ShouldInvokeInBackground(bool keepInBackground) + { + return MaxSdkBase.InvokeEventsOnUnityMainThread == null ? keepInBackground : !MaxSdkBase.InvokeEventsOnUnityMainThread.Value; + } + + private static void LogSubscribedToEvent(string eventName) + { + MaxSdkLogger.D("Listener has been added to callback: " + eventName); + } + + private static void LogUnsubscribedToEvent(string eventName) + { + MaxSdkLogger.D("Listener has been removed from callback: " + eventName); + } + +#if UNITY_EDITOR && UNITY_2019_2_OR_NEWER + /// + /// Resets static event handlers so they still get reset even if Domain Reloading is disabled + /// + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + private static void ResetOnDomainReload() + { + _onSdkInitializedEvent = null; + + _onInterstitialAdLoadedEventV2 = null; + _onInterstitialAdLoadFailedEventV2 = null; + _onInterstitialAdDisplayedEventV2 = null; + _onInterstitialAdFailedToDisplayEventV2 = null; + _onInterstitialAdClickedEventV2 = null; + _onInterstitialAdRevenuePaidEvent = null; + _onInterstitialAdReviewCreativeIdGeneratedEvent = null; + _onInterstitialAdHiddenEventV2 = null; + + _onAppOpenAdLoadedEvent = null; + _onAppOpenAdLoadFailedEvent = null; + _onAppOpenAdDisplayedEvent = null; + _onAppOpenAdFailedToDisplayEvent = null; + _onAppOpenAdClickedEvent = null; + _onAppOpenAdRevenuePaidEvent = null; + _onAppOpenAdHiddenEvent = null; + + _onRewardedAdLoadedEventV2 = null; + _onRewardedAdLoadFailedEventV2 = null; + _onRewardedAdDisplayedEventV2 = null; + _onRewardedAdFailedToDisplayEventV2 = null; + _onRewardedAdClickedEventV2 = null; + _onRewardedAdRevenuePaidEvent = null; + _onRewardedAdReviewCreativeIdGeneratedEvent = null; + _onRewardedAdReceivedRewardEventV2 = null; + _onRewardedAdHiddenEventV2 = null; + + _onRewardedInterstitialAdLoadedEvent = null; + _onRewardedInterstitialAdLoadFailedEvent = null; + _onRewardedInterstitialAdDisplayedEvent = null; + _onRewardedInterstitialAdFailedToDisplayEvent = null; + _onRewardedInterstitialAdClickedEvent = null; + _onRewardedInterstitialAdRevenuePaidEvent = null; + _onRewardedInterstitialAdReviewCreativeIdGeneratedEvent = null; + _onRewardedInterstitialAdReceivedRewardEvent = null; + _onRewardedInterstitialAdHiddenEvent = null; + + _onBannerAdLoadedEventV2 = null; + _onBannerAdLoadFailedEventV2 = null; + _onBannerAdClickedEventV2 = null; + _onBannerAdRevenuePaidEvent = null; + _onBannerAdReviewCreativeIdGeneratedEvent = null; + _onBannerAdExpandedEventV2 = null; + _onBannerAdCollapsedEventV2 = null; + + _onMRecAdLoadedEventV2 = null; + _onMRecAdLoadFailedEventV2 = null; + _onMRecAdClickedEventV2 = null; + _onMRecAdRevenuePaidEvent = null; + _onMRecAdReviewCreativeIdGeneratedEvent = null; + _onMRecAdExpandedEventV2 = null; + _onMRecAdCollapsedEventV2 = null; + + _onBannerAdLoadedEvent = null; + _onBannerAdLoadFailedEvent = null; + _onBannerAdClickedEvent = null; + _onBannerAdExpandedEvent = null; + _onBannerAdCollapsedEvent = null; + + _onMRecAdLoadedEvent = null; + _onMRecAdLoadFailedEvent = null; + _onMRecAdClickedEvent = null; + _onMRecAdExpandedEvent = null; + _onMRecAdCollapsedEvent = null; + + _onInterstitialAdLoadedEvent = null; + _onInterstitialLoadFailedEvent = null; + _onInterstitialAdDisplayedEvent = null; + _onInterstitialAdFailedToDisplayEvent = null; + _onInterstitialAdClickedEvent = null; + _onInterstitialAdHiddenEvent = null; + + _onRewardedAdLoadedEvent = null; + _onRewardedAdLoadFailedEvent = null; + _onRewardedAdDisplayedEvent = null; + _onRewardedAdFailedToDisplayEvent = null; + _onRewardedAdClickedEvent = null; + _onRewardedAdReceivedRewardEvent = null; + _onRewardedAdHiddenEvent = null; + } +#endif +} diff --git a/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs.meta b/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs.meta new file mode 100644 index 0000000..dd08049 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkCallbacks.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 4dc129a60049645f7a492a0a658a6c22 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdkCallbacks.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdkLogger.cs b/Assets/MaxSdk/Scripts/MaxSdkLogger.cs new file mode 100644 index 0000000..9acac25 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkLogger.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; + +public class MaxSdkLogger +{ + private const string SdkTag = "AppLovin MAX"; + public const string KeyVerboseLoggingEnabled = "com.applovin.verbose_logging_enabled"; + + /// + /// Log debug messages. + /// + public static void UserDebug(string message) + { + if (MaxSdk.DisableAllLogs) return; + + Debug.Log("Debug [" + SdkTag + "] " + message); + } + + /// + /// Log debug messages when verbose logging is enabled. + /// + /// Verbose logging can be enabled by calling or via the Integration Manager for build time logs. + /// + public static void D(string message) + { + if (MaxSdk.DisableAllLogs && !MaxSdk.IsVerboseLoggingEnabled()) return; + + Debug.Log("Debug [" + SdkTag + "] " + message); + } + + /// + /// Log warning messages. + /// + public static void UserWarning(string message) + { + if (MaxSdk.DisableAllLogs) return; + + Debug.LogWarning("Warning [" + SdkTag + "] " + message); + } + + /// + /// Log warning messages when verbose logging is enabled. + /// + /// Verbose logging can be enabled by calling or via the Integration Manager for build time logs. + /// + public static void W(string message) + { + if (MaxSdk.DisableAllLogs && !MaxSdk.IsVerboseLoggingEnabled()) return; + + Debug.LogWarning("Warning [" + SdkTag + "] " + message); + } + + /// + /// Log error messages. + /// + public static void UserError(string message) + { + if (MaxSdk.DisableAllLogs) return; + + Debug.LogError("Error [" + SdkTag + "] " + message); + } + + /// + /// Log error messages when verbose logging is enabled. + /// + /// Verbose logging can be enabled by calling or via the Integration Manager for build time logs. + /// + public static void E(string message) + { + if (MaxSdk.DisableAllLogs && !MaxSdk.IsVerboseLoggingEnabled()) return; + + Debug.LogError("Error [" + SdkTag + "] " + message); + } + + /// + /// Log exceptions. + /// + public static void LogException(Exception exception) + { + if (MaxSdk.DisableAllLogs) return; + + Debug.LogException(exception); + } +} diff --git a/Assets/MaxSdk/Scripts/MaxSdkLogger.cs.meta b/Assets/MaxSdk/Scripts/MaxSdkLogger.cs.meta new file mode 100644 index 0000000..01a3427 --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkLogger.cs.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: ff2b160afdfd4a74b731954323772a90 +labels: +- al_max +- al_max_export_path-MaxSdk/Scripts/MaxSdkLogger.cs +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/MaxSdk/Scripts/MaxSdkUnityEditor.cs b/Assets/MaxSdk/Scripts/MaxSdkUnityEditor.cs new file mode 100644 index 0000000..b75c7dc --- /dev/null +++ b/Assets/MaxSdk/Scripts/MaxSdkUnityEditor.cs @@ -0,0 +1,1381 @@ +// This script is used for Unity Editor and non Android or iOS platforms. + +#if UNITY_EDITOR || !(UNITY_ANDROID || UNITY_IPHONE || UNITY_IOS) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using AppLovinMax.Internal; +using AppLovinMax.ThirdParty.MiniJson; +#if UNITY_EDITOR +using UnityEditor; +#endif +using UnityEngine; +using UnityEngine.UI; +using Object = UnityEngine.Object; + +/// +/// Unity Editor AppLovin MAX Unity Plugin implementation +/// +public class MaxSdkUnityEditor : MaxSdkBase +{ + private static bool _isInitialized; + private static bool _hasUserConsent = false; + private static bool _isUserConsentSet = false; + private static bool _doNotSell = false; + private static bool _isDoNotSellSet = false; + private static bool _showStubAds = true; + private static SafeAreaInsets _safeAreaInsets = new SafeAreaInsets(new int[] {0, 0, 0, 0}); + private static readonly HashSet RequestedAdUnits = new HashSet(); + private static readonly HashSet ReadyAdUnits = new HashSet(); + private static readonly Dictionary StubBanners = new Dictionary(); + + // Ad Placement + private static readonly Dictionary BannerPlacements = new Dictionary(); + private static readonly Dictionary MRecPlacements = new Dictionary(); + + [RuntimeInitializeOnLoadMethod] + public static void InitializeMaxSdkUnityEditorOnLoad() + { + // Unity destroys the stub banners each time the editor exits play mode, but the StubBanners stays in memory if Enter Play Mode settings is enabled. + StubBanners.Clear(); + } + + #region Initialization + + /// + /// Initialize the default instance of AppLovin SDK. + /// + /// Please make sure that application's Android manifest or Info.plist includes the AppLovin SDK key. + /// + /// + /// OPTIONAL: Set the MAX ad unit ids to be used for this instance of the SDK. 3rd-party SDKs will be initialized with the credentials configured for these ad unit ids. + /// This should only be used if you have different sets of ad unit ids / credentials for the same package name. + /// + public static void InitializeSdk(string[] adUnitIds = null) + { + _isInitialized = true; + + // Slight delay to emulate the SDK initializing + ExecuteWithDelay(0.1f, () => + { + _isInitialized = true; + +#if UNITY_EDITOR + MaxSdkCallbacks.EmitSdkInitializedEvent(); +#endif + }); + } + + /// + /// Check if the SDK has been initialized. + /// + /// True if SDK has been initialized + public static bool IsInitialized() + { + return _isInitialized; + } + + /// + /// Prevent stub ads from showing in the Unity Editor + /// + public static void DisableStubAds() + { + _showStubAds = false; + } + + #endregion + + #region User Info + + /// + /// Set an identifier for the current user. This identifier will be tied to SDK events and our optional S2S postbacks. + /// + /// If you're using reward validation, you can optionally set an identifier to be included with currency validation postbacks. + /// For example, a username or email. We'll include this in the postback when we ping your currency endpoint from our server. + /// + /// + /// The user identifier to be set. Must not be null. + public static void SetUserId(string userId) { } + + /// + /// Set the . + /// + /// The segment collection to be set. Must not be {@code null} + public static void SetSegmentCollection(MaxSegmentCollection segmentCollection) + { + if (_isInitialized) + { + MaxSdkLogger.UserError("Segment collection must be set before MAX SDK is initialized "); + } + } + + #endregion + + #region MAX + + /// + /// Returns the list of available mediation networks. + /// + /// Please call this method after the SDK has initialized. + /// + public static List GetAvailableMediatedNetworks() + { + return new List(); + } + + /// + /// Present the mediation debugger UI. + /// This debugger tool provides the status of your integration for each third-party ad network. + /// + /// Please call this method after the SDK has initialized. + /// + public static void ShowMediationDebugger() + { + if (!_isInitialized) + { + MaxSdkLogger.UserWarning("The mediation debugger cannot be shown before the MAX SDK has been initialized." + + "\nCall 'MaxSdk.InitializeSdk();' and listen for 'MaxSdkCallbacks.OnSdkInitializedEvent' before showing the mediation debugger."); + } + else + { + MaxSdkLogger.UserWarning("The mediation debugger cannot be shown in the Unity Editor. Please export the project to Android or iOS first."); + } + } + + /// + /// Present the mediation debugger UI. + /// + /// Please call this method after the SDK has initialized. + /// + public static void ShowCreativeDebugger() + { + if (!_isInitialized) + { + MaxSdkLogger.UserWarning("The creative debugger cannot be shown before the MAX SDK has been initialized." + + "\nCall 'MaxSdk.InitializeSdk();' and listen for 'MaxSdkCallbacks.OnSdkInitializedEvent' before showing the mediation debugger."); + } + else + { + MaxSdkLogger.UserWarning("The creative debugger cannot be shown in the Unity Editor. Please export the project to Android or iOS first."); + } + } + + /// + /// Returns the arbitrary ad value for a given ad unit identifier with key. Returns null if no ad is loaded. + /// + /// Ad unit identifier for which to get the ad value for. Must not be null. + /// Ad value key. Must not be null. + /// Arbitrary ad value for a given key, or null if no ad is loaded. + public static string GetAdValue(string adUnitIdentifier, string key) + { + return ""; + } + + #endregion + + #region Privacy + + /// + /// Get the SDK configuration for this user. + /// + /// Note: This method should be called only after SDK has been initialized. + /// + public static SdkConfiguration GetSdkConfiguration() + { + return SdkConfiguration.CreateEmpty(); + } + + /// + /// Set whether or not user has provided consent for information sharing with AppLovin and other providers. + /// + /// true if the user has provided consent for information sharing with AppLovin. false by default. + public static void SetHasUserConsent(bool hasUserConsent) + { + _hasUserConsent = hasUserConsent; + _isUserConsentSet = true; + } + + /// + /// Check if user has provided consent for information sharing with AppLovin and other providers. + /// + /// true if user has provided consent for information sharing. false if the user declined to share information or the consent value has not been set . + public static bool HasUserConsent() + { + return _hasUserConsent; + } + + /// + /// Check if user has set consent for information sharing. + /// + /// true if user has set a value of consent for information sharing. + public static bool IsUserConsentSet() + { + return _isUserConsentSet; + } + + /// + /// Set whether or not user has opted out of the sale of their personal information. + /// + /// true if the user has opted out of the sale of their personal information. + public static void SetDoNotSell(bool doNotSell) + { + _doNotSell = doNotSell; + _isDoNotSellSet = true; + } + + /// + /// Check if the user has opted out of the sale of their personal information. + /// + /// true if the user has opted out of the sale of their personal information. false if the user opted in to the sell of their personal information or the value has not been set . + public static bool IsDoNotSell() + { + return _doNotSell; + } + + /// + /// Check if the user has set the option to sell their personal information. + /// + /// true if user has chosen an option to sell their personal information. + public static bool IsDoNotSellSet() + { + return _isDoNotSellSet; + } + + #endregion + + #region Banners + + /// + /// Create a new banner. + /// + /// Ad unit identifier of the banner to create. Must not be null. + /// Banner position. Must not be null. + public static void CreateBanner(string adUnitIdentifier, BannerPosition bannerPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create banner"); + RequestAdUnit(adUnitIdentifier); + + if (_showStubAds && !StubBanners.ContainsKey(adUnitIdentifier)) + { + CreateStubBanner(adUnitIdentifier, bannerPosition); + } + + ExecuteWithDelay(1f, () => + { + var placement = MaxSdkUtils.GetStringFromDictionary(BannerPlacements, adUnitIdentifier); + var eventProps = Json.Serialize(CreateBaseEventPropsDictionary("OnBannerAdLoadedEvent", adUnitIdentifier, placement)); + MaxSdkCallbacks.ForwardEvent(eventProps); + }); + } + + /// + /// Create a new banner with a custom position. + /// + /// Ad unit identifier of the banner to create. Must not be null. + /// The X coordinate (horizontal position) of the banner relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the banner relative to the top left corner of the screen. + /// + /// The banner is placed within the safe area of the screen. You can use this to get the absolute position of the banner on screen. + /// + public static void CreateBanner(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create banner"); + RequestAdUnit(adUnitIdentifier); + + // TODO: Add stub ads support + } + + private static void CreateStubBanner(string adUnitIdentifier, BannerPosition bannerPosition) + { +#if UNITY_EDITOR + // Only support BottomCenter and TopCenter for now + var bannerPrefabName = bannerPosition == BannerPosition.BottomCenter ? "BannerBottom" : "BannerTop"; + var prefabPath = MaxSdkUtils.GetAssetPathForExportPath("MaxSdk/Prefabs/" + bannerPrefabName + ".prefab"); + var bannerPrefab = AssetDatabase.LoadAssetAtPath(prefabPath); + var stubBanner = Object.Instantiate(bannerPrefab, Vector3.zero, Quaternion.identity); + stubBanner.SetActive(false); // Hidden by default + Object.DontDestroyOnLoad(stubBanner); + + var bannerText = stubBanner.GetComponentInChildren(); + bannerText.text += ":\n" + adUnitIdentifier; + + StubBanners.Add(adUnitIdentifier, stubBanner); +#endif + } + + /// + /// Load a new banner ad. + /// NOTE: The method loads the first banner ad and initiates an automated banner refresh process. + /// You only need to call this method if you pause banner refresh. + /// + /// Ad unit identifier of the banner to load. Must not be null. + public static void LoadBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load banner"); + + ExecuteWithDelay(1f, () => + { + var placement = MaxSdkUtils.GetStringFromDictionary(BannerPlacements, adUnitIdentifier); + var eventProps = Json.Serialize(CreateBaseEventPropsDictionary("OnBannerAdLoadedEvent", adUnitIdentifier, placement)); + MaxSdkCallbacks.ForwardEvent(eventProps); + }); + } + + /// + /// Set the banner placement for an ad unit identifier to tie the future ad events to. + /// + /// Ad unit identifier of the banner to set the placement for. Must not be null. + /// Placement to set + public static void SetBannerPlacement(string adUnitIdentifier, string placement) + { + BannerPlacements[adUnitIdentifier] = placement; + MaxSdkLogger.UserDebug("Setting banner placement to '" + placement + "' for ad unit id '" + adUnitIdentifier + "'"); + } + + /// + /// Starts or resumes auto-refreshing of the banner for the given ad unit identifier. + /// + /// Ad unit identifier of the banner for which to start auto-refresh. Must not be null. + public static void StartBannerAutoRefresh(string adUnitIdentifier) + { + MaxSdkLogger.UserDebug("Starting banner auto refresh."); + } + + /// + /// Pauses auto-refreshing of the banner for the given ad unit identifier. + /// + /// Ad unit identifier of the banner for which to stop auto-refresh. Must not be null. + public static void StopBannerAutoRefresh(string adUnitIdentifier) + { + MaxSdkLogger.UserDebug("Stopping banner auto refresh."); + } + + /// + /// Updates the position of the banner to the new position provided. + /// + /// The ad unit identifier of the banner for which to update the position. Must not be null. + /// A new position for the banner. Must not be null. + public static void UpdateBannerPosition(string adUnitIdentifier, BannerPosition bannerPosition) + { + MaxSdkLogger.D("[AppLovin MAX] Updating banner position to '" + bannerPosition + "' for ad unit id '" + adUnitIdentifier + "'"); + } + + /// + /// Updates the position of the banner to the new coordinates provided. + /// + /// The ad unit identifier of the banner for which to update the position. Must not be null. + /// The X coordinate (horizontal position) of the banner relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the banner relative to the top left corner of the screen. + /// + /// The banner is placed within the safe area of the screen. You can use this to get the absolute position of the banner on screen. + /// + public static void UpdateBannerPosition(string adUnitIdentifier, float x, float y) + { + MaxSdkLogger.UserDebug("Updating banner position to '(" + x + "," + y + ")"); + } + + /// + /// Overrides the width of the banner in points/dp. + /// + /// The ad unit identifier of the banner for which to override the width for. Must not be null. + /// The desired width of the banner in points/dp + public static void SetBannerWidth(string adUnitIdentifier, float width) + { + // NOTE: Will implement in a future release + MaxSdkLogger.D("[AppLovin MAX] Set banner width to '" + width + "' for ad unit id '" + adUnitIdentifier + "'"); + } + + /// + /// Show banner at a position determined by the 'CreateBanner' call. + /// + /// Ad unit identifier of the banner to show. Must not be null. + public static void ShowBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show banner"); + + if (!IsAdUnitRequested(adUnitIdentifier)) + { + MaxSdkLogger.UserWarning("Banner '" + adUnitIdentifier + "' was not created, can not show it"); + } + else + { + GameObject stubBanner; + if (StubBanners.TryGetValue(adUnitIdentifier, out stubBanner)) + { + stubBanner.SetActive(true); + } + } + } + + /// + /// Remove banner from the ad view and destroy it. + /// + /// Ad unit identifier of the banner to destroy. Must not be null. + public static void DestroyBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "destroy banner"); + + GameObject stubBanner; + if (StubBanners.TryGetValue(adUnitIdentifier, out stubBanner)) + { + Object.Destroy(stubBanner); + StubBanners.Remove(adUnitIdentifier); + } + } + + /// + /// Hide banner. + /// + /// Ad unit identifier of the banner to hide. Must not be null. + public static void HideBanner(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "hide banner"); + + GameObject stubBanner; + if (StubBanners.TryGetValue(adUnitIdentifier, out stubBanner)) + { + stubBanner.SetActive(false); + } + } + + /// + /// Set non-transparent background color for banners to be fully functional. + /// + /// Ad unit identifier of the banner to set background color for. Must not be null. + /// A background color to set for the ad. Must not be null. + public static void SetBannerBackgroundColor(string adUnitIdentifier, Color color) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set background color"); + + GameObject stubBanner; + if (StubBanners.TryGetValue(adUnitIdentifier, out stubBanner)) + { + stubBanner.GetComponentInChildren().color = color; + } + } + + /// + /// Set an extra parameter for the banner ad. + /// + /// Ad unit identifier of the banner to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetBannerExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner extra parameter"); + } + + /// + /// Set a local extra parameter for the banner ad. + /// + /// Ad unit identifier of the banner to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the local extra parameter. + public static void SetBannerLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner local extra parameter"); + } + + /// + /// The custom data to tie the showing banner ad to, for ILRD and rewarded postbacks via the {CUSTOM_DATA} macro. Maximum size is 8KB. + /// + /// Banner ad unit identifier of the banner to set the custom data for. Must not be null. + /// The custom data to be set. + public static void SetBannerCustomData(string adUnitIdentifier, string customData) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set banner custom data"); + } + + /// + /// The banner position on the screen. When setting the banner position via or , + /// the banner is placed within the safe area of the screen. This returns the absolute position of the banner on screen. + /// + /// Ad unit identifier of the banner for which to get the position on screen. Must not be null. + /// A representing the banner position on screen. + public static Rect GetBannerLayout(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "get banner layout"); + return Rect.zero; + } + + #endregion + + #region MRECs + + /// + /// Create a new MREC. + /// + /// Ad unit identifier of the MREC to create. Must not be null. + /// MREC position. Must not be null. + public static void CreateMRec(string adUnitIdentifier, AdViewPosition mrecPosition) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create MREC"); + RequestAdUnit(adUnitIdentifier); + + ExecuteWithDelay(1f, () => + { + var placement = MaxSdkUtils.GetStringFromDictionary(MRecPlacements, adUnitIdentifier); + var eventProps = Json.Serialize(CreateBaseEventPropsDictionary("OnMRecAdLoadedEvent", adUnitIdentifier, placement)); + MaxSdkCallbacks.ForwardEvent(eventProps); + }); + } + + /// + /// Create a new MREC with a custom position. + /// + /// Ad unit identifier of the MREC to create. Must not be null. + /// The X coordinate (horizontal position) of the MREC relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the MREC relative to the top left corner of the screen. + /// + /// The MREC is placed within the safe area of the screen. You can use this to get the absolute position Rect of the MREC on screen. + /// + public static void CreateMRec(string adUnitIdentifier, float x, float y) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "create MREC"); + RequestAdUnit(adUnitIdentifier); + } + + /// + /// Load a new MREC ad. + /// NOTE: The method loads the first MREC ad and initiates an automated MREC refresh process. + /// You only need to call this method if you pause MREC refresh. + /// + /// Ad unit identifier of the MREC to load. Must not be null. + public static void LoadMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load MREC"); + + ExecuteWithDelay(1f, () => + { + var placement = MaxSdkUtils.GetStringFromDictionary(MRecPlacements, adUnitIdentifier); + var eventProps = Json.Serialize(CreateBaseEventPropsDictionary("OnMRecAdLoadedEvent", adUnitIdentifier, placement)); + MaxSdkCallbacks.ForwardEvent(eventProps); + }); + } + + /// + /// Set the MREC placement for an ad unit identifier to tie the future ad events to. + /// + /// Ad unit identifier of the MREC to set the placement for. Must not be null. + /// Placement to set + public static void SetMRecPlacement(string adUnitIdentifier, string placement) + { + MRecPlacements[adUnitIdentifier] = placement; + MaxSdkLogger.UserDebug("Setting MREC placement to '" + placement + "' for ad unit id '" + adUnitIdentifier + "'"); + } + + /// + /// Starts or resumes auto-refreshing of the MREC for the given ad unit identifier. + /// + /// Ad unit identifier of the MREC for which to start auto-refresh. Must not be null. + public static void StartMRecAutoRefresh(string adUnitIdentifier) + { + MaxSdkLogger.UserDebug("Starting banner auto refresh."); + } + + /// + /// Pauses auto-refreshing of the MREC for the given ad unit identifier. + /// + /// Ad unit identifier of the MREC for which to stop auto-refresh. Must not be null. + public static void StopMRecAutoRefresh(string adUnitIdentifier) + { + MaxSdkLogger.UserDebug("Stopping banner auto refresh."); + } + + /// + /// Updates the position of the MREC to the new position provided. + /// + /// The ad unit identifier of the MREC for which to update the position. Must not be null. + /// A new position for the MREC. Must not be null. + public static void UpdateMRecPosition(string adUnitIdentifier, AdViewPosition mrecPosition) + { + MaxSdkLogger.UserDebug("Updating MREC position to '" + mrecPosition + "' for ad unit id '" + adUnitIdentifier + "'"); + } + + /// + /// Updates the position of the MREC to the new coordinates provided. + /// + /// The ad unit identifier of the MREC for which to update the position. Must not be null. + /// The X coordinate (horizontal position) of the MREC relative to the top left corner of the screen. + /// The Y coordinate (vertical position) of the MREC relative to the top left corner of the screen. + /// + /// The MREC is placed within the safe area of the screen. You can use this to get the absolute position Rect of the MREC on screen. + /// + public static void UpdateMRecPosition(string adUnitIdentifier, float x, float y) + { + MaxSdkLogger.UserDebug("Updating MREC position to '(" + x + "," + y + ")"); + } + + /// + /// Show MREC at a position determined by the 'CreateMRec' call. + /// + /// Ad unit identifier of the MREC to show. Must not be null. + public static void ShowMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show MREC"); + + if (!IsAdUnitRequested(adUnitIdentifier)) + { + MaxSdkLogger.UserWarning("MREC '" + adUnitIdentifier + "' was not created, can not show it"); + } + } + + /// + /// Remove MREC from the ad view and destroy it. + /// + /// Ad unit identifier of the MREC to destroy. Must not be null. + public static void DestroyMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "destroy MREC"); + } + + /// + /// Hide MREC. + /// + /// Ad unit identifier of the MREC to hide. Must not be null. + public static void HideMRec(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "hide MREC"); + } + + /// + /// Set an extra parameter for the MREC ad. + /// + /// Ad unit identifier of the MREC to set the extra parameter for. Must not be null. + /// The key for the extra parameter. Must not be null. + /// The value for the extra parameter. + public static void SetMRecExtraParameter(string adUnitIdentifier, string key, string value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC extra parameter"); + } + + /// + /// Set a local extra parameter for the MREC ad. + /// + /// Ad unit identifier of the MREC to set the local extra parameter for. Must not be null. + /// The key for the local extra parameter. Must not be null. + /// The value for the local extra parameter. + public static void SetMRecLocalExtraParameter(string adUnitIdentifier, string key, object value) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC local extra parameter"); + } + + /// + /// The custom data to tie the showing MREC ad to, for ILRD and rewarded postbacks via the {CUSTOM_DATA} macro. Maximum size is 8KB. + /// + /// MREC Ad unit identifier of the banner to set the custom data for. Must not be null. + /// The custom data to be set. + public static void SetMRecCustomData(string adUnitIdentifier, string customData) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "set MREC custom data"); + } + + /// + /// The MREC position on the screen. When setting the MREC position via or , + /// the MREC is placed within the safe area of the screen. This returns the absolute position of the MREC on screen. + /// + /// Ad unit identifier of the MREC for which to get the position on screen. Must not be null. + /// A representing the banner position on screen. + public static Rect GetMRecLayout(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "get MREC layout"); + return Rect.zero; + } + + #endregion + + #region Interstitials + + /// + /// Start loading an interstitial. + /// + /// Ad unit identifier of the interstitial to load + public static void LoadInterstitial(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "load interstitial"); + RequestAdUnit(adUnitIdentifier); + + ExecuteWithDelay(1f, () => + { + AddReadyAdUnit(adUnitIdentifier); + + var eventProps = Json.Serialize(CreateBaseEventPropsDictionary("OnInterstitialLoadedEvent", adUnitIdentifier)); + MaxSdkCallbacks.ForwardEvent(eventProps); + }); + } + + /// + /// Check if interstitial ad is loaded and ready to be displayed. + /// + /// Ad unit identifier of the interstitial to load + /// True if the ad is ready to be displayed + public static bool IsInterstitialReady(string adUnitIdentifier) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "check interstitial loaded"); + + if (!IsAdUnitRequested(adUnitIdentifier)) + { + MaxSdkLogger.UserWarning("Interstitial '" + adUnitIdentifier + + "' was not requested, can not check if it is loaded"); + return false; + } + + return IsAdUnitReady(adUnitIdentifier); + } + + /// + /// Present loaded interstitial for a given placement to tie ad events to. Note: if the interstitial is not ready to be displayed nothing will happen. + /// + /// Ad unit identifier of the interstitial to load + /// The placement to tie the showing ad's events to + /// The custom data to tie the showing ad's events to. Maximum size is 8KB. + public static void ShowInterstitial(string adUnitIdentifier, string placement = null, string customData = null) + { + ValidateAdUnitIdentifier(adUnitIdentifier, "show interstitial"); + + if (!IsAdUnitRequested(adUnitIdentifier)) + { + MaxSdkLogger.UserWarning( + "Interstitial '" + adUnitIdentifier + "' was not requested, can not show it"); + return; + } + + if (!IsInterstitialReady(adUnitIdentifier)) + { + MaxSdkLogger.UserWarning("Interstitial '" + adUnitIdentifier + "' is not ready, please check IsInterstitialReady() before showing."); + return; + } + + RemoveReadyAdUnit(adUnitIdentifier); + + if (_showStubAds) + { + ShowStubInterstitial(adUnitIdentifier, placement); + } + } + + private static void ShowStubInterstitial(string adUnitIdentifier, string placement) + { +#if UNITY_EDITOR + var prefabPath = MaxSdkUtils.GetAssetPathForExportPath("MaxSdk/Prefabs/Interstitial.prefab"); + var interstitialPrefab = AssetDatabase.LoadAssetAtPath(prefabPath); + var stubInterstitial = Object.Instantiate(interstitialPrefab, Vector3.zero, Quaternion.identity); + var interstitialText = GameObject.Find("MaxInterstitialTitle").GetComponent(); + var closeButton = GameObject.Find("MaxInterstitialCloseButton").GetComponent